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

class Users extends MY_Controller {
	
	 public function __construct() {
        Parent::__construct();
		$this->load->library('session');
		$this->load->helper('form');
		$this->load->helper('url');
		$this->load->helper('html');
		$this->load->database();
		$this->load->library('form_validation');
		//load the models
		$this->load->model("Users_model");
		$this->load->model("Roles_model");
		$this->load->model("Xin_model");
	}
	
	/*Function to set JSON output*/
	public function output($Return=array()){
		/*Set response header*/
		header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		/*Final JSON response*/
		exit(json_encode($Return));
	}
	
	 public function index()
     {
         
        $cookie_name = $this->Xin_model->get_cookie_name();
        $session = $this->session->userdata($cookie_name);
		if(!empty($session)){ 
			
		} else {
			redirect('');
		}
         
		$data['title'] = $this->Xin_model->site_title();
		$data['all_user_roles'] = $this->Roles_model->all_user_roles();
		$data['breadcrumbs'] = $this->lang->line('xin_employees');
		$data['path_url'] = 'users';
		$role_resources_ids = $this->Xin_model->user_role_resource();
		//if(in_array('41',$role_resources_ids)) {
			if(!empty($session)){ 
			$data['subview'] = $this->load->view("users/user_list", $data, TRUE);
			$this->load->view('layout_main', $data); //page load
			} else {
				redirect('');
			}
		/*} else {
			redirect('dashboard/');
		}*/
     }
 
    public function users_list()
     {

		$data['title'] = $this->Xin_model->site_title();
		$cookie_name = $this->Xin_model->get_cookie_name();
        $session = $this->session->userdata($cookie_name);
		if(!empty($session)){ 
			$this->load->view("users/user_list", $data);
		} else {
			redirect('');
		}
		// Datatables Variables
		$draw = intval($this->input->get("draw"));
		$start = intval($this->input->get("start"));
		$length = intval($this->input->get("length"));
		
		
		$employee = $this->Users_model->get_users();
		
		$data = array();

        foreach($employee->result() as $r) {
			 			  
		// user full name
		$full_name = $r->name;				
		// get status
		if($r->status_id==2): $status = '<span data-toggle="tooltip" data-placement="top" title="In-Active" class="btn btn-danger">In-Active</span>';
		elseif($r->status_id==1): $status = '<span data-toggle="tooltip" data-placement="top" title="Active" class="btn btn-success">Active</span>'; endif;
		
		$option = '<span data-toggle="tooltip" data-placement="top" title="Edit"><button type="button" class="btn btn-secondary btn-sm m-b-0-0 waves-effect waves-light"  data-toggle="modal" data-target=".edit-modal-data"  data-employee_id="'. $r->id . '"><i class="fa fa-pencil-square-o"></i></button></span><span data-toggle="tooltip" data-placement="top" title="'.$this->lang->line('xin_delete').'"><button type="button" class="btn btn-danger btn-sm m-b-0-0 waves-effect waves-light delete" data-toggle="modal" data-target=".delete-modal" data-record-id="'. $r->id . '"><i class="fa fa-trash-o"></i></button></span>';
		$data[] = array(
			$option,
			$full_name,
			$r->email,
			$status
		);
      
	  }
	  $output = array(
		   "draw" => $draw,
			 "recordsTotal" => $employee->num_rows(),
			 "recordsFiltered" => $employee->num_rows(),
			 "data" => $data
		);
	  echo json_encode($output);
	  exit();
     }
     
    public function read()
	{
		$id = $this->input->get('employee_id');
		$cookie_name = $this->Xin_model->get_cookie_name();
        $session = $this->session->userdata($cookie_name);
		$result = $this->Users_model->read_user_information($id);
		$role_resources_ids = $this->Xin_model->user_role_resource();
		$data['breadcrumbs'] = $this->lang->line('xin_employee_details');
		$data['path_url'] = 'employees_detail';
		
		if(in_array('41',$role_resources_ids)) {
			if(!empty($session)){ 
			} else {
				redirect('');
			}
		} else {
			redirect('dashboard/');
		}
		$data = array(
			'first_name' => $result[0]->name,
			'user_id' => $result[0]->id,
			'contact_no' => $result[0]->mobile_no,
			'email' => $result[0]->email,
			'is_active' => $result[0]->status_id,
			'user_role_id' =>$result[0]->user_role_id,
			'all_user_roles' => $this->Roles_model->all_user_roles()
			);
		
		if(!empty($session)){ 
			$this->load->view('users/dialoge_user', $data);
		} else {
			redirect('');
		}
	 }
	 
