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

class Auth extends MX_Controller {
 	
 	public function __construct()
 	{
 		parent::__construct();

   $this->db->query('SET SESSION sql_mode = ""');

 		$this->load->model(array(
 			'auth_model',
			'user_model'
 		));

		$this->load->helper('captcha');
		
		//$this->load->library('form_validation');
 	}

	 private function generate_token($length = 16) {
        if (function_exists('random_bytes')) {
            return bin2hex(random_bytes($length));
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
            return bin2hex(openssl_random_pseudo_bytes($length));
        } else {
            throw new Exception('No cryptographically secure random function available');
        }
    }

	public function index()
{
    // Check if the user is already logged in
    if ($this->session->userdata('isLogIn')) {
        redirect('dashboard/home');
    }
    
    $data['title'] = display('login'); 
    
    // Capture the redirect URL parameter and store it in the session
    $redirect = $this->input->get('redirect');
    if ($redirect) {
        $this->session->set_userdata('redirect_url', $redirect);
    }

    #-------------------------------------#
    $this->form_validation->set_rules('email', display('email'), 'required|valid_email|max_length[100]|trim');
    $this->form_validation->set_rules('password', display('password'), 'required|max_length[32]|md5|trim');
    $this->form_validation->set_rules(
        'captcha', display('captcha'),
        array(
            'matches[captcha]', 
            function($captcha) { 
                $oldCaptcha = $this->session->userdata('captcha');
                return $captcha === $oldCaptcha;
            }
        )
    );

    #-------------------------------------#
    $data['user'] = (object) $userData = array(
        'email' => $this->input->post('email', true),
        'password' => $this->input->post('password', true),
    );

    #-------------------------------------#
    if ($this->form_validation->run()) {

        $this->session->unset_userdata('captcha');

        // Authenticate user
        $user = $this->auth_model->checkUser($userData);
        if ($user->num_rows() > 0) {
            $checkPermission = $this->auth_model->userPermission2($user->row()->id);
            $permission = $permission1 = array();

            if ($checkPermission) {
                foreach ($checkPermission as $value) {
                    $permission[$value->module] = array(
                        'create' => $value->create,
                        'read' => $value->read,
                        'update' => $value->update,
                        'delete' => $value->delete
                    );
                    $permission1[$value->menu_title] = array(
                        'create' => $value->create,
                        'read' => $value->read,
                        'update' => $value->update,
                        'delete' => $value->delete
                    );
                }
            }

            $userRole = $this->auth_model->userRole($user->row()->id);
            if ($user->row()->is_admin == 2) {
                $row = $this->db->select('client_id,client_email')
                                ->where('client_email', $user->row()->email)
                                ->get('setup_client_tbl')
                                ->row();
            }

            $employee_info = $this->db->select('employee_id,employee_status,first_name,last_name,is_super_visor')
                                      ->from('employee_history')
                                      ->where('email', $user->row()->email)
                                      ->get()
                                      ->row();

            if (!$user->row()->is_admin && ($user->row()->status != 1 || $employee_info->employee_status != 1)) {
                $this->session->set_flashdata('exception', "It seems you are not an active user of the system!");
                redirect('login');
            }

            $fyear = $this->auth_model->checkfinancialyear();
            if (!$fyear) {
                $this->session->set_flashdata('message', display('welcome_back') . ' ' . $user->row()->fullname);
                redirect('accounts/accounts/financial_year');
            } else {
                $sData = array(
                    'isLogIn' => true,
                    'isAdmin' => $user->row()->is_admin == 1,
                    'user_type' => $user->row()->is_admin,
                    'id' => $user->row()->id,
                    'client_id' => @$row->client_id,
                    'fullname' => $user->row()->fullname,
                    'user_level' => $user->row()->user_level,
                    'email' => $user->row()->email,
                    'image' => $user->row()->image,
                    'last_login' => $user->row()->last_login,
                    'last_logout' => $user->row()->last_logout,
                    'ip_address' => $user->row()->ip_address,
                    'employee_id' => $employee_info->employee_id,
                    'first_name' => $employee_info->first_name,
                    'last_name' => $employee_info->last_name,
                    'supervisor' => $employee_info->is_super_visor,
                    'permission' => json_encode(@$permission),
                    'label_permission' => json_encode(@$permission1),
                    'userRole' => $userRole,
                    'fyear' => $fyear->id,
                    'fyearName' => $fyear->yearName,
                    'fyearStartDate' => $fyear->startDate,
                    'fyearEndDate' => $fyear->endDate,
                );

                $this->session->set_userdata($sData);
                $this->auth_model->last_login();
                $this->session->set_flashdata('message', display('welcome_back') . ' ' . $user->row()->fullname);

                // Redirect based on the stored redirect URL or default to dashboard
                $redirect_url = $this->session->userdata('redirect_url');
                $this->session->unset_userdata('redirect_url');
                redirect($redirect_url ? $redirect_url : 'dashboard/home');
            }
        } else {
            $this->session->set_flashdata('exception', display('incorrect_email_or_password'));
            redirect('login');
        }
    } else {
        $captcha = create_captcha(array(
            'img_path' => './assets/img/captcha/',
            'img_url' => base_url('assets/img/captcha/'),
            'font_path' => './assets/fonts/captcha.ttf',
            'img_width' => '300',
            'img_height' => 64,
            'expiration' => 600, //5 min
            'word_length' => 4,
            'font_size' => 26,
            'img_id' => 'Imageid',
            'pool' => '0123456789abcdefghijklmnopqrstuvwxyz',
            'colors' => array(
                'background' => array(255, 255, 255),
                'border' => array(228, 229, 231),
                'text' => array(49, 141, 1),
                'grid' => array(241, 243, 246)
            )
        ));
        $data['captcha_word'] = $captcha['word'];
        $data['captcha_image'] = $captcha['image'];
        $this->session->set_userdata('captcha', $captcha['word']);

        echo Modules::run('template/login', $data);
    }
}

  
	public function logout()
	{ 
		//update database status
		$this->auth_model->last_logout();
		//destroy session
		$this->session->sess_destroy();
		redirect('login');
	}
    /*
 |--------------------------------------------------------
 | Finger print Device information
 |--------------------------------------------------------
 */
	

