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

class User extends MX_Controller {
 	
 	public function __construct()
 	{
 		parent::__construct();
 		 $this->db->query('SET SESSION sql_mode = ""');
 		$this->load->model(array(
 			'user_model'  
 		));
 		
		if (! $this->session->userdata('isAdmin'))
			redirect('login');
 	}
 
	public function index()
	{ 
		$data['title']      = display('user_list');
		$data['module'] 	= "dashboard";  
		$data['page']   	= "user/list";   
		$data['user'] = $this->user_model->read();
		echo Modules::run('template/layout', $data); 
	}
 

    public function email_check($email, $id)
    { 
        $emailExists = $this->db->select('email')
            ->where('email',$email) 
            ->where_not_in('id',$id) 
            ->get('user')
            ->num_rows();

        if ($emailExists > 0) {
            $this->form_validation->set_message('email_check', 'The {field} is already registered.');
            return false;
        } else {
            return true;
        }
    } 

 
	public function form($id = null)
	{ 
		$data['title']    = display('add_user');
		/*-----------------------------------*/
		$this->form_validation->set_rules('firstname', display('firstname'),'required|max_length[50]');
		$this->form_validation->set_rules('lastname', display('lastname'),'required|max_length[50]');
		#------------------------#
		if (!empty($id)) {   
       		$this->form_validation->set_rules('email', display('email'), "required|valid_email|max_length[100]");
       		/*---#callback fn not supported#---*/  
		} else {
			$this->form_validation->set_rules('email', display('email'),'required|valid_email|max_length[100]');
		}
		#------------------------#
		if(empty($id)){
		$this->form_validation->set_rules('password', display('password'),'required|max_length[32]|md5');
		}
		$this->form_validation->set_rules('about', display('about'),'max_length[1000]');
		$this->form_validation->set_rules('status', display('status'),'required|max_length[1]');
		/*-----------------------------------*/
        $config['upload_path']          = './assets/img/user/';
        $config['allowed_types']        = 'gif|jpg|png'; 
         $image = $this->input->post('image');
		/*-----------------------------------*/
		$data['user'] = (object)$userLevelData = array(
			'id' 		  => $this->input->post('id'),
			'firstname'   => $this->input->post('firstname',true),
			'lastname' 	  => $this->input->post('lastname',true),
			'email' 	  => $this->input->post('email',true),
			'password' 	  => (!empty($this->input->post('password',true))?md5($this->input->post('password',true)):$this->input->post('oldpassword',true)),
			'about' 	  => $this->input->post('about',true),
			'image'   	  => (!empty($image)?$image:$this->input->post('old_image')),
			'last_login'  => null,
			'last_logout' => null,
			'ip_address'  => null,
			'status'      => 1,
			'is_admin'    => 0
		);

		/*-----------------------------------*/
		if ($this->form_validation->run()) {


			if (empty($userLevelData['id'])) {
			    
			    $employee_email = $this->input->post('email',true);
				$userinfo = $this->user_model->userinfo($employee_email);

				if($userinfo){

					$this->session->set_flashdata('exception', "User already created for this employee!");
					redirect("dashboard/user/form/");

				}else{

					if ($this->user_model->create($userLevelData)) {
						$this->session->set_flashdata('message', display('save_successfully'));
					} else {
						$this->session->set_flashdata('exception', display('please_try_again'));
					}
					redirect("dashboard/user/form/");

				}

			} else {
				if ($this->user_model->update($userLevelData)) {
					$this->session->set_flashdata('message', display('update_successfully'));
				} else {
					$this->session->set_flashdata('exception', display('please_try_again'));
				}

				redirect("dashboard/user/form/$id");
			}


		} else {
			$data['module'] = "dashboard";  
			$data['page']   = "user/form"; 
			$data['empl']   = $this->user_model->employee();
			if(!empty($id))
			$data['user']   = $this->user_model->single($id);
		    $data['empinfo']= $this->user_model->empinfo($data['user']->email);
			echo Modules::run('template/layout', $data);
		}
	}

	public function delete($id = null)
	{ 
		if ($this->user_model->delete($id)) {
			$this->session->set_flashdata('message', display('delete_successfully'));
		} else {
			$this->session->set_flashdata('exception', display('please_try_again'));
		}

		redirect("dashboard/user/index");
	}

	public function employeeData(){
		$employee_id = $this->input->post('employee_id');
		$data = $this->db->select('first_name,last_name,email,picture')->from('employee_history')->where('employee_id',$employee_id)->get()->row();
		$info = array(
			'first_name' => $data->first_name,
			'last_name'  => $data->last_name,
			'emails'     => (!empty($data->email)?$data->email:null),
			'image'      => $data->picture,
		);
		echo json_encode($info);
	}