	  public function detail() {

		$id = $this->uri->segment(3);
		$cookie_name = $this->Xin_model->get_cookie_name();
        $session = $this->session->userdata($cookie_name);
		$result = $this->Employees_model->read_employee_information($id);
		$role_resources_ids = $this->Xin_model->user_role_resource();
		$data['breadcrumbs'] = $this->lang->line('xin_employee_details');
		$data['path_url'] = 'employees_detail';
		
		if(in_array('41',$role_resources_ids)) {
			if(!empty($session)){ 
			} else {
				redirect('');
			}
		} else {
			redirect('dashboard/');
		}
		
		$data = array(
			'breadcrumbs' => $this->lang->line('xin_employee_detail'),
			'path_url' => 'employees_detail',
			'first_name' => $result[0]->first_name,
			'last_name' => $result[0]->last_name,
			'user_id' => $result[0]->user_id,
			'employee_id' => $result[0]->employee_id,
			'username' => $result[0]->username,
			'email' => $result[0]->email,
			'department_id' => $result[0]->department_id,
			'designation_id' => $result[0]->designation_id,
			'user_role_id' => $result[0]->user_role_id,
			'date_of_birth' => $result[0]->date_of_birth,
			'date_of_leaving' => $result[0]->date_of_leaving,
			'gender' => $result[0]->gender,
			'marital_status' => $result[0]->marital_status,
			'contact_no' => $result[0]->contact_no,
			'address' => $result[0]->address,
			'is_active' => $result[0]->is_active,
			'date_of_joining' => $result[0]->date_of_joining,
			'all_departments' => $this->Department_model->all_departments(),
			'all_designations' => $this->Designation_model->all_designations(),
			'all_user_roles' => $this->Roles_model->all_user_roles(),
			'title' => $this->Xin_model->site_title(),
			'profile_picture' => $result[0]->profile_picture,
			'facebook_link' => $result[0]->facebook_link,
			'twitter_link' => $result[0]->twitter_link,
			'blogger_link' => $result[0]->blogger_link,
			'linkdedin_link' => $result[0]->linkdedin_link,
			'google_plus_link' => $result[0]->google_plus_link,
			'instagram_link' => $result[0]->instagram_link,
			'pinterest_link' => $result[0]->pinterest_link,
			'youtube_link' => $result[0]->youtube_link,
			'all_countries' => $this->Xin_model->get_countries(),
			'all_document_types' => $this->Employees_model->all_document_types(),
			'all_education_level' => $this->Employees_model->all_education_level(),
			'all_qualification_language' => $this->Employees_model->all_qualification_language(),
			'all_qualification_skill' => $this->Employees_model->all_qualification_skill(),
			'all_contract_types' => $this->Employees_model->all_contract_types(),
			'all_contracts' => $this->Employees_model->all_contracts(),
			'all_office_shifts' => $this->Employees_model->all_office_shifts(),
			'all_office_locations' => $this->Location_model->all_office_locations(),
			);
		
		$data['subview'] = $this->load->view("employees/employee_detail", $data, TRUE);
		$this->load->view('layout_main', $data); //page load
		
		// Datatables Variables
		$draw = intval($this->input->get("draw"));
		$start = intval($this->input->get("start"));
		$length = intval($this->input->get("length"));
	 }
	
	
	// Validate and add info in database
	public function add_user() {
	
		if($this->input->post('add_type')=='user') {		
		    
		$query = $this->Xin_model->read_user_info_byemail($this->input->post('email'));
		$q_result = $query->result();
		
		/* Define return | here result is used to return user data and error for error message */
		$Return = array('result'=>'', 'error'=>'');
			
		/* Server side PHP input validation */		
		if($this->input->post('first_name')==='') {
       		 $Return['error'] = $this->lang->line('xin_employee_error_first_name');
		} else if($this->input->post('last_name')==='') {
			$Return['error'] = $this->lang->line('xin_employee_error_last_name');
		}  else if(empty($this->input->post('email'))) {
			 $Return['error'] = $this->lang->line('xin_employee_error_email');
		} else if (!filter_var($this->input->post('email'), FILTER_VALIDATE_EMAIL)) {
			$Return['error'] = $this->lang->line('xin_employee_error_invalid_email');
		} else if(empty($this->input->post('contact_no'))) {
			 $Return['error'] = $this->lang->line('xin_employee_error_contact_number');
		}else if($q_result==1 && isset($q_result))
		{
		    $Return['error'] = 'This user already exist';
		}
		
				
		if($Return['error']!=''){
       		$this->output($Return);
    	}
    	
    	$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        $password = implode($pass); //turn the array into a string
        $salt = $password;
        $pw_hash = sha1($salt.$password);
	    //print_r($pw_hash);exit();
		$data = array(
		'name' => $this->input->post('first_name'),
		'email' => $this->input->post('email'),
		'secure_password' => $pw_hash,
		'password_salt' => $salt,
		'user_type_id' => 1,
		'status_id' =>1,
		'mobile_no' => $this->input->post('contact_no'),
		'user_role_id' => $this->input->post('role'),
		'created_at' => date('d-m-Y'),
		);
		//print_r($data);exit();
		$result = $this->Users_model->add($data);
		if ($result == TRUE) {
			$Return['result'] = $this->lang->line('xin_success_add_user');
			
			//get setting info 
			$setting = $this->Xin_model->read_setting_info(1);
			if($setting[0]->enable_email_notification == 'yes') {
				
				// load email library
				$this->load->library('email');
				$this->email->set_mailtype("html");
				
				//get company info
				$cinfo = $this->Xin_model->read_company_setting_info(1);
				//get email template
				$template = $this->Xin_model->read_email_template(8);
				$subject = $template[0]->subject.' - '.$cinfo[0]->name;
				$logo = base_url().'uploads/logo/logo.svg';
				
				// get user full name
				$full_name = $this->input->post('name');
				
				$message = '
			<div style="background:#f6f6f6;font-family:Verdana,Arial,Helvetica,sans-serif;font-size:12px;margin:0;padding:0;padding: 20px;">
			<img src="'.$logo.'" title="Price Check" style="max-width:200px;"><br>'.str_replace(array("{var site_name}","{var site_url}","{var username}","{var employee_id}","{var employee_name}","{var email}","{var password}"),array($cinfo[0]->name,site_url(),$this->input->post('email'),$this->input->post('employee_id'),$full_name,$this->input->post('email'),$password),htmlspecialchars_decode(stripslashes($template[0]->message))).'</div>';
				
				require './mail/gmail.php';
                $mail->addAddress($this->input->post('email'), $full_name);
                $mail->Subject = $subject;
                $mail->msgHTML($message);
                
                if (!$mail->send()) {
                    //echo "Mailer Error: " . $mail->ErrorInfo;
                } else {
                    //echo "Message sent!";
                }
                
                $Return['result'] = $this->lang->line('xin_success_add_user');
                
			}
		} else {
			$Return['error'] = $this->lang->line('xin_error_msg');
		}
		$this->output($Return);
		exit;
		}
	}
	