	//Register method
    public function register() {
        if ($this->session->userdata('isLogIn'))
            redirect('dashboard/home');

        $data['title'] = 'Register';

        // Load the view from the template module
        echo Modules::run('template/register_view', $data);
    }


    // Register Submit method
	public function register_submit() {
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
		$this->form_validation->set_rules('first_name', 'First Name', 'required|trim');
		$this->form_validation->set_rules('last_name', 'Last Name', 'required|trim');
		$this->form_validation->set_rules('gender', 'Gender', 'required|trim');
		$this->form_validation->set_rules('designation', 'Job Title', 'required|trim');
		$this->form_validation->set_rules('present_salary_category', 'Present Salary Category', 'required|trim');
		$this->form_validation->set_rules('date_of_employment', 'Date Of Employment', 'required|trim');
		$this->form_validation->set_rules('date_of_last_promotion', 'Date and Grade of Last Promotion', 'required|trim');
		$this->form_validation->set_rules('directorate', 'Directorate', 'required|trim');
		$this->form_validation->set_rules('division', 'Department', 'required|trim');
		$this->form_validation->set_rules('appointment_confirmed', 'Appointment Confirmation', 'required|trim');
		$this->form_validation->set_rules('qualification', 'Qualifications', 'required|trim');
		$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|trim');
		$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]|trim');
		

		
	