	public function save_to_another_database() {
		// Load necessary helpers/libraries
		$this->load->helper('url');
		$this->load->library('session');
		$this->load->library('form_validation');
		$this->form_validation->set_rules('firstname', display('firstname'), 'required|max_length[50]');
		$this->form_validation->set_rules('lastname', display('lastname'), 'required|max_length[50]');
		$this->form_validation->set_rules('email', display('email'), 'required|valid_email|max_length[100]');
		//$this->form_validation->set_rules('password', display('password'), 'required|max_length[32]');
		$this->form_validation->set_rules('status', display('status'), 'required|max_length[1]');

		if ($this->form_validation->run() == FALSE) {
			        echo json_encode(['status' => 'error', 'message' => validation_errors()]);
			    } else {
			               // Default values for all keys
						   $defaultValues = [
							'employee_id' => 1,
							'pos_id' => 1,
							'first_name' => 1,
							'middle_name' => 1,
							'last_name' => 1,
							//'maiden_name' => 1,
							'email' => 1,
							'attendance_time' => 1,
							'monthly_work_hours' => 1,
							'employee_type' => 1,
							'phone' => 1,
							'alter_phone' => 1,
							'present_address' => 1,
							'parmanent_address' => 1,
							'picture' => 1,
							'dept_id' => 1,
							'state' => 1,
							'city' => 1,
							'zip' => 1,
							'citizenship' => 1,
							'duty_type' => 1,
							'hire_date' => 1,
							'original_hire_date' => 1,
							'termination_date' => 1,
							'termination_reason' => 1,
							'voluntary_termination' => 1,
							'rehire_date' => 1,
							'rate_type' => 1,
							'rate' => 1,
							'pay_frequency' => 1,
							'pay_frequency_txt' => 1,
							'hourly_rate2' => 1,
							'hourly_rate3' => 1,
							'home_department' => 1,
							'department_text' => 1,
							'class_code' => 1,
							'class_code_desc' => 1,
							'class_acc_date' => 1,
							'class_status' => 1,
							'is_super_visor' => 1,
							'super_visor_id' => 1,
							'supervisor_report' => 1,
							'dob' => 1,
							'gender' => 1,
							'marital_status' => 1,
							'ethnic_group' => 1,
							'eeo_class_gp' => 1,
							'sos' => 1,
							'work_in_state' => 1,
							'live_in_state' => 1,
							'home_email' => 1,
							'business_email' => 1,
							'home_phone' => 1,
							'business_phone' => 1,
							'cell_phone' => 1,
							'em_contact_person' => 1,
							'emerg_contct' => 1,
							'emrg_h_phone' => 1,
							'emrg_w_phone' => 1,
							'emgr_contct_relation' => 1,
							'alt_em_contct' => 1,
							'alt_emg_h_phone' => 1,
							'alt_emg_w_phone' => 1,
							'password' => 1,
						];

		// Specific values from the employee history data
			$specificValues = [
				'employee_id' => $this->input->post('id'),
				'first_name' => $this->input->post('firstname', true),
				'last_name' => $this->input->post('lastname', true),
				'email' => $this->input->post('email', true),
				'password' => (!empty($this->input->post('password', true)) ? md5($this->input->post('password', true)) : $this->input->post('oldpassword', true)),
			];

				(object)$userLevelData = array(
				'id' => $this->input->post('id'),
				'firstname' => $this->input->post('firstname', true),
				'lastname' => $this->input->post('lastname', true),
				'email' => $this->input->post('email', true),
				'password'  => (!empty($this->input->post('password',true))?md5($this->input->post('password',true)):$this->input->post('oldpassword',true)),
				
			);

		// Update the default values with specific values
			$postData = array_merge($defaultValues, $specificValues);
			if (!empty($postData['employee_id'])) {
        // Load your secondary database configuration
        $employee_email = $this->input->post('email',true);
		$userinfo = $this->user_model->empinfo($employee_email);

            if ($userinfo) {
				$this->session->set_flashdata('message', 'User already created for this employee!');
			$response = [
				'status' => 'error',
				'message' => 'User already created for this employee!'
			];
               
            } else {
                if ($this->user_model->createEmp($postData)) {
					$this->session->set_flashdata('message', 'User saved successfully.');
			$response = [
				'status' => 'success',
				'message' => 'User saved successfully.'
			];
                    echo json_encode(['status' => 'success', 'message' => 'User saved successfully',]);
                } else {
					$this->session->set_flashdata('message', 'An error occurred while saving the user');
			$response = [
				'status' => 'error',
				'message' => 'An error occurred while saving the user.'
			];
                  
                }
            }

		}

		 else {
			// Set flash data for error message
			$this->session->set_flashdata('message', 'No data received.');
			$response = [
				'status' => 'error',
				'message' => 'No data received.'
			];
		}
	
		// Return JSON response
		echo json_encode($response);
	}
	
	}

}



	