	/*  add and update employee details info */
	
	// Validate and update info in database // basic info
	public function basic_info() {
	
		if($this->input->post('type')=='basic_info') {		
		/* Define return | here result is used to return user data and error for error message */
		$Return = array('result'=>'', 'error'=>'');
			
		/* Server side PHP input validation */		
		if($this->input->post('first_name')==='') {
       		 $Return['error'] = $this->lang->line('xin_employee_error_first_name');
		} else if($this->input->post('last_name')==='') {
			$Return['error'] = $this->lang->line('xin_employee_error_last_name');
		} else if($this->input->post('employee_id')==='') {
			 $Return['error'] = $this->lang->line('xin_employee_error_employee_id');
		} else if(empty($this->input->post('date_of_joining'))) {
			 $Return['error'] = $this->lang->line('xin_employee_error_joining_date');
		} else if(empty($this->input->post('department_id'))) {
			 $Return['error'] = $this->lang->line('xin_employee_error_department');
		} else if(empty($this->input->post('designation_id'))) {
			 $Return['error'] = $this->lang->line('xin_employee_error_designation');
		} else if(empty($this->input->post('role'))) {
			 $Return['error'] = $this->lang->line('xin_employee_error_user_role');
		} else if(empty($this->input->post('username'))) {
			 $Return['error'] = $this->lang->line('xin_employee_error_username');
		} else if(empty($this->input->post('email'))) {
			 $Return['error'] = $this->lang->line('xin_employee_error_email');
		} else if (!filter_var($this->input->post('email'), FILTER_VALIDATE_EMAIL)) {
			$Return['error'] = $this->lang->line('xin_employee_error_invalid_email');
		}
				
		if($Return['error']!=''){
       		$this->output($Return);
    	}
	
		$data = array(
		'employee_id' => $this->input->post('employee_id'),
		'first_name' => $this->input->post('first_name'),
		'last_name' => $this->input->post('last_name'),
		'username' => $this->input->post('username'),
		'email' => $this->input->post('email'),
		'date_of_birth' => $this->input->post('date_of_birth'),
		'gender' => $this->input->post('gender'),
		'user_role_id' => $this->input->post('role'),
		'marital_status' => $this->input->post('marital_status'),
		'is_active' => $this->input->post('status'),
		'department_id' => $this->input->post('department_id'),
		'designation_id' => $this->input->post('designation_id'),
		'date_of_joining' => $this->input->post('date_of_joining'),
		'contact_no' => $this->input->post('contact_no'),
		'address' => $this->input->post('address')
		);
		$id = $this->input->post('user_id');
		$result = $this->Employees_model->basic_info($data,$id);
		if ($result == TRUE) {
			$Return['result'] = $this->lang->line('xin_employee_basic_info_updated');
		} else {
			$Return['error'] = $this->lang->line('xin_error_msg');
		}
		$this->output($Return);
		exit;
		}
	}
	