		if ($this->form_validation->run() == FALSE) {

			$this->session->set_flashdata('validation_errors', validation_errors());
			$this->register();
		} else {
			$token = $this->generate_token();
            $expires_at = date('Y-m-d H:i:s', strtotime('+60 minutes'));
			$data['user'] = (object)$userLevelData = array(
				'firstname' => $this->input->post('first_name', true),
				'lastname' => $this->input->post('last_name', true),
				'about' => $this->input->post('about', true),
				'email' => $this->input->post('email', true),
				'gender' => $this->input->post('gender', true),
				'job_title' => $this->input->post('designation', true),
				'present_salary_category' => $this->input->post('present_salary_category', true),
				'directorate' => $this->input->post('directorate', true),
				'department' => $this->input->post('division',true),
				'qualification' => $this->input->post('qualification', true),
				'date_of_employment' => $this->input->post('date_of_employment', true),
				'date_of_last_promotion' => $this->input->post('date_of_last_promotion', true),
				'appointment_confirmed' => $this->input->post('appointment_confirmed', true),
				'password' => md5($this->input->post('password', true)),
				'id_card' => null,
				'payslip' => null,
				'image' => (!empty($image) ? $image : null),
				'last_login' => null,
				'last_logout' => null,
				'ip_address' => null,
				'status' => 0,
				'is_admin' => 0,
				'token' => $token,
				'token_expires_at' => $expires_at

			);

			$academic_institution = $this->input->post('academic_institution', true);
			$academic_duration_from = $this->input->post('academic_duration_from', true);
			$academic_duration_to = $this->input->post('academic_duration_to', true);
			$academic_qualification = $this->input->post('academic_qualification', true);

			$professional_qualification = $this->input->post('professional_qualification', true);
			$professional_awarding_body = $this->input->post('professional_awarding_body', true);
			$professional_date_of_award = $this->input->post('professional_date_of_award', true);

	
			$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('login');

			}else{

				if ($this->user_model->create($userLevelData)) {
					//var_dump($userLevelData);
					for ($i = 0; $i < count($academic_institution); $i++) {
						$academic_data = array(
							'user_email' => $employee_email, 
							'institution' => $academic_institution[$i],
							'duration_from' => $academic_duration_from[$i],
							'duration_to' => $academic_duration_to[$i],
							'qualification' => $academic_qualification[$i]
						);
						$this->db->insert('academic', $academic_data);
					}
					
					for ($i = 0; $i < count($professional_qualification); $i++) {
						$professional_data = array(
							'user_email' => $employee_email,
							'qualification' => $professional_qualification[$i],
							'awarding_body' => $professional_awarding_body[$i],
							'date_of_award' => $professional_date_of_award[$i]
						);
						$this->db->insert('professional', $professional_data);
					}
					$this->_send_verification_email($employee_email, $token);
					$this->session->set_flashdata('message', display('Registration successful! Please check your email to verify your account.'));
				} else {
					$this->session->set_flashdata('exception', display('please_try_again'));
				}
				redirect('register/success');

			}

	
			
		}
	}
	

    public function register_success() {
        $data['title'] = 'Registration Successful';
        echo Modules::run('template/registration_success_view', $data);
    }


	private function _send_verification_email($email, $token) {
        $verification_link = base_url("register/verify_token/$token");

        $message = "Please click the following link to verify your email address: $verification_link";

        $this->email->from('no-reply@pti.tppa-ng.com', 'PTI APPRAISAL');
        $this->email->to($email);
        $this->email->subject('Email Verification');
        $this->email->message($message);

        if (!$this->email->send()) {
            log_message('error', 'Email not sent: '.$this->email->print_debugger());
        }
    }

	public function verify($token) {
        $user = $this->user_model->get_user_by_token($token);

        if ($user && strtotime($user->token_expires_at) > time()) {
            // Token is valid and not expired
           

			 // 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' => 3,
				'phone' => 1,
				'alter_phone' => 1,
				'present_address' => 1,
				'parmanent_address' => 1,
				'picture' => '',
				'dept_id' => 1,
				'state' => 'Delta',
				'city' => 'warri',
				'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' => 2,
				'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' => 0,
				'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' => $user->id,
				'pos_id'=> $user->job_title,
				'first_name' => $user->firstname,
				'last_name' => $user->lastname,
				'email' => $user->email,
				'password' => $user->password,
				'gender' => $user->gender,
				'dept_id' => $user->department,
				
			];

			//User Role is being assigned
			(object)$empUserRole = array(
				'fk_role_id' => 1,
				'fk_user_id' => $user->id
			);

			// Update the default values with specific values
			$postData = array_merge($defaultValues, $specificValues);
			if (!empty($postData['employee_id'])) {
        // Load your secondary database configuration
        $employee_email = $user->email;
		$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->user_model->createRole($empUserRole);
				$this->user_model->verify_user($user->id);
				$this->session->set_flashdata('message', 'Email verified successfully! You can now log in.');
            redirect('login');
			
			} 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.'
		];
	}        
        } else {
            // Token is invalid or expired
            $this->session->set_flashdata('exception', 'Invalid or expired token. Please register again.');
            redirect('register');
        }
    }

	public function resend() {
        if ($this->session->userdata('isLogIn'))
            redirect('dashboard/home');

        $data['title'] = 'Resend Token';

        // Load the view from the template module
        echo Modules::run('template/resend_activation', $data);
    }

	public function resend_activation() {
        // Set validation rules
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');

        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('exception', validation_errors());
            redirect('register/resend');
        } else {
            $email = $this->input->post('email');
            $user = $this->user_model->get_user_by_email($email);

            if ($user && $user->status == 0) {
                $token = $this->generate_token();
                $expires_at = date('Y-m-d H:i:s', strtotime('+60 minutes'));

                // Update user data with new token and expiration time
                $data = array(
                    'token' => $token,
                    'token_expires_at' => $expires_at
                );

                if ($this->user_model->update_user($user->id, $data)) {
                    $this->_send_verification_email($email, $token);
                    $this->session->set_flashdata('message', 'A new activation email has been sent. Please check your email to verify your account.');
                    redirect('register/success');
                } else {
                    $this->session->set_flashdata('exception', 'An error occurred while resending the activation email. Please try again.');
                    redirect('register/resend');
                }
            } else {
                $this->session->set_flashdata('exception', 'Email not found or already verified.');
                redirect('register/resend');
            }
        }
	}


	public function verify_token($token = null) {
        if ($this->session->userdata('isLogIn'))
            redirect('dashboard/home');

			if (!$token || !$this->validate_register_token($token)) {
				$this->session->set_flashdata('exception', 'Invalid or expired token. Please request a new activation link. ');
				redirect('register/resend_activation');
			}

        
		$user = $this->user_model->get_user_by_token($token);
		$token_id = $user->token;
		$id = $user->id;
		if($this->user_model->get_user_exp_by_id($id)){
			redirect("register/verify/" . $token);
		}

		$data['title'] = 'Verification';
		$data['employeeId'] = $id;
		$data['staffStatus'] = $user->job_title;
		$data['token'] = $token;
		


        // Load the view from the template module
        echo Modules::run('template/register_verify', $data);
    }

	// Function to validate the reset token
