<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {
	

	/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            10-05-2017 
     
     */ 
	 function __construct() {
		  parent::__construct();
       
        $this->load->model('User_model');
        $this->load->library('form_validation');
     	$this->userid = $this->session->userdata('id');
		$this->username = $this->session->userdata('username');
        $this->role = $this->session->userdata('role');
		$this->status = $this->session->userdata('status');
		$this->taluk = $this->session->userdata('taluk_id');
		$this->panchayath = $this->session->userdata('panchayath');
		$this->district = $this->session->userdata('district');
		
       

          
    }
	/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            9-05-2017 
     	Description : loGIN
     */  
	public function index()
	{
		$this->load->view('login');
	}
	/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            9-05-2017 
     	Description : 	Check user 
     */  
	public function check_user()
    {  
		
        if(!$_POST)
        {
            
			redirect('user');
        }
		
    	 //$data['email'] = $this->input->post('email');
		 $data['username'] = $this->input->post('username');
      	 $data['password'] = $this->input->post('password');
		
        $this->form_validation->set_message('required', '%s Required');
        //$this->form_validation->set_rules('email', 'email', 'required|trim|valid_email');
        $this->form_validation->set_rules('username', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');
        if ($this->form_validation->run() == FALSE) 
        {
            
            redirect('user');// redirect to login page
        }
        else 
        {    
             $data['user'] = $this->User_model->login_data($data);                
             $count = count($data['user']); 
			 

             if($count > 0){ 
					 
					foreach ($data['user'] as $ud) 
						{
							$id = $ud['id'];
							$name = $ud['name'];
							$username = $ud['username'];
							$role = $ud['role'];
							$taluk = $ud['taluk_id'];
							$panchayath = $ud['panchayath_id'];
							$district = $ud['district_id'];
							
						}
						$newdata = array(
								'id' => $id,
								'name' => $name,
								'username' =>$username,
								'role' => $role,
								'taluk' =>$taluk,
								'panchayath' => $panchayath,
								'district' => $district,
							 );

						$this->session->set_userdata($newdata);
						redirect('dashboard');
						
					}
				else{
					$this->session->set_flashdata('er', '<label class="text-danger">Invalid login. Please try again.</label>');
					$this->load->view('login');
					}
            
          } 
    }
    /**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            9-05-2017 
     	Description : User Edit
     */  
	function edit_user()
        {
           if($this->role == TALUK || $this->role == PANCHAYATH)
		  	{
            
            $data['id']=$this->uri->segment(2);
            if(is_numeric($data['id']))
	         { 
	            
                $data['user']=$this->User_model->check_user($data);
				if($data['user'])
                {	$data['taluk_all']=$this->User_model->taluk();
                    $this->load->view('header');
                    $this->load->view('user_edit',$data);
                }
            }else{
            		redirect('dashboard');
	            
            }
            
        	}else
            {
                redirect('user');
            }
        }
        /**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            9-05-2017 
     	Description : User Edit
     */ 
		 function edit_user_change()
        {
            if($_POST)
            {
            $d['id']=$this->input->post('id');
            $data['name']=$this->input->post('name');
            $data['username']=$this->input->post('username');
            $data['taluk']=$this->input->post('taluk');
        	$data['panchayath']=$this->input->post('panchayath');
            
            
            
            $this->form_validation->set_message('required', '%s Required');
            $this->form_validation->set_rules('username', 'username', 'required|trim|valid_email');
            $this->form_validation->set_error_delimiters('', '');
            if ($this->form_validation->run() == FALSE) 
			{

            $data['user']=$this->User_model->check_user($d);
            $data['taluk_all']=$this->User_model->taluk();
            $this->load->view('header');
            $this->load->view('user_edit',$data);

            }else
            {
               
                
                $returnFlag=$this->User_model->update_user_details($data,$d['id']); 
                $data['taluk_all']=$this->User_model->taluk();
                 if ($returnFlag) {

                    
                        $this->session->set_flashdata('err', '<label class="success">User Edited Successfully...</label>');
                      
                        $data['user']=$this->User_model->check_user($d);
                        $this->load->view('header');
                        $this->load->view('user_edit',$data);

                 }else
                 {
                        $this->session->set_flashdata('err', '<label class="text-danger">No Updation Done...</label>');
                        
                        $data['user']=$this->User_model->check_user($d);
                        $this->load->view('header');
                        $this->load->view('user_edit',$data);
                 }
            }

            }
        else
        {
            redirect('user_list','refresh');
        }
    }
		
		
		
	/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            9-05-2017 
     	Description :Admin dashboard
     */ 
	 function admin_dashboard()
		{
			
		    	if($this->userid == '')
				{
					
				redirect('user');
				}
	
				 $role=$this->role;
				 $result=$this->User_model->get_all_count($role);
				 
				 /*$chart_details=$this->User_model->taluk();
				 $survey='';
				 foreach ($chart_details as $key) {
				 	$condition="user_data.taluk_name= ".$key['id'];
				 	$survey_count=$this->User_model->count_detail('user_data',$condition);
				 	$survey.="['".$key['taluk_name']."',".$survey_count."],";
				 }
				 $result['chart']=rtrim($survey,',');*/
				 $this->load->view('header');
				 $this->load->view('admin_dashboard',$result);
				 $this->load->view('footer');
		}				
				
	/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            9-05-2017 
     	Description :Admin dashboard
     */ 
	 public function user_list()
	    {  
		
		  if(($this->role == TALUK) || ($this->role == PANCHAYATH))
		  {
			 
			  $data['user_type'] = $this->uri->segment(3);
			  $this->load->view('header');
			  $this->load->view('user_list',$data);
		  }else
		  {
			  
		  	 redirect('user');
		  
		  }
	 	}
		
		
		function get_users_list()
		{
			
			$data=array();            
			$data['id'] = $this->userid;
			$data['role'] = $this->role;
			$data['status'] = $this->status;
			$joins = array(
						array(
						'table' => 'panchayath',
						'condition' => 'panchayath.id=login.panchayath',
						'jointype' => 'LEFT'
						),	 
						array(
						'table' => 'taluk_all',
						'condition' => 'taluk_all.id=login.taluk',
						'jointype' => 'LEFT'
						),
					  );
	
			$select_condtion = array(              
				  array(
					'key' => 'login.role',
					'value' => AGENT
					), 
					array(
					'key' => 'login.status',
					'value' => ACTIVE
					)
			);
			if($data['role'] == TALUK)
			{
				$select_condtion[] =              
				  array(
					'key' => 'login.taluk',
					'value' => $this->taluk
					);
			}
			if($data['role'] == PANCHAYATH)
			{
				$select_condtion[] =              
				  array(
					'key' => 'login.panchayath',
					'value' => $this->panchayath
					);	
			}
        	$category_array = array();
			// Give the table fields for searching with datatable search area
			
			$search_value = $_POST['search_text'];
						//$search_value='';
			$user_type = '';
			$districts = '';
			$searchQuery = '';
			$searchQuery1 = '';
			
			$search_like = array('name','username');
			
			// limit for search
			
		   

			$limit = array('start' => $_POST['start'] , 'length' => $_POST['length']);
			// Group clause
			$order_by = array('key' => 'login.id', 'type' => 'desc');
			$select_fields ='SQL_CALC_FOUND_ROWS null as rows,login.id,login.name,login.username,taluk_all.taluk_name,panchayath.panchayath_name';
			$data = $this->User_model->common_get_pipeline('login',$select_fields,$select_condtion,$search_value,$user_type,$districts,$searchQuery,$searchQuery1,$search_like,$joins,$limit,$order_by,'',$category_array);
			
			echo $data;
			
			
		}
		public function user_form()
		{
		  $data['user_id']=$this->userid;
		  $data['role_id']=$this->role;

		  if($data['role_id'] == TALUK || $data['role_id'] == PANCHAYATH)
		  {
			
		 	$data['taluk_all']=$this->User_model->taluk();
		 	$data['taluk']=$this->taluk;
		 	$data['panchayath']=$this->panchayath;
	        $this->load->view('header');
			$this->load->view('user_form',$data);
		  }else
		  {
		  	  redirect('user');
		  
		  }
		  
		}

		public function get_panchayath()
		{
		  	$taluk_id=$this->input->post('taluk_id');
        	$panchayath=$this->User_model->get_panchayath_tatuk($taluk_id);
       		echo json_encode($panchayath);
		  
		}
		 function change_password()
    	{
    	
    	$data['old_password'] = $this->input->post('old_password');
        $data['password'] = $this->input->post('password');
        $data['confirm_pass'] = $this->input->post('confirm_pass');
       	$data['id'] = $this->session->userdata('id');

        $this->form_validation->set_rules('old_password', 'Old password', 'required');
        $this->form_validation->set_rules('password', 'New Password', 'required');
        $this->form_validation->set_rules('confirm_pass', 'Confirm New Password', 'required');

        $user_details = $this->User_model->check_user($data);

        if ($this->form_validation->run() == FALSE) {
           
        	$this->load->view('header');
            $this->load->view('change_password');


        } else {
            if ($data['confirm_pass'] == $data['password']) {
            	
            	$enc_pass=md5($data['old_password']);
                if ($user_details['password'] == $enc_pass) {

                	$update_arr=array('password'=> md5($data['password']) );
                    $result = $this->User_model->update_user_details($update_arr,$data['id']);
					
                    if ($result) {
                        $this->session->set_flashdata('error', '<label class="success">Password changed successfully</label>');
                        redirect('user/changepassword');
                    } else {
                        $this->session->set_flashdata('error', '<label class="text-danger">Password not updated</label>');
                        redirect('user/changepassword');
                    }
                } else {
                    $this->session->set_flashdata('error', '<label class="text-danger">Old password does not match</label>');
                    redirect('user/changepassword');
                }
            } else {
                $this->session->set_flashdata('error', '<label class="text-danger">Please specify your New Password Again</label>');
                redirect('user/changepassword');
            }
        }
    }
		
		
	 
    function changepassword()
    {
        if($this->userid == '')
        {
            redirect('user');
        }
    	$this->load->view('header'); 
        $this->load->view('change_password');
    }
	
    
    function logout()
    {
        
        $array_items = array('id', 'username','role');
        $this->session->unset_userdata($array_items);
		
        redirect('user','refresh');
    }
			/**
			 Auther:: Reshma Rajan
			 19/11/16
			 */
			 
	 public function delete_user()
	{
		
		if($_POST)
				{
				$user_id    = $this->input->post('user_id');
				$arr = array(
					'status'=> DELETE,
				
				  );
		       $return = $this->User_model->update_user_details($arr,$user_id);
			   
				}else
				{
					
					redirect('user_list','refresh');
				}
	}
		public function changeStatus()
			{
				
				if($_POST)
					{
					$user_id   = $this->input->post('user_id');
					$status    = $this->input->post('status');
					if($status == ACTIVE)
						{
							$arr = array('status'=> INACTIVE);
						}
					if($status == INACTIVE)
						{
							$arr = array('status'=> ACTIVE);
						}	
				   $return = $this->User_model->update_user_status($arr,$user_id);
				   
					}else
					{
						
						redirect('user_list','refresh');
					}
			}
	   public function change_password_admin()
		{
			
			if($this->role != ADMIN)
			{
				
				redirect('user');
			}
			$data['id']=$this->input->post('uid');
			$data['password']=$this->input->post('password');
			$data['confirm_pass']=$this->input->post('confirm_pass');
			if(isset($data['id']) && ($data['id'] != '') && isset($data['password']) && ($data['password'] != ''))
			{
				if($data['password'] == $data['confirm_pass'])
				{
					$arr=array('password'=>md5($data['password']));
					$result=$this->User_model->update_user_details($arr,$data['id']);
					
					if($result)
					{
						echo 'SUCCESS';
					}else
					{
						echo 'NO_UPDATION';
					}

				}else
				{
					echo 'MIS_MATCH';
				}
			}else
			{
				echo 'FAIL';
			}
    }

	public function insert_users()
	{
		
	if(!$_POST)
		{
			
			redirect('user');
		}
		$data['name']=$this->input->post('name');
		$data['username']=$this->input->post('username');
		$data['password']=$this->input->post('password');
		$data['confirm_password']=$this->input->post('confirm_password');
		$data['taluk']=$this->input->post('taluk');
        $data['panchayath']=$this->input->post('panchayath');
         $data['taluk_all']=$this->User_model->taluk();
         $data['role']=AGENT;
		$this->form_validation->set_rules('name', 'name', 'required');
		$this->form_validation->set_rules('username', 'username', 'trim|valid_email');
		$this->form_validation->set_rules('password', 'password', 'required|min_length[6]|matches[confirm_password]');
		$this->form_validation->set_rules('confirm_password', 'confirm_password', 'required|min_length[6]');
	//	$this->form_validation->set_rules('taluk', 'taluk', 'required');
	//	$this->form_validation->set_rules('panchayath', 'panchayath', 'required');
//			$this->form_validation->set_rules('role', 'role', 'required');
		$this->form_validation->set_error_delimiters('', '');
		if ($this->form_validation->run() == FALSE) 
				{
					

				$this->load->view('header');
				$this->load->view('user_form',$data);
					 
				}
			 else
				{
				$returnFlag=$this->User_model->insert_users($data);
								
				if ($returnFlag != '' && $returnFlag != 2)
					{
					$this->session->set_flashdata('err', '<label class="success">User Added Successfully...</label>'); 
					redirect('user_form');

					}
					 else
					 {
						$this->session->set_flashdata('err', '<label class="text-danger">username already exists...</label>');
						$this->load->view('header');
						$this->load->view('user_form',$data);
					 }
				}

	}
			
		/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            23-05-2017 
     	Description :taluk details
     */ 
	 public function agent()
	    {  
		
		  if($this->role == ADMIN || $this->role == DISTRICT_AGENT)
			  {
				  $data['district_all']	=	$this->User_model->getLocation('district','','');
				  $data['user_type'] 	= 	$this->uri->segment(3);
				  $data['district']  	= 	$this->district;
				  $data['role']  		= 	$this->role;
				  
				  $this->load->view('header');
				  $this->load->view('taluk_members',$data);
				  
			  }
			else{
				
				redirect('user');
			}  
	 	}
	       /**
     * CodeIgniter
     * @package         
     * @author          Arun
     * @since           Version 1.0
     * Description:     Excel upload function
     */
    function excel_upload1()
    {
    	$this->load->view('header');
		$this->load->view('excel_upload');		  
    }
      /**
     * CodeIgniter
     * @package         
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            8-03-2017 
     * Description:     Excel upload function
     */
    function do_file_upload()
    {
    	$this->load->helper('upload');
    	$server_type = $_SERVER["REMOTE_ADDR"];
        if($server_type =='127.0.0.1') 
		{
			$target_dir = 'uploads/excel/';
		}
		else
		{
			//$target_dir = $_SERVER['DOCUMENT_ROOT'].'/demo/kudumbasree/uploads/excel/';
			$target_dir = 'uploads/excel/';
		}
		echo '<pre>';print_r($_FILES);die;
        if (move_uploaded_file($_FILES['attachment']['tmp_name'],$target_dir. $_FILES["attachment"]['name'])) {
		    echo "Uploaded";
		} else {
		   echo "File was not uploaded";
		   $this->session->set_flashdata('err', '<div class="alert alert-danger" role="alert"><label>Invalid file format or exceeded file size limit</label></div>');
		   redirect('agent-bulk-upload');
		} 
		
		
        
        //$target_dir = $_SERVER['DOCUMENT_ROOT'].'/uploads/excel/';
        $file_name = $target_dir.$_FILES["attachment"]['name'];
        if($file_name != '')
	        {              
		        $path 			=	'uploads/excel/'.$file_name;
		        $this->load->library('Excel'); 
		        //EXCEL_PATH_LIVE        
		        $objPHPExcel 	= 	PHPExcel_IOFactory::load($file_name);  
		        $totalrows 		=	$objPHPExcel->setActiveSheetIndex(0)->getHighestRow();//Count Numbe of rows avalable in excel      	 
		         $objWorksheet 	=	$objPHPExcel->setActiveSheetIndex(0);        
		         for($i=0;$i<=13;$i++)
		          {
		          	if($objWorksheet->getCellByColumnAndRow($i) !='')
			          	{
							$fields[]	= 	trim($objWorksheet->getCellByColumnAndRow($i));		
						}			  
		          }
				$data['file_name'] 		= 	$file_name;
		        $data['excel_fields'] 	= 	$fields;
				$this->load->view('header');
				$this->load->view('sort_table_fields',$data);
	        }
        else
        	{
                $this->session->set_flashdata('err', '<div class="alert alert-danger" role="alert"><label>Invalid file format or exceeded file size limit</label></div>');
                redirect('agent-bulk-upload');
            }
    }
            /**
     * CodeIgniter
     * @package         
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            8-03-2017 
     * Description:     Excel import function
     */
    public function import_content()
    {
		
    	$data['user_id'] = $this->userid;
    	$this->load->helper('upload');
    	$this->load->model('User_model');
    	
        $file_name 		= 	trim($this->input->post('file_name'));
        $name 			= 	trim($this->input->post('name'));
        $email 			= 	trim($this->input->post('email'));//email
        $username 		= 	trim($this->input->post('username'));
        $place_category = 	trim($this->input->post('place_category'));
        $district_id 	= 	trim($this->input->post('district_id'));

        $taluk_id 		= 	trim($this->input->post('taluk_id'));
        $block_id 		= 	trim($this->input->post('block_id'));
        $corporation 	= 	trim($this->input->post('corporation'));
        $muncipality 	= 	trim($this->input->post('muncipality'));
        $cds 			= 	trim($this->input->post('cds'));
        $ads 			= 	trim($this->input->post('ads'));
        $constitution 	= 	trim($this->input->post('constitution'));
        $panchayath_id 	= 	trim($this->input->post('panchayath'));

		
		//echo '<pre>';print_r($this->input->post());	
        $path 			= 	'uploads/excel/'.$file_name; 
        $this->load->library('Excel');

        $server_type = $_SERVER["REMOTE_ADDR"];
        if($server_type =='127.0.0.1') 
		{
			$target_dir = '/uploads/excel/';
		}
		else
		{
			//$target_dir = $_SERVER['DOCUMENT_ROOT'].'/demo/kudumbasree/uploads/excel/';
			$target_dir = '/uploads/excel/';
		}

         
         $objPHPExcel 	= 	PHPExcel_IOFactory::load($file_name);  
         //echo '<pre>';print_r($objPHPExcel); 
         $totalrows 	=	$objPHPExcel->setActiveSheetIndex(0)->getHighestRow();   //Count Numbe of rows avalable in excel      	 
         $objWorksheet 	=	$objPHPExcel->setActiveSheetIndex(0); 
         $k 			=	1;
         $agt =0;
         $ex =0;
         $a =1;
	
         /*echo '<pre>';print_r($totalrows);
         echo '<br>'.'=======================#####============================';
         echo '<pre>';print_r($objWorksheet);
         echo '<br>'.'=======================@@@@@============================';*/
        for($i=2;$i<=300;$i++)
        {
			$details = array();
			if($panchayath_id != ''){          		
                $panchayath_data = trim($objWorksheet->getCellByColumnAndRow($panchayath_id,$i)->getValue());//$this->spreadsheet_excel_reader->val($i,$name));
                if($panchayath_data !='nil' && $panchayath_data != '')
					{
						$exist  	=	"name= '".$panchayath_data."' and  type='panchayath'"; 
						$details 	=	$this->User_model->get_datum('location_settings_master','name',$exist,TRUE);
						if(isset($details) && !empty($details))
						{                          
							 $panchayath_data = $this->User_model->getLocationByName($panchayath_data,'panchayath');
							
							 if(!empty($panchayath_data))
								{
									$data['panchayath_id']=$panchayath_data['id'];
								}  
							 else
								{
									$data['panchayath_id']='0';
								}
						}
						else
						{
							$data['panchayath_id']='0';
						}
					}
				else
						{
							$data['panchayath_id']='0';
						}	
             
            }else
            {
                $data['panchayath_id']='0';
            }
          	if($block_id != ''){          		
                $block_data = trim($objWorksheet->getCellByColumnAndRow($block_id,$i)->getValue());//$this->spreadsheet_excel_reader->val($i,$name));
                if($block_data !='nil' && $block_data != '')
					{
						$exist  	=	"name= '".$block_data."' and  type='block'"; 
						$details 	=	$this->User_model->get_datum('location_settings_master','name',$exist,TRUE);
						if(isset($details) && !empty($details))
						{                          
							 $block_data = $this->User_model->getLocationByName($block_data,'block');
							 // print_r($block_data);die;
							 if(!empty($block_data))
								{
									$data['block_id']=$block_data['id'];
								}  
							 else
								{
									$data['block_id']='0';
								}
						}
						else
						{
							$data['block_id']='0';
						}
					}
				else
						{
							$data['block_id']='0';
						}	
             
            }else
            {
                $data['block_id']='0';
            }
            if($corporation != ''){
          		
                $corporation_data = trim($objWorksheet->getCellByColumnAndRow($corporation,$i)->getValue());//$this->spreadsheet_excel_reader->val($i,$name));
                if($corporation_data != 'nil' && $corporation_data != '')
					{
						$exist  	=	"name= '".$corporation_data."' and  type='corporation'"; 
						$details 	=	$this->User_model->get_datum('location_settings_master','name',$exist,TRUE);
						if(isset($details) && !empty($details))
						{                          
							 $corporation_data = $this->User_model->getLocationByName($corporation_data,'corporation');
							 if(!empty($corporation_data))
								{
									$data['corporation']=$corporation_data['id'];
								}  
							 else
								{
									$data['corporation']='0';
								}
						}
						else
						{
							$data['corporation']='0';
						}
					}
				else
					{
						$data['corporation']='0';
					}
            }else
            {
                $data['corporation']='0';
            }
            if($muncipality != ''){
          		
                $muncipality_data = trim($objWorksheet->getCellByColumnAndRow($muncipality,$i)->getValue());//$this->spreadsheet_excel_reader->val($i,$name));
                if($muncipality_data != 'nil' && $muncipality_data != '')
				{
					$exist  	=	"name= '".$muncipality_data."' and  type='muncipality'"; 
					$details 	=	$this->User_model->get_datum('location_settings_master','name',$exist,TRUE);
					if(isset($details) && !empty($details))
					{                          
						 $muncipality_data = $this->User_model->getLocationByName($muncipality_data,'muncipality');
						 if(!empty($muncipality_data))
							{
								$data['muncipality']=$muncipality_data['id'];
							}  
						 else
							{
								$data['muncipality']='0';
							}
					}
					else
					{
						$data['muncipality']='0';
					}
				}
			else
				{
					$data['muncipality']='0';
				}
             
            }else
            {
                $data['muncipality']='0';
            }
            if($cds != ''){
          		
                $data['cds'] = trim($objWorksheet->getCellByColumnAndRow($cds,$i)->getValue());//$this->spreadsheet_excel_reader->val($i,$name));
             
            }else
            {
                $data['cds']='';
            }
            if($ads != ''){
          		
                $data['ads'] = trim($objWorksheet->getCellByColumnAndRow($ads,$i)->getValue());//$this->spreadsheet_excel_reader->val($i,$name));
             
            }else
            {
                $data['ads']='';
            }
            if($constitution != ''){
          		
                $data['constitution'] = trim($objWorksheet->getCellByColumnAndRow($constitution,$i)->getValue());//$this->spreadsheet_excel_reader->val($i,$name));
             
            }else
            {
                $data['constitution']='';
            }
          	if($name != ''){
          		
                $data['name'] = trim($objWorksheet->getCellByColumnAndRow($name,$i)->getValue());//$this->spreadsheet_excel_reader->val($i,$name));
             
            }else
            {
                $data['name']='';
            }
          	if($email != '' && !empty($email)){
          		
				$data['email']='';
                $data['email'] = trim($objWorksheet->getCellByColumnAndRow($email,$i)->getValue());//$this->spreadsheet_excel_reader->val($i,$name));
				if($data['email'] == 'nill')
				{
					$data['email']='';
				}
				if(!empty($data['email']))
					{
						$data['email']=$data['email'];
					}
				
            }
			
            if($place_category != ''){
          		
                 $place_category1 = trim($objWorksheet->getCellByColumnAndRow($place_category,$i)->getValue());//$this->spreadsheet_excel_reader->val($i,$name));
       		  if($place_category1 == "Urban")
                {
                	$data['place_category']='2';
                }
				if($place_category1 =='Rural')
                {
                	$data['place_category']='1';
                }
			
            }else
            {
                $data['place_category']='';
            }
			if($district_id != '')
            {
               $district_data = trim($objWorksheet->getCellByColumnAndRow($district_id,$i)->getValue());//trim($this->spreadsheet_excel_reader->val($i,$email));
                if($district_data != 'nil' && $district_data != '')
					{
						$exist  	=	"name= '".$district_data."' and  type='district'";
						$details 	=	$this->User_model->get_datum('location_settings_master','name',$exist,TRUE);
						if(isset($details) && !empty($details))
						{                          
							 $district_data = $this->User_model->getLocationByName($district_data,'district');
							 if(!empty($district_data))
								{
									$data['district_id']=$district_data['id'];
								}  
							 else
								{
									$data['district_id']='0';
								}
						}
						else
						{
							$data['district_id']='0';
						}
					}
				else
					{
						$data['district_id']='0';
					}	
            }
            else
            {
                $data['district_id']='0';
            }
           /* if($taluk_id != ''){
              $taluk_data =trim($objWorksheet->getCellByColumnAndRow($taluk_id,$i)->getValue()); //trim($this->spreadsheet_excel_reader->val($i,$mobile));
              if($taluk_data != 'nil' && $taluk_data != '')
			  {
				 $exist  	=	"name= '".$taluk_data."' and  type='taluk'";				  
				  $details 	=	$this->User_model->get_datum('location_settings_master','name',$exist,TRUE);
				  if(isset($details) && !empty($details))
					{                          
						 $taluk_data = $this->User_model->getLocationByName($taluk_data,'taluk');
						 if(!empty($taluk_data))
							{
								$data['taluk_id']=$taluk_data['id'];
							}  
						 else
							{
								$data['taluk_id']='0';
							}
					}
					else
					{
						$data['taluk_id']='0';
					}
			  }
			  else
					{
						$data['taluk_id']='0';
					
               
            }
			}else
            {
                $data['taluk_id']='0';
            }*/
			//echo $username.'<<>>';
			if($username != ''){
              $data['username'] =trim($objWorksheet->getCellByColumnAndRow($username,$i)->getValue()); //trim($this->spreadsheet_excel_reader->val($i,$mobile));
              if($data['username'] != 'nil' && $data['username'] != '')
			  {
				  $exist  	=	"username= '".$data['username']."'";				  
				  $details 	=	$this->User_model->get_datum('login','username',$exist,TRUE);
				  //echo 'dd';print_r($details);
				  if(!empty($data['username']))
				  {
					  $ex++;
				  }
				  
			  }
			 
			}else
            {
                $data['username']='';
            }
			
		if (!filter_var(trim($data['email']), FILTER_VALIDATE_EMAIL) )
			{
			   $k=0;
			   $data['email'] ='';
			}
			else
			{ 
			$data['email'] =$data['email'];
			}
			if($data['email'] == 'nill')
			{
				$data['email'] = '';
			}
           
			if(empty($details) && !empty($data['username']))
			{			
				$password = hash('SHA512','password',false);						
				$data['password']=$password;
				$arr_mem=array(                               
				   'name'=>$data['name'],
				   'email'=>$data['email'],
				   'username'=>$data['username'],
				   'password'=>$data['password'],
				   'place_category'=>$data['place_category'],
				   'district_id'=>$data['district_id'],
				   //'taluk_id'=>$data['taluk_id'],
				   'block_id'=>$data['block_id'],
				   'panchayath_id'=>$data['panchayath_id'],
				   'corporation'=>$data['corporation'],
				   'muncipality'=>$data['muncipality'],
				   'cds'=>$data['cds'],
				   'ads'=>$data['ads'],
				   'constitution'=>$data['constitution'],
				   'from_source'=>'xls',//xls or api 
				   'status' =>1,
					'role' =>2,//agent
					);
				
				$mem_id=$this->User_model->save('login',$arr_mem);
				   $agt ++; 
				//mal temp
			}
						
				$a++;
            }
            $this->session->set_flashdata('err',' <div class="alert alert-success" role="alert"><label>'.$reg_msg.' Registered.</label></div>');
             redirect('agent');        
                        
        
            
    }
			/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            23-05-2017 
     	Description :taluk details
     */ 
		
	function get_agent_list()
		{
			
			$data				=	array();            
			$data['id'] 		= 	$this->userid;
			$data['role'] 		= 	$this->role;
			$data['district'] 	= 	$this->district;
			$data['status'] 	= 	$this->status;
			$joins 				= 	array(
									array('table' => 'location_settings_master as a','condition' => 'a.id=login.district_id','jointype' => 'LEFT'),
									array('table' => 'location_settings_master as b','condition' => 'b.id=login.taluk_id','jointype' => 'LEFT')
										);	
			$select_condtion 	= 	array(array('key' => 'login.role','value' => 2),array('key' => 'login.status !=','value' => DELETE));
			if($data['role'] == DISTRICT_AGENT)
				{				
					//$select_condtion[]= 	array('key' => 'login.district_id','value' => $this->district);
					$select_condtion 	= 	array(array('key' => 'login.district_id','value' => $this->district),array('key' => 'login.status !=','value' => DELETE),array('key' => 'login.id !=','value' => $this->userid));
				}
			$category_array 	= 	array();
			// Give the table fields for searching with datatable search area
			$search_value 		= '';
			$search_like 		= '';
			$searchQuery 		= 	'';
			if(!empty($_POST['search_text'])  && $_POST['search_text'] !=''  && $_POST['search_text'] !=null)
				{
					$search_value 		= 	$_POST['search_text'];
					$search_like 		= 	array('login.name','login.username');
				}
			if(!empty($_POST['muncipality']) && $_POST['muncipality'] !=''  && $_POST['muncipality'] !=null)
				{
					$search_value 		= 	$_POST['muncipality'];
					//$select_condtion[]= 	array('key' => 'login.muncipality','value' => $search_value);
					$select_condtion 	= 	array(array('key' => 'login.muncipality','value' => $search_value),array('key' => 'login.status !=','value' => DELETE));
				}
			if(!empty($_POST['panchayath']) && $_POST['panchayath'] !=''  && $_POST['panchayath'] !=null)
				{
					$search_value 		= 	$_POST['panchayath'];
					//$select_condtion[]= 	array('key' => 'login.panchayath_id','value' => $search_value);
					$select_condtion 	= 	array(array('key' => 'login.panchayath_id','value' => $search_value),array('key' => 'login.status !=','value' => DELETE));
				}	
			
			$user_type 			= 	'';
			$districts 			= 	'';
			$searchQuery 		= 	'';
			$searchQuery1 		= 	'';			
						
			$limit 				= 	array('start' => $_POST['start'] , 'length' => $_POST['length']);// limit for search 
			$order_by 			= 	array('key' => 'login.id', 'type' => 'desc');// Group clause to_char(login.created_at, "'DD-MON-YYYY'")
			$select_fields 		=	"login.id,login.name,login.email,login.username,to_char(login.created_at, 'DD-MON-YYYY'),login.cds,login.status,login.constitution,login.place_category,login.district_id,login.taluk_id,login.block_id,login.corporation,login.muncipality,login.cds,login.ads,login.cds,login.ads,login.constitution,a.name as d_name,b.name as t_name";
			$data 				= 	$this->User_model->common_get_pipeline('login',$select_fields,$select_condtion,$search_value,$user_type,$districts,$searchQuery,$searchQuery1,$search_like,$joins,$limit,$order_by,'',$category_array);
			
			echo $data;
		}	
			/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            23-05-2017 
     	Description :taluk details
     */ 
	public function panchayath()
	    {  
		 	if($this->role == TALUK || $this->role == ADMIN)
			{
			  $data['user_type'] = $this->uri->segment(3);
			  $this->load->view('header');
			  $this->load->view('panchayath_members',$data);
			}else
			{
				redirect('user');
			}
	 	}
			/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            23-05-2017 
     	Description :taluk details
     */ 
		
		function get_panchayath_list()
		{

			$data=array();            
			$data['id'] = $this->userid;
			$data['role'] = $this->role;
			$data['status'] = $this->status;
			$joins = array(
						array(
						'table' => 'panchayath',
						'condition' => 'panchayath.id=login.panchayath',
						'jointype' => 'LEFT'
						),	 
						array(
						'table' => 'taluk_all',
						'condition' => 'taluk_all.id=login.taluk',
						'jointype' => 'LEFT'
						),
					  );
			
			$select_condtion = array(              
				  array(
					'key' => 'login.role',
					'value' => PANCHAYATH
					), 
					array(
					'key' => 'login.status',
					'value' => ACTIVE
					)
			);
			if($data['role'] == TALUK)
			{
			$select_condtion[] =           
				  array(
					'key' => 'login.taluk',
					'value' => $this->taluk
					);
				
			}
        	$category_array = array();
			// Give the table fields for searching with datatable search area
			
			$search_value = $_POST['search_text'];
						//$search_value='';
			$user_type = '';
			$districts = '';
			$searchQuery = '';
			$searchQuery1 = '';
			
			$search_like = array('name','username');
			
			// limit for search
			
		   

			$limit = array('start' => $_POST['start'] , 'length' => $_POST['length']);
			// Group clause
			$order_by = array('key' => 'login.id', 'type' => 'desc');
			$select_fields ='SQL_CALC_FOUND_ROWS null as rows,login.id,login.name,login.username,taluk_all.taluk_name,panchayath.panchayath_name';
			$data = $this->User_model->common_get_pipeline('login',$select_fields,$select_condtion,$search_value,$user_type,$districts,$searchQuery,$searchQuery1,$search_like,$joins,$limit,$order_by,'',$category_array);
			echo $data;
			
			
		}
				/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            23-05-2017 
     	Description :taluk details
     */ 

	public function insert_agent()
	{	
		
		if($this->role != ADMIN)
		{
			redirect('user');
		}
		$data =array();
		$data['district_all']=$this->User_model->getLocation('district','','');		
		if($this->input->post('submit'))
			{
				$data 					=	array();
				$data['name']			=	$this->input->post('name');
				$data['username']		=	$this->input->post('username');
				$data['email']			=	$this->input->post('email');
				$data['password']		=	$this->input->post('password');
				$data['confirm_password']=	$this->input->post('confirm_password');
				$data['district_id']	=	$this->input->post('district_id');
				$data['muncipality']	=	$this->input->post('sel_muncipality');
				$data['block_id']		=	$this->input->post('sel_block');
				$data['panchayath_id']	=	$this->input->post('sel_panchayath');
				$data['corporation']	=	$this->input->post('sel_corporation');
				$sel1					=	$this->input->post('sel1');
				if($sel1 == 1)$data['place_category'] = 1;
				if($sel1 == 2)$data['place_category'] = 2;
				$data['role']=2;
				$this->form_validation->set_rules('name', 'name', 'required');
				$this->form_validation->set_rules('username', 'username', 'required');
				$this->form_validation->set_rules('email', 'email', 'trim|valid_email');
				$this->form_validation->set_rules('password', 'password', 'required|min_length[6]|matches[confirm_password]');
				$this->form_validation->set_rules('confirm_password', 'confirm_password', 'required|min_length[6]');
				$this->form_validation->set_error_delimiters('', '');
				if ($this->form_validation->run() == FALSE) 
					{
						
						$this->load->view('header');
					//$this->load->view('taluk_form',$data);					 
					}
				else
					{
						$returnFlag=$this->User_model->insert_users($data);
						
						if ($returnFlag != '' && $returnFlag != 2)
							{						
								$this->session->set_flashdata('err', '<label class="success">User Added Successfully...</label>'); 
								//$this->load->view('add-agent',$data);
								redirect('add-agent');
							}
						else
							{
								$this->session->set_flashdata('err', '<label class="text-danger">username already exists...</label>');
								$this->load->view('header');
								//$this->load->view('add-agent',$data);
								redirect('user');
							}
					}

			}
		else
			{
				
				$this->load->view('header');
				$this->load->view('taluk_form',$data);
			}
	}
	function testImage()
	   {
		   
		  //  echo  $file_name = excel_upload(EXCEL_UPLOAD);
			
				 // $imgData =$_FILES["attachment"]["tmp_name"];
				  $imgData =addslashes(file_get_contents($_FILES['attachment']['tmp_name']));
				 // $imgData='dddd';
				  print_r($imgData);
			   // $imageProperties = exif_read_data($_FILES['attachment']['tmp_name']);  
				$imageProperties = getimageSize($_FILES['attachment']['tmp_name']);

					//  $imageProperties = $_FILES["attachment"]['size'];
					  $file_array = array('img_data'=>'0','img_type'=>$imageProperties['mime']);
					   $file_id = $this->User_model->common_insertion('test_image',$file_array);
					  //$sql = "INSERT INTO output_images(imageType ,imageData)
					  //VALUES('{$imageProperties['mime']}', '{$imgData}')";
					   //       echo 'ff';die;
				   }
				   function view_img()
				   {
					$row=$this->User_model->get_image(); 
					//echo $row["imageData"]; 
				  // print_r($row);
				   //header("Content-type: image/png"); 
					//    echo $row['imageData']; 
				$this->load->view('test',$row);

	   }
	public function getLocationDetails()
	{
		
		$type				=	$this->input->post('type');
		$district_id		=	$this->input->post('district_id');
		$action				=	$this->input->post('action');
		$data['location']	=	$this->User_model->getLocation($type,$district_id,$action);
		
		echo json_encode($data);
	}
					/**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            23-05-2017 
     	Description :Panchayath details
     */ 		
	public function insert_panchayath_members()
	{
	
		if($this->role == TALUK || $this->role == ADMIN)
		{
		$data['taluk_all']=$this->User_model->taluk();
		$data['taluk']=$this->taluk;
	    $data['panchayath']=$this->panchayath;
		if($this->input->post('submit'))
		{
			$data['name']=$this->input->post('name');
			$data['username']=$this->input->post('username');
			$data['password']=$this->input->post('password');
			$data['confirm_password']=$this->input->post('confirm_password');
			$data['taluk']=$this->input->post('taluk');
	        $data['panchayath']=$this->input->post('panchayath');
	         $data['taluk_all']=$this->User_model->taluk();
	         $data['role']=PANCHAYATH;
			$this->form_validation->set_rules('name', 'name', 'required');
			$this->form_validation->set_rules('username', 'username', 'trim|valid_email');
			$this->form_validation->set_rules('password', 'password', 'required|min_length[6]|matches[confirm_password]');
			$this->form_validation->set_rules('confirm_password', 'confirm_password', 'required|min_length[6]');
		//	$this->form_validation->set_rules('taluk', 'taluk', 'required');
		//	$this->form_validation->set_rules('panchayath', 'panchayath', 'required');
	//			$this->form_validation->set_rules('role', 'role', 'required');
			$this->form_validation->set_error_delimiters('', '');
			if ($this->form_validation->run() == FALSE) 
					{
						

					$this->load->view('header');
					$this->load->view('panchayath_form',$data);
						 
					}
				 else
					{
					$returnFlag=$this->User_model->insert_users($data); 
					if ($returnFlag != '' && $returnFlag != 2)
						{
						$this->session->set_flashdata('err', '<label class="success">Panchayath Member Added Successfully...</label>'); 
						redirect('new_panchayath_members');

						}
						 else
						 {
							$this->session->set_flashdata('err', '<label class="text-danger">Member Already exists...</label>');
							$this->load->view('header');
							$this->load->view('panchayath_form',$data);
						 }
					}
			}else
			{

				$this->load->view('header');
				$this->load->view('panchayath_form',$data);
			}
		}else{
			redirect('user');
		}	
	}		
	    /**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            24-05-2017 
     	Description : Taluk Member Edit
     */  
	function edit_taluk_member()
        {
           if($this->role != ADMIN)
		  	{
            
                redirect('user');
            }
            if($this->input->post('submit'))
			{
				$d['id']=$this->input->post('id');
	            $data['name']=$this->input->post('name');
	            $data['username']=$this->input->post('username');
	            $data['taluk']=$this->input->post('taluk');
	        	
	            
	            
	            
	            $this->form_validation->set_message('required', '%s Required');
	            $this->form_validation->set_rules('username', 'username', 'required|trim|valid_email');
	            $this->form_validation->set_error_delimiters('', '');
	            if ($this->form_validation->run() == FALSE) 
				{

	            $data['user']=$this->User_model->check_user($d);
	            $data['taluk_all']=$this->User_model->taluk();
	            $this->load->view('header');
	            $this->load->view('edit_taluk',$data);

	            }else
	            {
	               
	                
	                $returnFlag=$this->User_model->update_user_details($data,$d['id']); 
	                $data['taluk_all']=$this->User_model->taluk();
	                 if ($returnFlag) {

	                    
	                        $this->session->set_flashdata('err', '<label class="success">Member Edited Successfully...</label>');
	                        $data['user']=$this->User_model->check_user($d);
	                        $this->load->view('header');
	                        $this->load->view('edit_taluk',$data);

	                 }else
	                 {
	                        $this->session->set_flashdata('err', '<label class="text-danger">No Updation Done...</label>');
	                        $data['user']=$this->User_model->check_user($d);
	                        $this->load->view('header');
	                        $this->load->view('edit_taluk',$data);
	                 }
	            }
			}else
			{
	            $data['id']=$this->uri->segment(2);
	            if(is_numeric($data['id']))
		        { 
		            
	                $data['user']=$this->User_model->check_user($data);
					if($data['user'])
	                {	$data['taluk_all']=$this->User_model->taluk();
	                    $this->load->view('header');
	                    $this->load->view('edit_taluk',$data);
	                }
	            }else
	            {
	            		redirect('dashboard');
		            
	            }
            }
        	
        }
			    /**
     * CodeIgniter
     * @package         Survey
     * @author          Reshma Rajan
     * @since           Version 1.0
     * Date:            24-05-2017 
     	Description : Panchayath Member Edit
     */  
	function edit_panchayath_member()
    {
        if($this->role == TALUK || $this->role == ADMIN)
		{
           
            if($this->input->post('submit'))
			{
				$d['id']=$this->input->post('id');
	            $data['name']=$this->input->post('name');
	            $data['username']=$this->input->post('username');
	            $data['taluk']=$this->input->post('taluk');
	        	$data['panchayath']=$this->input->post('panchayath');
	            
	            
	            
	            $this->form_validation->set_message('required', '%s Required');
	            $this->form_validation->set_rules('username', 'username', 'required|trim|valid_email');
	            $this->form_validation->set_error_delimiters('', '');
	            if ($this->form_validation->run() == FALSE) 
				{

	            $data['user']=$this->User_model->check_user($d);
	            $data['taluk_all']=$this->User_model->taluk();
	            $this->load->view('header');
	            $this->load->view('edit_panchayath',$data);

	            }else
	            {
	               
	                
	                $returnFlag=$this->User_model->update_user_details($data,$d['id']); 
	                $data['taluk_all']=$this->User_model->taluk();
	                 if ($returnFlag) {

	                    
	                        $this->session->set_flashdata('err', '<label class="success">Member Edited Successfully...</label>');
	                        $data['user']=$this->User_model->check_user($d);
	                        $this->load->view('header');
	                        $this->load->view('edit_panchayath',$data);

	                 }else
	                 {
	                        $this->session->set_flashdata('err', '<label class="text-danger">No Updation Done...</label>');
	                        $data['user']=$this->User_model->check_user($d);
	                        $this->load->view('header');
	                        $this->load->view('edit_panchayath',$data);
	                 }
	            }
			}else
			{
	            $data['id']=$this->uri->segment(2);
	            if(is_numeric($data['id']))
		        { 
		            
	                $data['user']=$this->User_model->check_user($data);
					if($data['user'])
	                {	$data['taluk_all']=$this->User_model->taluk();
	                    $this->load->view('header');
	                    $this->load->view('edit_panchayath',$data);
	                }
	            }else
	            {
	            		redirect('dashboard');
		            
	            }
            }
        }else
        {
        	redirect('user');
        }

    }

	public function delete_survey()
		{
			$survey_id = $this->input->post('survey_id');
			if(isset($survey_id) && !empty($survey_id))
				{
					//$return = $this->User_model->deleteSurvey($survey_id);
					$arr 	= array('status'=> INACTIVE);
					$return = $this->User_model->update_surveyData($arr,$survey_id);
				}
		}
	public function getDistrictAgent()
		{
			$district_id = $this->input->post('district_id');
			if(!empty($district_id))
				{
					$return = $this->User_model->getAgent($district_id);
					echo json_encode($return);
				}
		}
	
}