	// Validate and update info in database // social info
	public function profile_picture() {
	
		if($this->input->post('type')=='profile_picture') {		
		/* Define return | here result is used to return user data and error for error message */
		$Return = array('result'=>'', 'error'=>'');
		$id = $this->input->post('user_id');
			
		/* Check if file uploaded..*/
		if($_FILES['p_file']['size'] == 0 && null ==$this->input->post('remove_profile_picture')) {
			$Return['error'] = $this->lang->line('xin_employee_select_picture');
		} else {
			if(is_uploaded_file($_FILES['p_file']['tmp_name'])) {
					
					//checking image type
    				$allowed =  array('png','jpg','jpeg','gif');
    				$filename = $_FILES['p_file']['name'];
    				$ext = pathinfo($filename, PATHINFO_EXTENSION);
    				
    				if(in_array($ext,$allowed)){
					
					$uploadedfile = $_FILES['p_file']['tmp_name'];
                    
        			if ($ext == "jpg" || $ext == "jpeg")
        				{
        				    $src = imagecreatefromjpeg($uploadedfile);
        				}
        			  else if ($extension == "png")
        				{
        				    $src = imagecreatefrompng($uploadedfile);
        				}
        			  else
        				{
        				    $src = imagecreatefromgif($uploadedfile);
        				}
        
        			list($width, $height) = getimagesize($uploadedfile);
        			$newwidth = 250;
        			$newheight = ($height / $width) * $newwidth;
        			$tmp = imagecreatetruecolor($newwidth, $newheight);
        			imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        			$uxi = rand(111, 999).round(microtime(true)).'.'.$ext;
                    $fname = $photo = "profile_" . $uxi;
        			$filename = "../uploads/profile/" . $photo;
        			imagejpeg($tmp, $filename, 100);
        			imagedestroy($src);
        			imagedestroy($tmp);
					
					$result2     = $this->Employees_model->read_employee_information($this->input->post('user_id'));
        		    $delete_file = $result2[0]->profile_picture;
					
					//UPDATE Employee info in DB
					$data = array('profile_picture' => $fname);
					$result = $this->Employees_model->profile_picture($data,$id);
					if ($result == TRUE) {
						$Return['result'] = $this->lang->line('xin_employee_picture_updated');
						$Return['img'] = $set_img.$fname;
						
						if(file_exists('../uploads/profile/'.$delete_file))
    					{
    					    unlink('../uploads/profile/'.$delete_file);
    					}
					
					} else {
						$Return['error'] = $this->lang->line('xin_error_msg');
					}
					$this->output($Return);
					exit;
					
				} else {
					$Return['error'] = $this->lang->line('xin_employee_picture_type');
				}
				}
			}
			
			if(null!=$this->input->post('remove_profile_picture')) {
				//UPDATE Employee info in DB
				$data = array('profile_picture' => 'no file');				
				$row = $this->Employees_model->read_employee_information($id);
				$profile = base_url()."uploads/profile/";
				$result = $this->Employees_model->profile_picture($data,$id);
				if ($result == TRUE) {
					$Return['result'] = $this->lang->line('xin_employee_picture_updated');
					if($row[0]->gender=='Male') {
						$Return['img'] = $profile.'default_male.jpg';
					} else {
						$Return['img'] = $profile.'default_female.jpg';
					}
				} else {
					$Return['error'] = $this->lang->line('xin_error_msg');
				}
				$this->output($Return);
				exit;
				
			}
				
			if($Return['error']!=''){
				$this->output($Return);
			}
		}
	}
	