private function validate_register_token($token) {
    $user = $this->user_model->get_user_by_token($token);

    if ($user && strtotime($user->token_expires_at) > time()) {
        return true;
    }

    return false;
}

public function token_submit($token = null)
{
    // Set up validation rules
    $this->form_validation->set_rules('employee_id', 'Employee ID', 'required');
    
    // Check if form validation fails
    if ($this->form_validation->run() == FALSE) {
        $this->session->set_flashdata('exception', validation_errors());
        redirect('register/verify_token/' . $token); // Ensure $token is correctly appended to the URL
    } else {
        // Retrieve all form inputs
        $id = $this->input->post('employee_id', true);
        $token = $this->input->post('user_token', true); // This overwrites the $token variable

        // Teaching Experience
        $institutions = $this->input->post('exp_institutions', true);
        $designations = $this->input->post('exp_designation', true);
        $specializations = $this->input->post('exp_specialization', true);
        $subjects = $this->input->post('exp_subject', true);
        $dates = $this->input->post('exp_date', true);

        // Professional Experience
        $institutions_prof = $this->input->post('exp_institutions_professional', true);
        $designations_prof = $this->input->post('exp_designation_professional', true);
        $duties_prof = $this->input->post('exp_duty_professional', true);
        $dates_start_prof = $this->input->post('exp_date_start_professional', true);
        $dates_end_prof = $this->input->post('exp_date_end_professional', true);

        // Research Experience
        $topics_research = $this->input->post('exp_researh_topic', true);
        $dates_research = $this->input->post('exp_researh_date', true);

        // Unpublished Research
        $topics_unpublish = $this->input->post('exp_unpublish_topic', true);
        $reads_unpublish = $this->input->post('exp_unpublish_read', true);
        $dates_unpublish = $this->input->post('exp_unpublish_date', true);

        // Other inputs
        $exp_description = $this->input->post('exp_description', true);
        $recognized_publications = $this->input->post('recognised_publications', true);
        $exp_other_activities = $this->input->post('exp_other_activities', true);
        $exp_other_activities_out = $this->input->post('exp_other_activities_out', true);
        $exp_serve_date_end = $this->input->post('exp_serve_date_end', true);

        // Key Goals and Duties
        $key_goals = $this->input->post('key_goals', true);
        $key_duties_res = $this->input->post('duties_responsibilites', true);
        $special_contributions = $this->input->post('special_contributions', true);
        $duties_perf_circumstances = $this->input->post('duties_perf_circumstances', true);
        $duties_perf_circumstances_bad = $this->input->post('duties_perf_circumstances_bad', true);

        // Initialize arrays for storing data
        $teaching_experience = [];
        $professional_experience = [];
        $research_experience = [];
        $research_unpublish_experience = [];
        $key_duties_res_data = [];
        $key_goals_data = [];

        // Process Teaching Experience
        if (!empty($institutions)) {
            for ($i = 0; $i < count($institutions); $i++) {
                $teaching_experience[] = [
                    'institution' => $institutions[$i] ?? '',
                    'designation' => $designations[$i] ?? '',
                    'specialization' => $specializations[$i] ?? '',
                    'subject' => $subjects[$i] ?? '',
                    'date' => $dates[$i] ?? '',
                ];
            }
        }

        // Process Professional Experience
        if (!empty($institutions_prof)) {
            for ($i = 0; $i < count($institutions_prof); $i++) {
                $professional_experience[] = [
                    'institution' => $institutions_prof[$i] ?? '',
                    'designation' => $designations_prof[$i] ?? '',
                    'duty' => $duties_prof[$i] ?? '',
                    'date_start' => $dates_start_prof[$i] ?? '',
                    'date_end' => $dates_end_prof[$i] ?? '',
                ];
            }
        }

        // Process Research Experience
        if (!empty($topics_research)) {
            for ($i = 0; $i < count($topics_research); $i++) {
                $research_experience[] = [
                    'topic' => $topics_research[$i] ?? '',
                    'date' => $dates_research[$i] ?? '',
                ];
            }
        }

        // Process Unpublished Research Experience
        if (!empty($topics_unpublish)) {
            for ($i = 0; $i < count($topics_unpublish); $i++) {
                $research_unpublish_experience[] = [
                    'topic' => $topics_unpublish[$i] ?? '',
                    'read' => $reads_unpublish[$i] ?? '',
                    'date' => $dates_unpublish[$i] ?? '',
                ];
            }
        }

        // Process Key Duties and Responsibilities
        if (!empty($key_duties_res)) {
            for ($i = 0; $i < count($key_duties_res); $i++) {
                $key_duties_res_data[] = [
                    'duties_responsibilites' => $key_duties_res[$i] ?? '',
                    'special_contributions' => $special_contributions[$i] ?? null,
                    'duties_perf_circumstances' => $duties_perf_circumstances[$i] ?? null,
                    'duties_perf_circumstances_bad' => $duties_perf_circumstances_bad[$i] ?? null,
                ];
            }
        }

        // Process Key Goals
        if (!empty($key_goals)) {
            for ($i = 0; $i < count($key_goals); $i++) {
                $key_goals_data[] = [
                    'key_goals' => $key_goals[$i] ?? '',
                ];
            }
        }

        // Prepare data to be inserted
        $emp_exp_data = [
            'emp_per_id' => $id,
            'exp_teaching' => json_encode($teaching_experience),
            'exp_professional' => json_encode($professional_experience),
            'exp_description' => $exp_description,
            'exp_research' => json_encode($research_experience),
            'recognized_publications' => $recognized_publications,
            'exp_research_unpublish' => json_encode($research_unpublish_experience),
            'exp_other_activities' => $exp_other_activities,
            'exp_other_activities_out' => $exp_other_activities_out,
            'key_goals' => json_encode($key_goals_data),
            'key_duties_res' => json_encode($key_duties_res_data),
            'exp_serve_date_end' => $exp_serve_date_end
        ];

        // Insert data into the database
        $this->db->insert('user_emp_exp', $emp_exp_data);

        // Redirect back with the token
        redirect('register/verify/' . $token);
    }
}


	public function callback_file_check($str, $field)
{
    // Retrieve the file
    $file = $_FILES[$field];

    // Check if a file was uploaded
    if (isset($file['name']) && $file['name'] != '') {
        // Get the file extension
        $allowed_mime_type_arr = array('pdf', 'jpg', 'jpeg', 'png');
        $mime = pathinfo($file['name'], PATHINFO_EXTENSION);

        // Check file size (500KB)
        if ($file['size'] > 512000) {
            $this->form_validation->set_message('file_check', 'The {field} field must not exceed 500KB in size.');
            return FALSE;
        }

        // Check file type
        if (!in_array($mime, $allowed_mime_type_arr)) {
            $this->form_validation->set_message('file_check', 'The {field} field must contain only pdf, jpg, jpeg, or png files.');
            return FALSE;
        }

        return TRUE;
    } else {
        $this->form_validation->set_message('file_check', 'The {field} field is required.');
        return FALSE;
    }
}


    // Upload file method
    private function upload_file($field) {
        $config['upload_path'] = './assets/img/user/';
        $config['allowed_types'] = 'pdf|jpg|png';
        $config['max_size'] = 500;
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload($field)) {
            return '';
        } else {
            return $this->upload->data('file_name');
        }
    }

	//Password reset method
    public function request() {
        if ($this->session->userdata('isLogIn'))
        redirect('dashboard/home');

        $data['title'] = 'Reset Password';

        // Load the view from the template module
        echo Modules::run('template/request', $data);
    }

	public function submit_reset() {
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');

        if ($this->form_validation->run() == FALSE) {
            redirect('password_reset/request');
        } else {
            $email = $this->input->post('email');
            $user = $this->user_model->get_user_by_email($email);

            if ($user) {
                $token = $this->generate_token();
                $expires_at = date('Y-m-d H:i:s', strtotime('+1 hour'));

                $data = array(
                    'password_reset_token' => $token,
                    'reset_expires_at' => $expires_at
                );

                if ($this->user_model->update_user($user->id, $data)) {
                    $this->_send_reset_email($email, $token);
                    $this->session->set_flashdata('message', 'Password reset email sent! Please check your email.');
                    redirect('password_reset/request_reset');
                } else {
                    $this->session->set_flashdata('exception', 'An error occurred while sending the password reset email. Please try again.');
                    redirect('password_reset/request_reset');
                }
            } else {
                $this->session->set_flashdata('exception', 'Email not found.');
                redirect('password_reset/request_reset');
            }
        }
    }

    private function _send_reset_email($email, $token) {
        $reset_link = base_url("password_reset/$token");

        $message = "Please click the following link to reset your password: $reset_link";

        $this->email->from('no-reply@pti.tppa-ng.com', 'PTI APPRAISAL');
        $this->email->to($email);
        $this->email->subject('Password Reset');
        $this->email->message($message);

        if (!$this->email->send()) {
            log_message('error', 'Email not sent: '.$this->email->print_debugger());
        }
    }

	public function reset_password($token = null) {
		// Redirect logged-in users to the dashboard
		if ($this->session->userdata('isLogIn')) {
			redirect('dashboard/home');
		}
	
		// If no token is provided, or if the token is invalid or expired, redirect to the request reset page
		if (!$token || !$this->validate_reset_token($token)) {
			$this->session->set_flashdata('exception', 'Invalid or expired token. Please request a new password reset. ');
			redirect('password_reset/request_reset');
		}
	
		// If the token is valid, load the reset password form
		$data['title'] = 'Reset Password';
		$data['token'] = $token; // Pass the token to the view for form submission
		echo Modules::run('template/reset', $data);
	}
	
	// Function to validate the reset token
