<?php	if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller {

	function __construct(){
		parent::__construct();
		$this->load->model('master_model');
		//$this->lang->load('masters', '');	
		$language = $this->session->userdata('language'); 
    		if ($language=='hindi') {
      	       $this->lang->load('hindi', '');
   			}else{
      		    $this->lang->load('masters', '');
            }
            //error_reporting(E_ALL);
	}
	function index(){	
		$this->list_user();
	}
	
	function list_user($query_id = 0, $sort_by = 'user_id', $sort_order = 'asc', $offset = 0,$sort_type=0) 
	{
		//error_reporting(E_ALL);

		admin_auth();
		$submit=check_injections_filter($this->input->post('search')); 
		
		$limit = LIMIT_PER_PAGE;
		$this->page_data['page_title']="List of Users";
		$this->page_data['bredcrum']=array(
										'User Management'=>'#',
										'User'=>'#',
										'List User'=>'#',
										);

		    
		$condition = array();
		$access_branch= $this->session->userdata('access_branch');
		if ($access_branch!='') 
		{
			 $acb =  explode( ',',$access_branch);
			 $condition[] = array('where_in',TABLE_COMPANY_BRANCH.'.company_branch_id',$acb);
		}
		//$condition[] = array('where',TABLE_COMPANY.'.company_id',$company_id);
		$condition[] = array('join',TABLE_COMPANY_BRANCH,TABLE_COMPANY_BRANCH.'.company_branch_id ='.TABLE_USERS.'.company_branch_id','left');
		$condition[] = array('join',TABLE_USER_TYPE,TABLE_USER_TYPE.'.user_type_id ='.TABLE_USERS.'.user_type_id','left');
	   // $condition[] = array('where','users.is_active');

			/* $search_array=array(
				'table_name'=>TABLE_USERS,
				'table_fields'=>TABLE_USERS.'.is_active,user_id,first_name,last_name,email_id,designation,mobile_no,company_branch_name,user_type',
				'cond'=>$condition,
				'order_by_field'=>'first_name',
				'order'=>'DESC',
				'limit'=>'',
				'offset'=>''
			); */
		$user_type_cond = array();
		$user_type_cond[] = array('where','is_active','1');
	
		$user_select_array = array(
								'table_name'=>TABLE_USER_TYPE,
								'table_fields'=>'user_type,user_type_id',
								'condition'=>$user_type_cond,
								'sort_by'=>'user_type_id',
								'order_by_field'=>'user_type',
								'order'=>'ASC',
								'limit'=>'',
								'offset'=>''
								);
		$user_type_data['user_type_data']=$this->master_model->select_data($user_select_array);
		//dump($this->db->last_query());
		$user_type_cnt_data=count($user_type_data);
		$this->page_data['type_array'] = '';
		if(!empty($user_type_data['user_type_data'])&& is_array($user_type_data['user_type_data']))
		{
			$this->page_data['type_array'] = $user_type_data['user_type_data'];
				 
  	  			 
  	    }

		$this->page_data['user_first_name']='';
			//$this->page_data['user_last_name']='';
		$this->page_data['user_branch_name']='';
		$this->page_data['user_mobile_no']='';


		$this->load->library('NF_Query_search');
		$this->nf_query_search->load_query($query_id);

		$query_array = array(
				'user_type'=>$this->input->get('user_type'),
 				'user_first_name'=>$this->input->get('user_first_name'),
 				'user_branch_name'=>$this->input->get('user_branch_name'),
 				'user_mobile_no'=>$this->input->get('user_mobile_no'),

		);
		$user_type=check_injections_filter($query_array['user_type']);
		$user_first_name=check_injections_filter($query_array['user_first_name']);
		$user_branch_name=check_injections_filter($query_array['user_branch_name']);
		$user_mobile_no=check_injections_filter($query_array['user_mobile_no']);
		
		if ($user_type>0) {
        	$condition[]=array('where',TABLE_USERS.'.user_type_id',$user_type);
        	$this->page_data['user_type_id_check']=$user_type;
        }else{
         	$this->page_data['user_type_id_check']='';
        }

        if ($user_first_name!='') {
        	//$condition[]=array('like',TABLE_USERS.'.first_name',$user_first_name);
			$condition[] = array('where','(first_name LIKE "%'.$user_first_name.'%" OR last_name LIKE "%'.$user_first_name.'%")',NULL,FALSE);
        	$this->page_data['user_first_name']=$user_first_name;
         }else{
         	$this->page_data['user_first_name']='';
         }
        
        if ($user_branch_name!='') {
        	$condition[]=array('like',TABLE_COMPANY_BRANCH.'.company_branch_name',$user_branch_name);
        	$this->page_data['user_branch_name']=$user_branch_name;
        }else{
        	$this->page_data['user_branch_name']='';
        }
        if ($user_mobile_no!='') {
        	$condition[]=array('like',TABLE_USERS.'.mobile_no',$user_mobile_no);
        	$this->page_data['user_mobile_no']=$user_mobile_no;
        }else{
        	$this->page_data['user_mobile_no']='';
        }

        $this->page_data['fields'] = array(
							'user_type' => 'User Type',
							'first_name' => 'Person Name',
							'company_branch_name' => 'Branch Name',
							'email_id' => 'Email id',
							'mobile_no' => 'Mobile Number',
							'designation' => 'Designation',
							'accessible_branches' => 'Accessible branches',
						);

		//}
		
       
			$sort_columns = array('first_name','last_name','company_branch_name','mobile_no','accessible_branches','email_id','user_type','user_id');
			$search_array=array(
							'limit' => $limit,
							'offset' => $offset,
							'sort_by' => $sort_by,
							'sort_type' => $sort_type,
							'sort_order' => $sort_order,
							'sort_columns'=> $sort_columns,
							'table_fields'=> TABLE_USERS.' .is_active,user_id,first_name,last_name,email_id,designation,mobile_no,company_branch_name,user_type,accessible_branches',
							'order_by_field'=>'user_id',
							'order'=>'DESC',
							'table_name'=> TABLE_USERS,
							'cond'=> $condition,
							);
			
			//$users['users']=$this->master_model->select_data($select_array);
			$results = $this->master_model->search($search_array);

			$search_full_array=array(
							'limit' =>'',
							'offset' =>'',
							'sort_by' => $sort_by,
							'sort_type' => $sort_type,
							'sort_order' => $sort_order,
							'sort_columns'=> $sort_columns,
							'table_fields'=>TABLE_USERS.' .is_active,user_id,first_name,last_name,email_id,designation,mobile_no,company_branch_name,user_type,accessible_branches',
							'order_by_field'=>'user_id',
							'order'=>'DESC',
							'table_name'=> TABLE_USERS,
							'condition'=> $condition,
							);
			$search_data=$this->master_model->select_data($search_full_array);			
		    $cnt_all_rows=count($search_data);
			
			if(!empty($results)&& is_array($results))
			{
				$this->page_data['users'] = $results['rows'];
				$this->page_data['num_results'] = $cnt_all_rows;
			}
			else
			{

				$results='';
			}
						
			$this->page_data['offset'] = $offset;
			/// pagination
			$this->load->library('pagination');
			$config = array();
			$config['base_url'] = site_url("gc/user/list_user/$query_id/$sort_by/$sort_order");
			$config['total_rows'] = $this->page_data['num_results'];
			$config['per_page'] = $limit;
			$config['uri_segment'] = 7;
			$config['full_tag_open'] = '<span class=\'paging\'>';
			$config['full_tag_close'] = '</span>';
			$config['first_link'] = 'First';
			$config['prev_link'] = '<<';
			$config['next_link'] = '>>';
			$config['last_link'] = 'Last';
			$this->pagination->initialize($config);
			
			$this->page_data['pagination'] = $this->pagination->create_links();
			$this->page_data['sort_by'] = $sort_by;
			$this->page_data['sort_order'] = $sort_order;
			$this->page_data['sort_type'] = $sort_type;
			//$data['purpose'] = $purpose;
			$this->page_data['query_id'] = $query_id;

		   $this->load->view('gc/user_list',$this->page_data);
                           
	}

	function search_user()
	{
		$query_array = array(
			
						'user_type' =>check_injections_filter($this->input->post('user_type')),
						'user_first_name' =>check_injections_filter($this->input->post('user_first_name')),
						'user_branch_name' => check_injections_filter($this->input->post('user_branch_name')),
						'user_mobile_no' => check_injections_filter($this->input->post('user_mobile_no')),
						
					);
		$this->load->library('NF_Query_search');
		$query_id = $this->nf_query_search->save_query($query_array);			
		
		redirect('gc/user/list_user/'.$query_id);		
	}
	
	function view_user($user_id) {
      admin_auth();
	 $this->page_data['page_title']="View User";
     // $id=$this->encrypt->decode($user_id);
		$id=encrypt_decrypt_parameters($user_id,'decrypt');
		$this->page_data['bredcrum']=array(
			 							
			 							'User Management'=>'#',
			 							'User'=>'#',
										'List Users'=>site_url(USER_PATH.'list_user'),
										'View User'=>'#',
										);
		             $condition = array();
                            $condition[] = array('where','user_id',$id);
                            $condition[] = array('join',TABLE_COMPANY_BRANCH,TABLE_COMPANY_BRANCH.'.company_branch_id ='.TABLE_USERS.'.company_branch_id','left');
                            $condition[] = array('join',TABLE_USER_TYPE,TABLE_USER_TYPE.'.user_type_id ='.TABLE_USERS.'.user_type_id','left');
                           // $condition[] = array('where','users.is_active');

                            $select_array=array(
                                'table_name'=>TABLE_USERS,
                                'table_fields'=>'user_id,first_name,last_name,email_id,designation,mobile_no,company_branch_name,user_type,accessible_branches',
                                'condition'=>$condition,
                                'limit'=>'',
                                'offset'=>''
                            );
                            $users['users']=$this->master_model->select_data($select_array);
                            

                            if(!empty($users['users'])&& is_array($users['users'])){
							
				                   $this->page_data['users'] =  $users['users'];
		 	

  	                          } 

      
  	                       $this->load->view('gc/user_view',$this->page_data);
	}
	
	function manage_user($user_id="") {
		admin_auth();
 		$this->page_data['u_Branch_Name']=$this->lang->line('u_Branch_Name', FALSE);
 		$this->page_data['u_First_Name']=$this->lang->line('u_First_Name', FALSE);
 		$this->page_data['u_User_Type']=$this->lang->line('u_User_Type', FALSE);
 		$this->page_data['u_Last_Name']=$this->lang->line('u_Last_Name', FALSE);
 		$this->page_data['u_Mobile_Number']=$this->lang->line('u_Mobile_Number', FALSE);
 		$this->page_data['u_Email_Id']=$this->lang->line('u_Email_Id', FALSE);

 		$this->page_data['u_Accessible_Company_Branches']=$this->lang->line('u_Accessible_Company_Branches', FALSE);
 		$this->page_data['u_Designation']=$this->lang->line('u_Designation', FALSE);

 		$this->page_data['u_User_Details']=$this->lang->line('u_User_Details', FALSE);
 		$this->page_data['u_Contact_Details']=$this->lang->line('u_Contact_Details', FALSE);

       // $id=$this->encrypt->decode($user_id);
		$id=encrypt_decrypt_parameters($user_id,'decrypt');
        $this->page_data['branch'] = $this->fetch_branch_name();
        $this->page_data['user_type'] = $this->fetch_user_type();
		if ($id) {
			$this->page_data['page_title']="Edit User";
			$this->page_data['bredcrum']=array(
										
										'User Management'=>'#',
										'User'=>'#',
										'List User'=>site_url(USER_PATH.'list_user'),
										'Edit User'=>'#',
										);
		}else{$this->page_data['page_title']="Add User";
				$this->page_data['bredcrum']=array(
										
										'User Management'=>'#',
										'User'=>'#',
										//'List User'=>site_url(USER_PATH.'list_user'),
										'Add  User'=>'#',
										);
		}
		
	
         	if (!$id) {
	         $this->load->view('gc/user_manage.php',$this->page_data);
	         //redirect('gc/user/manage_user');

			}else{
                  
				$condition = array();
                            $condition[] = array('where','user_id',$id);
                            $condition[] = array('join',TABLE_COMPANY_BRANCH,TABLE_COMPANY_BRANCH.'.company_branch_id ='.TABLE_USERS.'.company_branch_id','left');
                            $condition[] = array('join',TABLE_USER_TYPE,TABLE_USER_TYPE.'.user_type_id ='.TABLE_USERS.'.user_type_id','left');
                           // $condition[] = array('where','users.is_active');

                            $select_array=array(
                                'table_name'=>TABLE_USERS,
                                'table_fields'=>'user_id,accessible_branches,first_name,last_name,email_id,designation,mobile_no,company_branch_name,user_type,'.TABLE_USER_TYPE.'.user_type_id,'.TABLE_COMPANY_BRANCH.'.company_branch_id,',
                                'condition'=>$condition,
                                'limit'=>'',
                                'offset'=>''
                            );
                            $users['users']=$this->master_model->select_data($select_array);

			
			if(!empty($users['users'] )&& is_array($users['users']))
			{
				 $this->page_data['users'] = $users['users'] ;
				 
  	  			 
  	        }else{
  	        	$this->page_data['users']='';
  	        }
		 	$this->load->view('gc/user_manage.php',$this->page_data);
		
		}
	
	}

	function add_user(){

    	 admin_auth();

	 	 $u_User_created=$this->lang->line('u_User_created', FALSE);
 		 $u_User_updated=$this->lang->line('u_User_updated', FALSE);
 		 $u_User_present=$this->lang->line('u_User_present', FALSE);

    	 $id = $this->input->post('hidden');
    	 $branch = $this->input->post('branch');
    	 $user_type =$this->input->post('user_type');
    	 $first_name = check_injections_filter($this->input->post('first_name'));
    	 $last_name = check_injections_filter($this->input->post('last_name'));
    	 $access_branch = $this->input->post('access_branch'); 
    	 if ($access_branch!='') {
    	 	$acb=  implode(",",$access_branch);
    	 }else{
    	 	$acb= '';
    	 }
    	   
    	 $designation = check_injections_filter($this->input->post('designation'));  
    	 $mobile_number = check_injections_filter($this->input->post('mobile_number'));  
    	 $email_id = check_injections_filter($this->input->post('email_id'));
    	 $s_email_id=strtolower($email_id);
    	 $user_pass = $this->get_rand_alphanumeric();
    	 $user_password = md5($user_pass);
    	 $user_id=$this->session->userdata('user_id'); 
    	 $name=$first_name." ".$last_name;

    	 /* $this->form_validation->set_rules('first_name', 'First Name', 'required');
    	 //$this->form_validation->set_rules('last_name', 'last Name', 'required'); 
    	 $this->form_validation->set_rules('designation', 'Designation', 'required'); 
    	 $this->form_validation->set_rules('mobile_number', 'Mobile Number', 'required'); 
    	$this->form_validation->set_rules('email_id', 'Email Id', 'required'); */    
    	/* if ($this->form_validation->run() == FALSE)
        {
        	$this->manage_user();
        }else{ */

        	  // $condition[] = array('where','LOWER(user_name)',$s_email_id);
        	  
    	       
    	       if ($id) {
    	       	$condition[] = array('where','email_id',$s_email_id);
    	       	$condition[] = array('where_not_in','user_id',$id);
    	       	
               }else{
               	$condition[] = array('or_where','email_id',$s_email_id);
               }


		       $selected_array=array(
								'table_name' =>TABLE_USERS,								
								'table_fields'=>'first_name,last_name,mobile_no,email_id,user_name',
								 'limit'=>'',
                                'offset'=>'',
								'condition'=>$condition							
					    );
    	
    	       
    			$user['user'] = $this->master_model->select_data($selected_array);
    			// dump($this->db->last_query());
    			// exit;
    			if(!empty($user['user']))
				{			
					 $this->session->set_flashdata('message',$u_User_present);
				     redirect('gc/user/manage_user');
				}else{
					if (!$id) {
						$user_data=array(
    	        				'user_name' => $email_id,
    	        				'user_password' => $user_password,							
    							'first_name' =>$first_name,
								'last_name' => $last_name,
								'accessible_branches' =>$acb,								
								'email_id' => $email_id,
								'designation' =>$designation,
								'mobile_no' =>$mobile_number,
								'company_branch_id' => $branch,
								'user_type_id' =>$user_type,							
								'created_on' => date("Y-m-d H:i:s"),
								'created_by' =>$user_id,
								'modified_by' => '',	
								'modified_on' => date("Y-m-d H:i:s")
								
					    );
					
						
				 		$this->master_model->insert_record(TABLE_USERS,$user_data);
				 		//if ($insert) {
				 		$this->session->set_flashdata('message',$u_User_created);
						//	$this->send($email_id,$user_pass,$name);	
				 		redirect('gc/user/list_user');
				 		
				 		//}
    	         		
					}else{
						$this->session->set_flashdata('message',$u_User_updated);
				 		$user_data=array(
    	        				'user_name' => $email_id,
    	        				// 'user_password' => $user_password,							
    							'first_name' =>$first_name,
								'last_name' => $last_name,
								'accessible_branches' =>$acb,	
								'email_id' => $email_id,
								'designation' =>$designation,
								'mobile_no' =>$mobile_number,
								'company_branch_id' => $branch,
								'user_type_id' =>$user_type,							
								'created_on' => date("Y-m-d H:i:s"),
								'created_by' =>$user_id,
								'modified_by' =>$user_id,	
								'modified_on' => date("Y-m-d H:i:s")
								
					    );
				        $condition=array('user_id'=> $id);
						$this->master_model->update_record(TABLE_USERS,$user_data,$condition);
			     		redirect('gc/user/list_user');	
					}
				}
        //}
	 
    }
     function fetch_branch_name(){
     	admin_auth();
     	$condition[] = array('where','is_active','1');
    	$selected_array = array( 
			                   'table_name' =>TABLE_COMPANY_BRANCH,
			                   'table_fields' => 'company_branch_id,company_branch_name,is_active',
			                   'order_by_field'=>'company_branch_name',
			                   'condition'=>$condition,
			                   'group_by_field'=>'company_branch_name',
			                   'order'=>'ASC',
			                   'limit'=>'',
			                   'offset'=>''

		);

		return $this->master_model->select_data($selected_array);	
		
    }
    function fetch_user_type(){
    	admin_auth();
		$condition[] = array('where','is_active','1');
    	$selected_array = array( 
			                   'table_name' =>TABLE_USER_TYPE,
			                   'table_fields' => 'user_type_id,user_type',
			                   'order_by_field'=>'user_type',
			                   'condition'=>$condition,
			                   'order'=>'ASC',
			                   'limit'=>'',
			                   'offset'=>''
		);

		return $this->master_model->select_data($selected_array);		         
    }
      function get_rand_alphanumeric() {
    
    		$alph = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        	$code='';
       		 $i=0;
       		 while($i<9){
           		 $position=rand(0,35);
            	 $code=$code.substr($alph,$position,1);
                 $i++;
             }
           return $code;
    }
     function disable_user($user_id){
     	admin_auth();
     	$u_User_disable=$this->lang->line('u_User_disable', FALSE);
     	//$id=$this->encrypt->decode($user_id);
		$id=encrypt_decrypt_parameters($user_id,'decrypt');
     	$user_id = $this->session->userdata('user_id'); 
        $user_data=array(
								'is_active' =>'0',								
								'created_on' => date("Y-m-d H:i:s"),
								'created_by' =>$user_id,
								'modified_by' =>$user_id,	
								'modified_on' => date("Y-m-d H:i:s")								
					    );
     	$condition=array('user_id'=>$id);
     	$this->session->set_flashdata('message',$u_User_disable);
		$this->master_model->update_record(TABLE_USERS,$user_data,$condition);
		redirect('gc/user/list_user');
    }
    function enable_user($user_id){
      	admin_auth();
      	$u_User_enable=$this->lang->line('u_User_enable', FALSE);
      	//$id=$this->encrypt->decode($user_id);
		$id=encrypt_decrypt_parameters($user_id,'decrypt');
      	$user_id = $this->session->userdata('user_id'); 
      $user_data=array(
								'is_active' =>'1',								
								'created_on' => date("Y-m-d H:i:s"),
								'created_by' =>$user_id,
								'modified_by' =>$user_id,	
								'modified_on' => date("Y-m-d H:i:s")								
					    );
     	$condition=array('user_id'=>$id);
     	$this->session->set_flashdata('message',$u_User_enable);
		$this->master_model->update_record(TABLE_USERS,$user_data,$condition);
		redirect('gc/user/list_user');
    } 
    function send($email_id,$user_pass,$name){
   	
		$url='https://shagoon.nityamhygiene.in/';
    	$mailContent = "<table align=center border=0 cellpadding=8 cellspacing=0 width=600>    <tbody>        <tr>            <td align=left bgcolor=#f26e2e style=font-family:Arial, Helvetica, sans-serif; font-size:12px; line-height:18px; color:#666666; text-align:justify; font-family:Arial, Helvetica, sans-serif; font-size:12px; line-height:18px; color:#ffffff; padding:4px; valign=top><img src=https://shagoon.nityamhygiene.in/assets/images/logohygiene.jpg></td>
 			</tr>
 			<tr>
  			  <td align=left style=border-left:4px solid #CBE4EC; border-right:4px solid #CBE4EC; font-family:Arial, Helvetica, sans-serif; font-size:12px; line-height:18px; color:#666666; text-align:justify; padding:10px; valign=top><p><strong>Dear $name,</strong></p>

  
				<p>Welcome to Nityam Hygiene - Refill Management System.</p> 
				<p> Please find below your login details.</p> 
				<p>Username=$email_id</p> 
        		<p>Password=$user_pass</p>
        		<p>Following link is provided for login </p>
        		<p><a href='$url'>$url</a></p>
        		
   				<p>Warm Regards,</p>

   				<p>Nityam Hygiene</p>
			  </td>
			 </tr>
  		
  </tbody>
</table>";

  //   $mail->Body = $mailContent;
	//$email_id='yatin@nityam.in';
 	$this->load->library('email'); 
 	$this->email->clear();
    $this->email->from('no-reply@shagoon.nityamhygiene.in','Nityam');
    $this->email->to($email_id);
    $this->email->subject("Login Credentials");
    $this->email->message($mailContent);
    $this->email->set_newline("\r\n");
    //$this->email->send();
     if (!$this->email->send()) {
    show_error($this->email->print_debugger()); }
     else {
       redirect('gc/user/list_user');
     }
  }
  
}