	// Validate and update info in database // change password
	public function change_password() {
	
		if($this->input->post('type')=='change_password') {		
		/* Define return | here result is used to return user data and error for error message */
		$Return = array('result'=>'', 'error'=>'');
			
		/* Server side PHP input validation */		
		if(trim($this->input->post('new_password'))==='') {
       		 $Return['error'] = $this->lang->line('xin_employee_error_newpassword');
		} else if(strlen($this->input->post('new_password')) < 6) {
			$Return['error'] = $this->lang->line('xin_employee_error_password_least');
		} else if(trim($this->input->post('new_password_confirm'))==='') {
			 $Return['error'] = $this->lang->line('xin_employee_error_new_cpassword');
		} else if($this->input->post('new_password')!=$this->input->post('new_password_confirm')) {
			 $Return['error'] = $this->lang->line('xin_employee_error_old_new_cpassword');
		}
				
		if($Return['error']!=''){
       		$this->output($Return);
    	}
    	
    	$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        $password = $this->input->post('new_password'); //turn the array into a string
        $salt = implode($pass);
        $pw_hash = sha1($salt.$password);
	
		$data = array(
		'secure_password' => $pw_hash,
		'password_salt' => $salt,
		'updated_at' => date('Y-m-d H:i:s')
		);
		$id = $this->input->post('user_id');
		$result = $this->Users_model->change_password($data,$id);
		if ($result == TRUE) {
			$Return['result'] = $this->lang->line('xin_employee_password_update');
		} else {
			$Return['error'] = $this->lang->line('xin_error_msg');
		}
		$this->output($Return);
		exit;
		}
	}
	

	// Validate and update info in database
	public function update() {
	
		if($this->input->post('edit_type')=='basic_info') {		
		/* Define return | here result is used to return user data and error for error message */
		$Return = array('result'=>'', 'error'=>'');
			
		/* Server side PHP input validation */		
		if($this->input->post('first_name')==='') {
       		 $Return['error'] = $this->lang->line('xin_employee_error_first_name');
		} else if(empty($this->input->post('email'))) {
			 $Return['error'] = $this->lang->line('xin_employee_error_email');
		} else if (!filter_var($this->input->post('email'), FILTER_VALIDATE_EMAIL)) {
			$Return['error'] = $this->lang->line('xin_employee_error_invalid_email');
		}
				
		if($Return['error']!=''){
       		$this->output($Return);
    	}
	
		$data = array(
		'name' => $this->input->post('first_name'),
		'email' => $this->input->post('email'),
		'mobile_no' => $this->input->post('contact_no'),
		'user_role_id' => $this->input->post('role'),
		'status_id' => $this->input->post('is_active')
		);
		$id = $this->input->post('user_id');
		$result = $this->Users_model->user_info($data,$id);
		if ($result == TRUE) {
			$Return['result'] = 'users basic info updated';
		} else {
			$Return['error'] = $this->lang->line('xin_error_msg');
		}
		$this->output($Return);
		exit;
		}
	}

	
	// delete employee record
	public function delete() {
		
		if($this->input->post('is_ajax')=='2') {
			/* Define return | here result is used to return user data and error for error message */
			$Return = array('result'=>'', 'error'=>'');
			$id = $this->uri->segment(3);
			$result = $this->Users_model->delete_record($id);
			if(isset($id)) {
				$Return['result'] = 'User Deleted';
			} else {
				$Return['error'] = $this->lang->line('xin_error_msg');
			}
			$this->output($Return);
		}
	}
	

}