private function validate_reset_token($token) {
    $user = $this->user_model->get_user_by_reset_token($token);

    if ($user && strtotime($user->reset_expires_at) > time()) {
        return true;
    }

    return false;
}

    public function reset($token) {
        $user = $this->user_model->get_user_by_reset_token($token);

        if ($user && strtotime($user->reset_expires_at) > time()) {
            // Token is valid and not expired
            $this->form_validation->set_rules('password', 'Password', 'required|min_length[8]');
            $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');

            if ($this->form_validation->run() == FALSE) {
                $this->load->view('password_reset/reset', array('token' => $token));
            } else {
                // $password = password_hash($this->input->post('password'), PASSWORD_BCRYPT);
                $password = md5($this->input->post('password', true));
                $data = array(
                    'password' => $password,
                    'password_reset_token' => NULL,
                    'reset_expires_at' => NULL
                );

                if ($this->user_model->update_user($user->id, $data)) {
                    $this->session->set_flashdata('message', 'Password reset successfully! You can now log in.');
                    redirect('login');
                } else {
                    $this->session->set_flashdata('exception', 'An error occurred while resetting the password. Please try again.');
                    $this->load->view('password_reset/reset', array('token' => $token));
                }
            }
        } else {
            // Token is invalid or expired
            $this->session->set_flashdata('exception', 'Invalid or expired token. Please request a new password reset.');
            redirect('password_reset/request_reset');
        }
    }

}
