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

class Employees extends MX_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->db->query('SET SESSION sql_mode = ""');
        $this->load->model(array(
            'Employees_model',
            'Country_model'

        ));

        $this->load->model('rewardpoint/rewardpoints_model');

        if (!$this->session->userdata('isLogIn'))
            redirect('login');

        $this->load->library('excel');
    }

    /* ################ Employee Salary Setup Start   #######################....*/

    public function emp_salary_setup_view()
    {
        $this->permission->module('employee', 'read')->redirect();

        $data['title'] = display('view_salary_setup');;
        $data['emp_sl'] = $this->Employees_model->salary_setupView();
        $data['module'] = "employee";
        $data['page'] = "emp_sal_setupview";
        echo Modules::run('template/layout', $data);
    }


    public function create_salary_setup()
    {
        $data['title'] = display('selectionlist');
        #-------------------------------#
        $this->form_validation->set_rules('emp_sal_name', display('emp_sal_name'), 'required|max_length[50]');
        $this->form_validation->set_rules('emp_sal_type', display('emp_sal_type'));

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

            $postData = [
                'emp_sal_name' => $this->input->post('emp_sal_name', true),
                'emp_sal_type' => $this->input->post('emp_sal_type', true),
            ];

            if ($this->Employees_model->emp_salsetup_create($postData)) {
                $this->session->set_flashdata('message', display('message_sent'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
            redirect("employee/Employees/create_salary_setup");


        } else {
            $data['title'] = display('create');
            $data['module'] = "employee";
            $data['page'] = "emp_salarysetup_form";
            echo Modules::run('template/layout', $data);

        }
    }

    public function delete_emp_salarysetup($id = null)
    {
        $this->permission->module('employee', 'delete')->redirect();

        if ($this->Employees_model->emp_salstup_delete($id)) {
            #set success message
            $this->session->set_flashdata('message', display('delete_successfully'));
        } else {
            #set exception message
            $this->session->set_flashdata('exception', display('please_try_again'));
        }
        redirect("employee/Employees/emp_salary_setup_view");
    }


    public function update_salsetup_form($id = null)
    {
        $this->form_validation->set_rules('emp_sal_set_id', null, 'required|max_length[11]');
        $this->form_validation->set_rules('emp_sal_name', display('emp_sal_name'), 'required|max_length[50]');
        $this->form_validation->set_rules('emp_sal_type', display('emp_sal_type'), 'required|max_length[20]');
        #-------------------------------#
        if ($this->form_validation->run() === true) {

            $postData = [
                'emp_sal_set_id' => $this->input->post('emp_sal_set_id', true),
                'emp_sal_name' => $this->input->post('emp_sal_name', true),
                'emp_sal_type' => $this->input->post('emp_sal_type', true),
            ];

            if ($this->Employees_model->update_em_salstup($postData)) {
                $this->session->set_flashdata('message', display('message_sent'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
            redirect("employee/Employees/update_salsetup_form/" . $id);

        } else {
            $data['title'] = display('update');
            $data['data'] = $this->Employees_model->salarysetup_updateForm($id);
            $data['module'] = "employee";
            $data['page'] = "update_salarysetup_form";
            echo Modules::run('template/layout', $data);
        }

    }

    /* ################ Employee Salary Setup End   #######################....*/
    /* <<<<<<<<<<<<<##############^^^^^^@@@@^^^^^###############>>>>>>>

    /* ################ Employee Performance Start   #######################....*/

    public function emp_performance_view()
    {
        $this->permission->module('employee', 'read')->redirect();

        $data['title'] = display('view_employee_performance');;
        $data['emp_perform'] = $this->Employees_model->emp_performanceView();
        $data['module'] = "employee";
        $data['page'] = "emp_performanceview";
        echo Modules::run('template/layout', $data);
    }


    public function create_emp_performance()
    {
        $data['title'] = display('performancelist');
        #-------------------------------#
        $this->form_validation->set_rules('employee_id', display('employee_id'), 'required|max_length[50]');
        $this->form_validation->set_rules('note', display('note'), 'max_length[200]');
        $this->form_validation->set_rules('date', display('date'));
        $this->form_validation->set_rules('number_of_star', display('number_of_star'), 'required|max_length[1]');
        $this->form_validation->set_rules('status', display('status'));
        #-------------------------------#
        if ($this->form_validation->run() === true) {
            $postData = [
                'employee_id' => $this->input->post('employee_id', true),
                'note' => $this->input->post('note', true),
                'date' => $this->input->post('date', true),
                'note_by' => $this->session->userdata('fullname'),
                'number_of_star' => $this->input->post('number_of_star', true),
                'status' => $this->input->post('status', true),
            ];

            if ($this->Employees_model->emp_performance_create($postData)) {
                $this->session->set_flashdata('message', display('successfully_saved'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
            redirect("employee/Employees/create_emp_performance");
        } else {
            $data['title'] = display('create');
            $data['module'] = "employee";
            $data['page'] = "emp_performance_form";
            $data['employee'] = $this->Employees_model->employee();
            $data['emp_perform'] = $this->Employees_model->emp_performanceView();
            echo Modules::run('template/layout', $data);

        }
    }

    public function delete_emp_performance($id = null)
    {
        $this->permission->module('employee', 'delete')->redirect();

        if ($this->Employees_model->emp_performance_delete($id)) {
            #set success message
            $this->session->set_flashdata('message', display('delete_successfully'));
        } else {
            #set exception message
            $this->session->set_flashdata('exception', display('please_try_again'));
        }
        redirect("employee/Employees/emp_performance_view");
    }


    public function update_emp_performance_form($id = null)
    {
        $this->form_validation->set_rules('emp_per_id', null, 'max_length[11]');
        $this->form_validation->set_rules('employee_id', display('employee_id'), 'max_length[50]');
        $this->form_validation->set_rules('note', display('note'), 'max_length[200]');
        $this->form_validation->set_rules('date', display('date'));
        $this->form_validation->set_rules('note_by', display('note_by'));
        $this->form_validation->set_rules('number_of_star', display('number_of_star'), 'required|max_length[1]');
        $this->form_validation->set_rules('status', display('status'));

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

            $postData = [
                'emp_per_id' => $this->input->post('emp_per_id', true),
                'employee_id' => $this->input->post('employee_id', true),
                'note' => $this->input->post('note', true),
                'date' => $this->input->post('date', true),
                'note_by' => $this->input->post('note_by', true),
                'number_of_star' => $this->input->post('number_of_star', true),
                'status' => $this->input->post('status', true),
                'updated_by' => $this->session->userdata('fullname'),
            ];

            if ($this->Employees_model->update_em_performance($postData)) {
                $this->session->set_flashdata('message', display('successfully_updated'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
            redirect("employee/Employees/update_emp_performance_form/" . $id);

        } else {
            $data['title'] = display('update');
            $data['data'] = $this->Employees_model->emp_performance_updateForm($id);
            $data['query'] = $this->Employees_model->get_performaceempid($id);
            $data['employee'] = $this->Employees_model->employee();
            $data['module'] = "employee";
            $data['page'] = "update_performance_form";
            echo Modules::run('template/layout', $data);
        }

    }

    /* ################ Employee Performance End   #######################....*/


    /* ################ Employee Payment start   #######################....*/

    public function create_payment()
    {
        $data['title'] = display('add_payment');
        #-------------------------------#
        $this->form_validation->set_rules('employee_id', display('employee_id'), 'max_length[50]');
        $this->form_validation->set_rules('total_salary', display('total_salary'));
        $this->form_validation->set_rules('total_working_minutes', display('total_working_minutes'));
        $this->form_validation->set_rules('working_period', display('working_period'));
        $this->form_validation->set_rules('payment_due', display('payment_due'));
        $this->form_validation->set_rules('payment_date', display('payment_date'));
        $this->form_validation->set_rules('paid_by', display('paid_by'));


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

            $postData = [
                'employee_id' => $this->input->post('employee_id', true),
                'total_salary' => $this->input->post('total_salary', true),
                'total_working_minutes' => $this->input->post('total_working_minutes', true),
                'working_period' => $this->input->post('working_period', true),
                'payment_due' => $this->input->post('payment_due', true),
                'payment_date' => $this->input->post('payment_date', true),
                'paid_by' => $this->input->post('paid_by', true),
            ];

            if ($this->Employees_model->create_employee_payment($postData)) {
                $this->session->set_flashdata('message', display('message_sent'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
            redirect("employee/Employees/create_payment");


        } else {
            $data['title'] = display('create');
            $data['module'] = "employee";
            $data['page'] = "emp_payment_form";
            echo Modules::run('template/layout', $data);

        }
    }


    public function delete_payment($id = null)
    {
        $this->permission->module('employee', 'delete')->redirect();

        if ($this->Employees_model->emp_payment_delete($id)) {
            #set success message
            $this->session->set_flashdata('message', display('delete_successfully'));
        } else {
            #set exception message
            $this->session->set_flashdata('exception', display('please_try_again'));
        }
        redirect($_SERVER['HTTP_REFERER']);
    }


    public function update_payment_form($id = null)
    {
        $this->form_validation->set_rules('emp_sal_pay_id', null, 'required|max_length[11]');
        $this->form_validation->set_rules('employee_id', display('employee_id'), 'max_length[50]');
        $this->form_validation->set_rules('total_salary', display('total_salary'));
        $this->form_validation->set_rules('total_working_minutes', display('total_working_minutes'));
        $this->form_validation->set_rules('working_period', display('working_period'));
        $this->form_validation->set_rules('payment_due', display('payment_due'));
        $this->form_validation->set_rules('payment_date', display('payment_date'));

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

            $postData = [
                'emp_sal_pay_id' => $this->input->post('emp_sal_pay_id', true),
                'employee_id' => $this->input->post('employee_id', true),
                'total_salary' => $this->input->post('total_salary', true),
                'total_working_minutes' => $this->input->post('total_working_minutes', true),
                'working_period' => $this->input->post('working_period', true),
                'payment_due' => $this->input->post('payment_due', true),
                'payment_date' => $this->input->post('payment_date', true),
                'paid_by' => $this->session->userdata('fullname'),
            ];

            if ($this->Employees_model->update_payment($postData)) {
                $this->session->set_flashdata('message', display('successfully_paid'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
            redirect("employee/Employees/emp_payment_view/" . $id);

        } else {
            $data['title'] = display('update');
            $data['data'] = $this->Employees_model->payment_updateForm($id);
            $data['module'] = "employee";
            $data['page'] = "update_payment_form";
            echo Modules::run('template/layout', $data);
        }

    }

    /* ################ Employee Payment end   #######################....*/


    /* ################ Employee Salary Pay Type Start   #######################....*/


    public function emp_sal_payType_view()
    {
        $this->permission->module('employee', 'read')->redirect();

        $data['title'] = display('view_employee_payment');;
        $data['paytype'] = $this->Employees_model->emp_salPaytypeView();
        $data['module'] = "employee";
        $data['page'] = "sal_pay_type_tview";
        echo Modules::run('template/layout', $data);
    }

    public function create_payment_type()
    {
        $data['title'] = display('add_payment_type');
        $this->form_validation->set_rules('payment_period', display('payment_period'), 'required|max_length[50]');
        #-------------------------------#
        if ($this->form_validation->run() === true) {

            $postData = [
                'payment_period' => $this->input->post('payment_period', true),
            ];

            if ($this->Employees_model->insert_payment_type($postData)) {
                $this->session->set_flashdata('message', display('message_sent'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
            redirect("employee/Employees/create_payment_type");


        } else {
            $data['title'] = display('create');
            $data['module'] = "employee";
            $data['page'] = "emp_payment_type_form";
            echo Modules::run('template/layout', $data);

        }
    }

    public function delete_payment_type($id = null)
    {
        $this->permission->module('employee', 'delete')->redirect();

        if ($this->Employees_model->emp_payment_type_delete($id)) {
            #set success message
            $this->session->set_flashdata('message', display('delete_successfully'));
        } else {
            #set exception message
            $this->session->set_flashdata('exception', display('please_try_again'));
        }
        redirect("employee/Employees/emp_sal_payType_view");
    }


    /* cv    */
    public function cv()
    {
        $this->permission->module('circularprocess', 'read')->redirect();

        $data['title'] = display('view details');
        $id = $this->uri->segment(4);
        $data['row'] = $this->Employees_model->employee_details($id);
        $data['edu'] = $this->Employees_model->updateedu($id);
        $data['benifit'] = $this->Employees_model->benifit($id);
        $data['award'] = $this->Employees_model->award($id);
        $data['perform'] = $this->Employees_model->performance($id);
        $data['salarylog'] = $this->Employees_model->salary_log_single($id);
        $data['warnings'] = $this->Employees_model->get_warnings($id);
        $data['module'] = "employee";
        $data['page'] = "resumepdf";
        echo Modules::run('template/layout', $data);
    }

    /* ########## NEW EMPLOYEE ADD ################*/
    public function viewEmhistory()
    {
        $this->permission->module('employee', 'read')->redirect();

        $data['title'] = display('view_salary_setup');;
        $data['emp_history'] = $this->Employees_model->emp_historyview();
        $data['module'] = "employee";
        $data['designation'] = $this->Employees_model->designation();
        $data['dropdowndept'] = $this->Employees_model->dropdowndept();
        $data['benefitlist'] = $this->Employees_model->benefit_list_dropdown();
        $data['skillslist'] = $this->Employees_model->skills_list_dropdown();
        $data['supervisor'] = $this->Employees_model->supervisorlist();
        $data['emplist'] = $this->Employees_model->emp_list_dropdown();
        $data['country_list'] = $this->Country_model->state();
        $data['page'] = "employ_form";
        echo Modules::run('template/layout', $data);
    }


    public function manageemployee()
    {
        $this->permission->module('employee', 'read')->redirect();

        $data['title'] = display('view_salary_setup');;
        $data['emp_history'] = $this->Employees_model->emp_list();
        $data['module'] = "employee";
        $data['designation'] = $this->Employees_model->designation(); // Set By Inam
        $data['page'] = "employee_view";
        echo Modules::run('template/layout', $data);
    }

    public function excel()
    {
        $file_name = 'Employee_details_on_' . date('Ymd') . '.csv';
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$file_name");
        header("Content-Type: application/csv;");

        // get data
        $Employee_data = $this->Employees_model->emp_list();
        // file creation
        $file = fopen('php://output', 'w');
        $header = array("emp_his_id", "employee_id", "employee_status", "position", "first_name",
            "middle_name",
            "last_name",
            "emp_code",
            "email",
            "personal_email",
            "phone",
            "alter_phone",
            "emp_cnic",
            "emp_exp_start_date",
            "emp_exp_end_date",
            "emp_address",
            "masters_degree_title",
            "masters_majors",
            "masters_year_completion",
            "masters_institute",
            "masters_location",
            "masters_cgpa",
            "bachelors_degree_title",
            "bachelors_majors",
            "bachelors_year_completion",
            "bachelors_institute",
            "bachelors_location",
            "bachelors_cgpa",
            "inter_degree_title",
            "inter_majors",
            "inter_year_completion",
            "inter_institute",
            "inter_location",
            "inter_percentage",
            "matric_degree_title",
            "matric_majors",
            "matric_year_completion",
            "matric_institute",
            "matric_location",
            "matric_percentage",
            "master_attachment",
            "bachelors_attachment",
            "inter_attachment",
            "matric_attachment",
            "present_address",
            "parmanent_address",
            "picture",
            "degree_name",
            "university_name",
            "cgp",
            "passing_year",
            "company_name",
            "working_period",
            "duties",
            "benefit_name",
            "emp_grade",
            "benefit_accural_date",
            "benefit_status",
            "supervisor",
            "signature",
            "is_admin",
            "department",
            "division_id",
            "maiden_name",
            "state",
            "city",
            "zip",
            "citizenship",
            "account_title",
            "bank_name",
            "account_number",
            "iban_number",
            "duty_type",
            "hire_date",
            "original_hire_date",
            "warning",
            "termination_date",
            "termination_reason",
            "voluntary_termination",
            "rehire_date",
            "rate_type",
            "rate",
            "pay_frequency",
            "pay_frequency_txt",
            "hourly_rate2",
            "hourly_rate3",
            "home_department",
            "department_text",
            "class_code",
            "class_code_desc",
            "class_acc_date",
            "class_status",
            "is_super_visor",
            "super_visor_id",
            "supervisor_report",
            "dob",
            "gender",
            "marital_status",
            "ethnic_group",
            "eeo_class_gp",
            "ssn",
            "work_in_state",
            "live_in_state",
            "home_email",
            "business_email",
            "home_phone",
            "business_phone",
            "cell_phone",
            "emerg_contct",
            "emrg_h_phone",
            "emrg_w_phone",
            "emgr_contct_relation",
            "alt_em_contct",
            "alt_emg_h_phone",
            "alt_emg_w_phone",
            "name_emg_contact_person_1",
            "relation_emg_contact_person_1",
            "phone_emg_contact_person_1",
            "alt_phone_emg_contact_person_1",
            "name_emg_contact_person_2",
            "relation_emg_contact_person_2",
            "phone_emg_contact_person_2",
            "alt_phone_emg_contact_person_2",
            "password",
            "resume",
            "id_card_front",
            "id_card_back",
            "signed_nda",
            "signed_offer_letter",
            "req_diploma_check",
            "req_diploma_date",
            "req_diploma_file",
            "req_nbi_check",
            "req_nbi_date",
            "req_nbi_file",
            "req_birth_cert_check",
            "req_birth_cert_date",
            "req_birth_cert_file",
            "req_cert_married_check",
            "req_cert_married_date",
            "req_cert_married_file",
            "req_work_permit_check",
            "req_work_permit_date",
            "req_work_permit_file",
            "req_id_picture_check",
            "req_id_picture_date",
            "req_id_picture_file",
            "req_drug_test_check",
            "req_drug_test_date",
            "req_drug_test_file",
            "req_driver_license_check",
            "req_driver_license_date",
            "req_driver_license_file",
            "terminate",
            "terminate_date",
            "terminate_reason",
            "probation_start_date",
            "probation_end_date",
            "evaluation_by",
            "evaluation_status",
            "probation_status",
            "shift_start",
            "shift_end");


        fputcsv($file, $header);
        foreach ($Employee_data as $row) {
            $array = json_decode(json_encode($row), true);
            $array['pos_id'] = $array['position_name'];
            $array['position_name'] = "";
            $array['dept_id'] = $array['department_name'];
            $array['department_name'] = "";
            $array['super_visor_id'] = $array['super_visor'];
            $array['super_visor'] = "";
            $array['gender'] = $array['gender_name'];
            $array['gender_name'] = "";
            $array['marital_status'] = $array['marital_sta'];
            $array['marital_sta'] = "";
            $array['pay_frequency'] = $array['frequency_name'];
            $array['frequency_name'] = "";
            if($array['duty_type'] == 1){
                $array['duty_type'] = "Intern";
                $array['type_name'] = "";
            }
            elseif($array['duty_type'] == 2 ){
                $array['duty_type'] = "Full Time";
                $array['type_name'] = "";
            }
            elseif($array['duty_type'] == 3){
                $array['duty_type'] = "Part Time";
                $array['type_name'] = "";
            }
            elseif($array['duty_type'] == 4){
                $array['duty_type'] = "Contructual";
                $array['type_name'] = "";
            }
            else{
                $array['duty_type'] = "Other";
                $array['type_name'] = "";
            }

            if( $array['picture'] != ""){
                $array['picture'] = base_url() .  substr($array['picture'], 2);
            }
            fputcsv($file, $array);
        }
        fclose($file);
        exit;

    }

    public function create_employee()
    {
        /***** file upload code start ***********/
        #-------------------------------#

        $data['title'] = display('create_employee');
        #-------------------------------#

        $this->form_validation->set_rules('first_name', display('first_name'), 'required|max_length[50]');
        $this->form_validation->set_rules('last_name', display('last_name'), 'required|max_length[50]');
        $this->form_validation->set_rules('maiden_name', display('maiden_name'), 'max_length[50]');
        $this->form_validation->set_rules('present_address', display('present_address'), 'max_length[250]');
        $this->form_validation->set_rules('parmanent_address', display('parmanent_address'), 'max_length[250]');
        $this->form_validation->set_rules('termreason', display('termreason'), 'max_length[250]');
        $this->form_validation->set_rules('email', display('email'), 'required|valid_email|is_unique[employee_history.email]|max_length[50]');

        $this->load->library('myupload');
        $img = $this->myupload->do_upload(
            './application/modules/employee/assets/images/',
            'picture'

        );
        $resume_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'resume'
        );

        $id_card_front_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'id_card_front'
        );

        $id_card_back_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'id_card_back'
        );

        $signed_nda_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'signed_nda'
        );

        $signed_offer_letter_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'signed_offer_letter'
        );

        $master_attachment_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'master_attachment'
        );

        $bachelors_attachment_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'bachelors_attachment'
        );

        $inter_attachment_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'inter_attachment'
        );

        $matric_attachment_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'matric_attachment'
        );

        $req_diploma_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'req_diploma_file'
        );

        $req_nbi_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'req_nbi_file'
        );

        $req_birth_cert_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'req_birth_cert_file'
        );

        $req_cert_married_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'req_cert_married_file'
        );

        $req_work_permit_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'req_work_permit_file'
        );

        $req_id_picture_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'req_id_picture_file'
        );

        $req_drug_test_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'req_drug_test_file'
        );

        $req_driver_license_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs/',
            'req_driver_license_file'
        );

        $this->form_validation->set_rules('c_f_name[]', 'Custom Field Name');
        $this->form_validation->set_rules('c_f_type[]', 'Custom Field Type');
        $this->form_validation->set_rules('customvalue[]', 'Custom Value');
        $employee_h = $this->db->select('employee_id')
            ->from('employee_history')
            ->order_by('emp_his_id', 'desc')
            ->get()
            ->row();
        $max_id = $employee_h->employee_id;
        if (!empty($max_id)) {
            $employee_id = $max_id + 1;
        } else {
            $employee_id = 1;
        }
        $customr_field = $this->input->post('c_f_name', true);
        $customr_field_type = $this->input->post('c_f_type', true);
        $customr_value = $this->input->post('customvalue', true);
        $benifit_code = $this->input->post('benifit_c_code', true);
        $benifit_code_desc = $this->input->post('benifit_c_code_d', true);
        $benifit_acc_date = $this->input->post('benifit_acc_date', true);
        $benift_status = $this->input->post('benifit_sst', true);
        #-------------------------------#

        $p_e_company_name = $this->input->post('p_e_company_name', true);
        $p_e_start_date = $this->input->post('p_e_start_date', true);
        $p_e_end_date = $this->input->post('p_e_end_date', true);
        $p_e_skill_name = $this->input->post('p_e_skill_name', true);
        $p_e_designation = $this->input->post('p_e_designation', true);
        $p_e_location = $this->input->post('p_e_location', true);


        $c_t_name = $this->input->post('c_t_name', true);
        $c_t_start_date = $this->input->post('c_t_start_date', true);
        $c_t_end_date = $this->input->post('c_t_end_date', true);
        $c_t_institute = $this->input->post('c_t_institute', true);
        $c_t_location = $this->input->post('c_t_location', true);

        $dependent_name = $this->input->post('dependent_name', true);
        $dependent_relation = $this->input->post('dependent_relation', true);
        $dependent_cnic = $this->input->post('dependent_cnic', true);
        $dependent_dob = $this->input->post('dependent_dob', true);
        $dependent_benefit = $this->input->post('dependent_benefit', true);

        if ($resume_file == null) {
            $resume = '';
        } else {
            $resume = base_url() . $resume_file;
        }

        if ($id_card_front_file == null) {
            $id_card_front = '';
        } else {
            $id_card_front = base_url() . $id_card_front_file;
        }

        if ($id_card_back_file == null) {
            $id_card_back = '';
        } else {
            $id_card_back = base_url() . $id_card_back_file;
        }

        if ($signed_nda_file == null) {
            $signed_nda = '';
        } else {
            $signed_nda = base_url() . $signed_nda_file;
        }

        if ($signed_offer_letter_file == null) {
            $signed_offer_letter = '';
        } else {
            $signed_offer_letter = base_url() . $signed_offer_letter_file;
        }

        if ($master_attachment_file == null) {
            $master_attachment = '';
        } else {
            $master_attachment = base_url() . $master_attachment_file;
        }
        if ($bachelors_attachment_file == null) {
            $bachelors_attachment = '';
        } else {
            $bachelors_attachment = base_url() . $bachelors_attachment_file;
        }
        if ($inter_attachment_file == null) {
            $inter_attachment = '';
        } else {
            $inter_attachment = base_url() . $inter_attachment_file;
        }
        if ($matric_attachment_file == null) {
            $matric_attachment = '';
        } else {
            $matric_attachment = base_url() . $matric_attachment_file;
        }

        if ($req_diploma_file == null) {
            $diploma = '';
        } else {
            $diploma = base_url() . $req_diploma_file;
        }

        if ($req_nbi_file == null) {
            $nbi = '';
        } else {
            $nbi = base_url() . $req_nbi_file;
        }

        if ($req_birth_cert_file == null) {
            $birth_cert = '';
        } else {
            $birth_cert = base_url() . $req_birth_cert_file;
        }

        if ($req_cert_married_file == null) {
            $cert_married = '';
        } else {
            $cert_married = base_url() . $req_cert_married_file;
        }

        if ($req_work_permit_file == null) {
            $work_permit = '';
        } else {
            $work_permit = base_url() . $req_work_permit_file;
        }

        if ($req_id_picture_file == null) {
            $id_picture = '';
        } else {
            $id_picture = base_url() . $req_id_picture_file;
        }

        if ($req_drug_test_file == null) {
            $drug_test = '';
        } else {
            $drug_test = base_url() . $req_drug_test_file;
        }

        if ($req_driver_license_file == null) {
            $driver_license = '';
        } else {
            $driver_license = base_url() . $req_driver_license_file;
        }


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

            $this->load->library('myupload');
            $postData = [
                'employee_id' => $employee_id,
                'pos_id' => $this->input->post('pos_id', true),
                'first_name' => $this->input->post('first_name', true),
                'middle_name' => $this->input->post('middle_name', true),
                'last_name' => $this->input->post('last_name', true),
                'maiden_name' => $this->input->post('maiden_name'),
                'emp_code' => $this->input->post('emp_code'),
                'email' => $this->input->post('email', true),
                'personal_email' => $this->input->post('personal_email', true),
                'phone' => $this->input->post('phone', true),
                'alter_phone' => $this->input->post('alter_phone', true),
                'emp_cnic' => $this->input->post('emp_cnic', true),
                'emp_exp_start_date' => $this->input->post('emp_exp_start_date', true),
                'emp_exp_end_date' => $this->input->post('emp_exp_end_date', true),
                'emp_address' => $this->input->post('emp_address', true),
                'masters_degree_title' => $this->input->post('masters_degree_title', true),
                'masters_majors' => $this->input->post('masters_majors', true),
                'masters_year_completion' => $this->input->post('masters_year_completion', true),
                'masters_institute' => $this->input->post('masters_institute', true),
                'masters_location' => $this->input->post('masters_location', true),
                'masters_cgpa' => $this->input->post('masters_cgpa', true),
                'bachelors_degree_title' => $this->input->post('bachelors_degree_title', true),
                'bachelors_majors' => $this->input->post('bachelors_majors', true),
                'bachelors_year_completion' => $this->input->post('bachelors_year_completion', true),
                'bachelors_institute' => $this->input->post('bachelors_institute', true),
                'bachelors_location' => $this->input->post('bachelors_location', true),
                'bachelors_cgpa' => $this->input->post('bachelors_cgpa', true),
                'inter_degree_title' => $this->input->post('inter_degree_title', true),
                'inter_majors' => $this->input->post('inter_majors', true),
                'inter_year_completion' => $this->input->post('inter_year_completion', true),
                'inter_institute' => $this->input->post('inter_institute', true),
                'inter_location' => $this->input->post('inter_location', true),
                'inter_percentage' => $this->input->post('inter_percentage', true),
                'matric_degree_title' => $this->input->post('matric_degree_title', true),
                'matric_majors' => $this->input->post('matric_majors', true),
                'matric_year_completion' => $this->input->post('matric_year_completion', true),
                'matric_institute' => $this->input->post('matric_institute', true),
                'matric_location' => $this->input->post('matric_location', true),
                'matric_percentage' => $this->input->post('matric_percentage', true),
                'present_address' => $this->input->post('present_address', true),
                'parmanent_address' => $this->input->post('parmanent_address', true),
                'picture' => $img,
                'benefit_name' => implode(',', $this->input->post('benefit_name', true)),
                'emp_grade' => $this->input->post('emp_grade', true),
                'benefit_accural_date' => $this->input->post('benefit_accural_date', true),
                'benefit_status' => $this->input->post('benefit_status', true),
                'dept_id' => $this->input->post('custdpt', true),
                'division_id' => $this->input->post('division', true),
                'state' => $this->input->post('state', true),
                'city' => $this->input->post('city', true),
                'zip' => $this->input->post('zip_code', true),
                'citizenship' => $this->input->post('citizenship', true),
                'account_title' => $this->input->post('account_title', true),
                'bank_name' => $this->input->post('bank_name', true),
                'account_number' => $this->input->post('account_number', true),
                'iban_number' => $this->input->post('iban_number', true),
                'duty_type' => $this->input->post('duty_type', true),
                'hire_date' => date("Y-m-d", strtotime(!empty($this->input->post('hiredate', true)) ? $this->input->post('hiredate', true) : date('Y-m-d'))),
                'original_hire_date' => date("Y-m-d", strtotime(!empty($this->input->post('ohiredate', true)) ? $this->input->post('ohiredate', true) : date('Y-m-d'))),
                'termination_date' => date("Y-m-d", strtotime(!empty($this->input->post('terminatedate', true)) ? $this->input->post('terminatedate', true) : '')),
                'termination_reason' => $this->input->post('termreason', true),
                'voluntary_termination' => $this->input->post('volunt_termination', true),
                'rehire_date' => date("Y-m-d", strtotime(!empty($this->input->post('rehiredate', true)) ? $this->input->post('rehiredate', true) : '')),
                'rate_type' => $this->input->post('rate_type', true),
                'rate' => $this->input->post('rate', true),
                'pay_frequency' => $this->input->post('pay_frequency', true),
                'pay_frequency_txt' => $this->input->post('pay_f_text', true),
                'hourly_rate2' => $this->input->post('h_rate2', true),
                'hourly_rate3' => $this->input->post('h_rate3', true),
                'home_department' => $this->input->post('h_department', true),
                'department_text' => $this->input->post('h_dep_text', true),
                'class_code' => $this->input->post('c_code', true),
                'class_code_desc' => $this->input->post('c_code_d', true),
                'class_acc_date' => date("Y-m-d", strtotime(!empty($this->input->post('class_acc_date', true)) ? $this->input->post('class_acc_date', true) : '')),
                'class_status' => $this->input->post('class_sst', true),
                'is_super_visor' => $this->input->post('is_supervisor', true),
                'super_visor_id' => $this->input->post('supervisorname', true),
                'supervisor_report' => $this->input->post('reports', true),
                'dob' => date("Y-m-d", strtotime(!empty($this->input->post('dob', true)) ? $this->input->post('dob', true) : '')),
                'gender' => $this->input->post('gender', true),
                'marital_status' => $this->input->post('marital_status', true),
                'ethnic_group' => $this->input->post('ethnic', true),
                'eeo_class_gp' => $this->input->post('eeo_class', true),
                'ssn' => $this->input->post('ssn', true),
                'work_in_state' => $this->input->post('w_s', true),
                'live_in_state' => $this->input->post('l_in_s', true),
                'home_email' => $this->input->post('h_email', true),
                'business_email' => $this->input->post('b_email', true),
                'home_phone' => $this->input->post('h_phone', true),
                'business_phone' => $this->input->post('w_phone', true),
                'cell_phone' => $this->input->post('c_phone', true),
                'emerg_contct' => $this->input->post('em_contact', true),
                'emrg_h_phone' => $this->input->post('e_h_phone', true),
                'emrg_w_phone' => $this->input->post('e_w_phone', true),
                'emgr_contct_relation' => $this->input->post('e_c_relation', true),
                'name_emg_contact_person_1' => $this->input->post('name_emg_contact_person_1', true),
                'relation_emg_contact_person_1' => $this->input->post('relation_emg_contact_person_1', true),
                'phone_emg_contact_person_1' => $this->input->post('phone_emg_contact_person_1', true),
                'alt_phone_emg_contact_person_1' => $this->input->post('alt_phone_emg_contact_person_1', true),
                'name_emg_contact_person_2' => $this->input->post('name_emg_contact_person_2', true),
                'relation_emg_contact_person_2' => $this->input->post('relation_emg_contact_person_2', true),
                'phone_emg_contact_person_2' => $this->input->post('phone_emg_contact_person_2', true),
                'alt_phone_emg_contact_person_2' => $this->input->post('alt_phone_emg_contact_person_2', true),
                'alt_em_contct' => $this->input->post('alt_em_cont', true),
                'alt_emg_h_phone' => $this->input->post('a_e_h_phone', true),
                'alt_emg_w_phone' => $this->input->post('a_e_w_phone', true),
                'password' => md5($this->input->post('password', true)),
                'resume' => $resume,
                'id_card_front' => $id_card_front,
                'id_card_back' => $id_card_back,
                'signed_nda' => $signed_nda,
                'signed_offer_letter' => $signed_offer_letter,
                'master_attachment' => $master_attachment,
                'bachelors_attachment' => $bachelors_attachment,
                'inter_attachment' => $inter_attachment,
                'matric_attachment' => $matric_attachment,
                'req_diploma_check' => $this->input->post('req_diploma_check', true),
                'req_diploma_date' => $this->input->post('req_diploma_date', true),
                'req_diploma_file' => $diploma,
                'req_nbi_check' => $this->input->post('req_nbi_check', true),
                'req_nbi_date' => $this->input->post('req_nbi_date', true),
                'req_nbi_file' => $nbi,
                'req_birth_cert_check' => $this->input->post('req_birth_cert_check', true),
                'req_birth_cert_date' => $this->input->post('req_birth_cert_date', true),
                'req_birth_cert_file' => $birth_cert,
                'req_cert_married_check' => $this->input->post('req_cert_married_check', true),
                'req_cert_married_date' => $this->input->post('req_cert_married_date', true),
                'req_cert_married_file' => $cert_married,
                'req_work_permit_check' => $this->input->post('req_work_permit_check', true),
                'req_work_permit_date' => $this->input->post('req_work_permit_date', true),
                'req_work_permit_file' => $work_permit,
                'req_id_picture_check' => $this->input->post('req_id_picture_check', true),
                'req_id_picture_date' => $this->input->post('req_id_picture_date', true),
                'req_id_picture_file' => $id_picture,
                'req_drug_test_check' => $this->input->post('req_drug_test_check', true),
                'req_drug_test_date' => $this->input->post('req_drug_test_date', true),
                'req_drug_test_file' => $drug_test,
                'req_driver_license_check' => $this->input->post('req_driver_license_check', true),
                'req_driver_license_date' => $this->input->post('req_driver_license_date', true),
                'req_driver_license_file' => $driver_license,
                'probation_start_date' => $this->input->post('probation_start_date', true),
                'probation_end_date' => $this->input->post('probation_end_date', true),
                'evaluation_by' => $this->input->post('evaluation_by', true),
                'evaluation_status' => $this->input->post('evaluation_status', true),
                'probation_status' => $this->input->post('probation_status', true),
                'shift_start' => $this->input->post('shift_start', true),
                'shift_end' => $this->input->post('shift_end', true),
            ];

            $coa = $this->Employees_model->headcode();
            if ($coa->HeadCode != NULL) {
                $headcode = $coa->HeadCode + 1;
            } else {
                $headcode = "502020000001";
            }

            $c_code = $employee_id;
            $c_name = $this->input->post('first_name', true) . $this->input->post('last_name', true);
            $c_acc = $c_code . '-' . $c_name;
            $createby = $this->session->userdata('fullname');
            $createdate = date('Y-m-d H:i:s');
            $data['aco'] = (object)$coaData = [
                'HeadCode' => $headcode,
                'HeadName' => $c_acc,
                'PHeadName' => 'Account Payable',
                'HeadLevel' => '2',
                'IsActive' => '1',
                'IsTransaction' => '1',
                'IsGL' => '0',
                'HeadType' => 'L',
                'IsBudget' => '0',
                'IsDepreciation' => '0',
                'DepreciationRate' => '0',
                'CreateBy' => $createby,
                'CreateDate' => $createdate,
            ];

            if ($this->Employees_model->create_employee($postData)) {

                $userData = array(
                    'firstname' => $this->input->post('first_name', true),
                    'lastname' => $this->input->post('last_name', true),
                    'email' => $this->input->post('user_email', true),
                    'password' => md5($this->input->post('password', true)),
                    'is_admin' => 0,
                    'image' => (!empty($img) ? substr($img, 2) : ''),
                );
                $this->db->insert('user', $userData);
                $user_id = $this->db->insert_id();
                $rolData = array(
                    'fk_role_id' => 1,
                    'fk_user_id' => $user_id
                );
                $this->db->insert('sec_user_access_tbl', $rolData);


                $this->Employees_model->create_coa($coaData);
                for ($i = 0; $i < count($customr_field); $i++) {
                    $custom = [
                        'custom_field' => $customr_field[$i],
                        'custom_data_type' => $customr_field_type[$i],
                        'custom_data' => $customr_value[$i],
                        'employee_id' => $employee_id,
                    ];
                    if (!empty($customr_field[$i])) {
                        $this->db->insert('custom_table', $custom);
                    }
                }

                for ($i = 0; $i < sizeof($p_e_company_name); $i++) {
                    $custom_exp = [
                        'p_e_company_name' => $p_e_company_name[$i],
                        'p_e_start_date' => $p_e_start_date[$i],
                        'p_e_end_date' => $p_e_end_date[$i],
                        'p_e_skill_name' => $p_e_skill_name[$i],
                        'p_e_designation' => $p_e_designation[$i],
                        'p_e_location' => $p_e_location[$i],
                        'employee_id' => $employee_id,
                    ];
                    if (!empty($p_e_company_name[$i])) {
                        $this->db->insert('professional_experience', $custom_exp);
                    }
                }

                for ($i = 0; $i < sizeof($c_t_name); $i++) {
                    $custom_cert = [
                        'c_t_name' => $c_t_name[$i],
                        'c_t_start_date' => $c_t_start_date[$i],
                        'c_t_end_date' => $c_t_end_date[$i],
                        'c_t_institute' => $c_t_institute[$i],
                        'c_t_location' => $c_t_location[$i],
                        'employee_id' => $employee_id,
                    ];
                    if (!empty($c_t_name[$i])) {
                        $this->db->insert('certificate_and_trainings', $custom_cert);
                    }
                }

                for ($i = 0; $i < sizeof($dependent_name); $i++) {
                    $custom_dep = [
                        'dependent_name' => $dependent_name[$i],
                        'dependent_relation' => $dependent_relation[$i],
                        'dependent_cnic' => $dependent_cnic[$i],
                        'dependent_dob' => $dependent_dob[$i],
                        'dependent_benefit' => $dependent_benefit[$i],
                        'employee_id' => $employee_id,
                    ];
                    if (!empty($dependent_name[$i])) {
                        $this->db->insert('dependent', $custom_dep);
                    }
                }

                for ($i = 0; $i < count($benifit_code); $i++) {

                    $benifit = [
                        'bnf_cl_code' => $benifit_code[$i],
                        'bnf_cl_code_des' => $benifit_code_desc[$i],
                        'bnff_acural_date' => date("Y-m-d", strtotime(!empty($benifit_acc_date[$i]) ? $benifit_acc_date[$i] : date('Y-m-d'))),
                        'bnf_status' => $benift_status[$i],
                        'employee_id' => $employee_id,
                    ];
                    if (!empty($benifit_code[$i])) {
                        $this->db->insert('employee_benifit', $benifit);
                    }
                }

                $firstName = $userData['firstname'];
                $lastName = $userData['lastname'];
                $empEmail = $userData["email"];
                $empPassword = "123456";

                // the message
                $msg = "Dear $firstName $lastName" . "\nYour account has been created in HR portal 
                \n Your Email is $empEmail and Password is $empPassword. 
                \n Please change your password first";

                // use wordwrap() if lines are longer than 70 characters
                $msg = wordwrap($msg, 70);

                // send email
                mail($empEmail, "HR Portal Credentials", $msg);


                $this->session->set_flashdata('message', display('save_successfully'));
                redirect("employee/Employees/viewEmhistory");
            }
        } else {
            $data['title'] = display('create');
            $data['module'] = "employee";
            $data['designation'] = $this->Employees_model->designation();
            $data['dropdowndept'] = $this->Employees_model->dropdowndept();
            $data['benefitlist'] = $this->Employees_model->benefit_list_dropdown();
            $data['skillslist'] = $this->Employees_model->skills_list_dropdown();
            $data['supervisor'] = $this->Employees_model->supervisorlist();
            $data['emplist'] = $this->Employees_model->emp_list_dropdown();
            $data['country_list'] = $this->Country_model->state();
            $data['page'] = "employ_form";
            echo Modules::run('template/layout', $data);

        }
    }

    public function delete_employhistory($id = null)
    {
        $this->permission->module('employee', 'delete')->redirect();
        $device_ip = $this->deviceData()->device_ip;
        if ($this->Employees_model->emplyee_history_delete($id)) {

            #set success message
            $this->session->set_flashdata('message', display('delete_successfully'));
        } else {
            #set exception message
            $this->session->set_flashdata('exception', display('please_try_again'));
        }
        redirect("employee/Employees/manageemployee");
    }


    public function download($id)
    {
        # load download helper
        $this->load->helper('download');
        # search for filename by id
        $id = $this->uri->segment(4);
        $this->db->select('*');
        $this->db->where('employee_id', $id);
        $q = $this->db->get('employee_history');
        # if exists continue
        if ($q->num_rows() > 0) {
            $row = $q->row();
            $file = FCPATH . 'files/' . $row->filename;
            if (file_exists($file))
                force_download($file, NULL);
        } else
            show_404();
    }

    public function DOWNLOAD_pdf()
    {
        $data = array();
        $data['cv'] = $this->Employees_model->employee_details();
        $html = $this->load->view('cv', $data, TRUE);
        pdf_create($html, 'User List');
    }

    public function position_view()
    {
        $this->permission->module('employee', 'read')->redirect();

        $data['title'] = display('circularprocess_list');;
        $data['position'] = $this->Employees_model->viewPosition();
        $data['module'] = "employee";
        $data['page'] = "positionview";
        echo Modules::run('template/layout', $data);
    }


    public function create_position()
    {
        $data['title'] = display('employee');
        #-------------------------------#
        $this->form_validation->set_rules('position_name', display('position_name'), 'required|max_length[50]');
        $this->form_validation->set_rules('position_details', display('position_details'), 'max_length[200]');
        #-------------------------------#
        if ($this->form_validation->run() === true) {

            $postData = [
                'position_name' => $this->input->post('position_name', true),
                'position_details' => $this->input->post('position_details', true),
            ];

            if ($this->Employees_model->position_create($postData)) {
                $this->session->set_flashdata('message', display('successfully_saved'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
            redirect("employee/Employees/create_position");


        } else {
            $data['title'] = display('create');
            $data['module'] = "employee";
            $data['position'] = $this->Employees_model->viewPosition();
            $data['page'] = "position_form";
            echo Modules::run('template/layout', $data);

        }
    }


    public function delete_pos($id = null)
    {
        $this->permission->module('employee', 'delete')->redirect();

        if ($this->Employees_model->delete_p($id)) {
            #set success message
            $this->session->set_flashdata('message', display('delete_successfully'));
        } else {
            #set exception message
            $this->session->set_flashdata('exception', display('please_try_again'));
        }
        redirect('employee/Employees/position_view');
    }

    public function update_form($id = null)
    {
        $this->form_validation->set_rules('pos_id', null, 'required|max_length[11]');
        $this->form_validation->set_rules('position_name', display('position_name'), 'required|max_length[50]');
        $this->form_validation->set_rules('position_details', display('position_details'), 'max_length[30]');


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

            $postData = [
                'pos_id' => $this->input->post('pos_id', true),
                'position_name' => $this->input->post('position_name', true),
                'position_details' => $this->input->post('position_details', true),

            ];

            if ($this->Employees_model->update_position($postData)) {
                $this->session->set_flashdata('message', display('successfully_updated'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
            redirect('employee/Employees/position_view');

        } else {
            $data['data'] = $this->Employees_model->pos_updateForm($id);
            $data['module'] = "employee";
            $data['page'] = "update_position";
            echo Modules::run('template/layout', $data);
        }

    }

    //************Employee Update Part***********//
    public function update_employee_form($id = null)
    {
        /***** file upload code start ***********/

        $data['title'] = display('employee_update_form');
        $device_ip = $this->deviceData()->device_ip;
        $this->form_validation->set_rules('first_name', display('first_name'), 'required|max_length[50]');
        $this->form_validation->set_rules('last_name', display('last_name'), 'required|max_length[50]');
        $this->form_validation->set_rules('maiden_name', display('maiden_name'), 'max_length[50]');
        $this->form_validation->set_rules('present_address', display('present_address'), 'max_length[250]');
        $this->form_validation->set_rules('parmanent_address', display('parmanent_address'), 'max_length[250]');
        $this->form_validation->set_rules('termreason', display('termreason'), 'max_length[250]');
        $this->load->library('myupload');
        $img = $this->myupload->do_upload(
            './application/modules/employee/assets/images/',
            'picture'
        );
        $resume_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'resume'
        );

        $id_card_front_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'id_card_front'
        );
        $id_card_back_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'id_card_back'
        );

        $signed_nda_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'signed_nda'
        );

        $signed_offer_letter_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'signed_offer_letter'
        );

        $master_attachment_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'master_attachment'
        );

        $bachelors_attachment_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'bachelors_attachment'
        );

        $inter_attachment_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'inter_attachment'
        );

        $matric_attachment_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'matric_attachment'
        );

        $req_diploma_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'req_diploma_file'
        );

        $req_nbi_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'req_nbi_file'
        );

        $req_birth_cert_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'req_birth_cert_file'
        );

        $req_cert_married_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'req_cert_married_file'
        );

        $req_work_permit_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'req_work_permit_file'
        );

        $req_id_picture_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'req_id_picture_file'
        );

        $req_drug_test_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'req_drug_test_file'
        );

        $req_driver_license_file = $this->myupload->do_upload(
            'application/modules/employee/assets/docs',
            'req_driver_license_file'
        );

        $this->form_validation->set_rules('c_f_name[]', 'Custom Field Name');
        $this->form_validation->set_rules('c_f_type[]', 'Custom Field Type');
        $this->form_validation->set_rules('customvalue[]', 'Custom Value');
        $customr_field = $this->input->post('c_f_name', true);
        $customr_field_type = $this->input->post('c_f_type', true);
        $customr_value = $this->input->post('customvalue', true);

        $p_e_company_name = $this->input->post('p_e_company_name', true);
        $p_e_start_date = $this->input->post('p_e_start_date', true);
        $p_e_end_date = $this->input->post('p_e_end_date', true);
        $p_e_skill_name = $this->input->post('p_e_skill_name', true);
        $p_e_designation = $this->input->post('p_e_designation', true);
        $p_e_location = $this->input->post('p_e_location', true);

        $c_t_name = $this->input->post('c_t_name', true);
        $c_t_start_date = $this->input->post('c_t_start_date', true);
        $c_t_end_date = $this->input->post('c_t_end_date', true);
        $c_t_institute = $this->input->post('c_t_institute', true);
        $c_t_location = $this->input->post('c_t_location', true);

        $dependent_name = $this->input->post('dependent_name', true);
        $dependent_relation = $this->input->post('dependent_relation', true);
        $dependent_cnic = $this->input->post('dependent_cnic', true);
        $dependent_dob = $this->input->post('dependent_dob', true);
        $dependent_benefit = $this->input->post('dependent_benefit', true);

        $benifit_code = $this->input->post('benifit_c_code', true);
        $benifit_code_desc = $this->input->post('benifit_c_code_d', true);
        $benifit_acc_date = $this->input->post('benifit_acc_date', true);
        $benift_status = $this->input->post('benifit_sst', true);

        $c_code = $id;
        $c_name = $this->input->post('first_name', true) . $this->input->post('last_name', true);
        $c_acc = $c_code . '-' . $c_name;

        $old_accname = $id . '-' . $this->input->post('oldfirstname', true) . $this->input->post('oldlastname', true);

        $old_resume = $this->input->post('old_resume');

        $old_id_card_front = $this->input->post('old_id_card_front');
        $old_id_card_back = $this->input->post('old_id_card_back');
        $old_signed_nda = $this->input->post('old_signed_nda');
        $old_signed_offer_letter = $this->input->post('old_signed_offer_letter');

        $old_master_attachment = $this->input->post('old_master_attachment');
        $old_bachelors_attachment = $this->input->post('old_bachelors_attachment');
        $old_inter_attachment = $this->input->post('old_inter_attachment');
        $old_matric_attachment = $this->input->post('old_matric_attachment');

        $old_req_diploma = $this->input->post('old_req_diploma');
        $old_req_nbi_file = $this->input->post('old_req_nbi_file');
        $old_req_birth_cert_file = $this->input->post('old_req_birth_cert_file');
        $old_req_cert_married_file = $this->input->post('old_req_cert_married_file');
        $old_req_work_permit_file = $this->input->post('old_req_work_permit_file');
        $old_req_id_picture_file = $this->input->post('old_req_id_picture_file');
        $old_req_drug_test_file = $this->input->post('old_req_drug_test_file');
        $old_req_driver_license_file = $this->input->post('old_req_driver_license_file');

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

            if ($resume_file == null && $old_resume != null) {
                $resume = $old_resume;
            } elseif ($resume_file == null && $old_resume == null) {
                $resume = '';
            } else {
                $resume = base_url() . $resume_file;
            }

            if ($id_card_front_file == null && $old_id_card_front != null) {
                $id_card_front = $old_id_card_front;
            } elseif ($id_card_front_file == null && $old_id_card_front == null) {
                $id_card_front = '';
            } else {
                $id_card_front = base_url() . $id_card_front_file;
            }

            if ($id_card_back_file == null && $old_id_card_back != null) {
                $id_card_back = $old_id_card_back;
            } elseif ($id_card_back_file == null && $old_id_card_back == null) {
                $id_card_back = '';
            } else {
                $id_card_back = base_url() . $id_card_back_file;
            }

            if ($signed_nda_file == null && $old_signed_nda != null) {
                $signed_nda = $old_signed_nda;
            } elseif ($signed_nda_file == null && $old_signed_nda == null) {
                $signed_nda = '';
            } else {
                $signed_nda = base_url() . $signed_nda_file;
            }

            if ($signed_offer_letter_file == null && $old_signed_offer_letter != null) {
                $signed_offer_letter = $old_signed_offer_letter;
            } elseif ($signed_offer_letter_file == null && $old_signed_offer_letter == null) {
                $signed_offer_letter = '';
            } else {
                $signed_offer_letter = base_url() . $signed_offer_letter_file;
            }

            if ($master_attachment_file == null && $old_master_attachment != null) {
                $master_attachment = $old_master_attachment;
            } elseif ($master_attachment_file == null && $old_master_attachment == null) {
                $master_attachment = '';
            } else {
                $master_attachment = base_url() . $master_attachment_file;
            }
            if ($bachelors_attachment_file == null && $old_bachelors_attachment != null) {
                $bachelors_attachment = $old_bachelors_attachment;
            } elseif ($bachelors_attachment_file == null && $old_bachelors_attachment == null) {
                $bachelors_attachment = '';
            } else {
                $bachelors_attachment = base_url() . $bachelors_attachment_file;
            }
            if ($inter_attachment_file == null && $old_inter_attachment != null) {
                $inter_attachment = $old_inter_attachment;
            } elseif ($inter_attachment_file == null && $old_inter_attachment == null) {
                $inter_attachment = '';
            } else {
                $inter_attachment = base_url() . $inter_attachment_file;
            }
            if ($matric_attachment_file == null && $old_matric_attachment != null) {
                $matric_attachment = $old_matric_attachment;
            } elseif ($matric_attachment_file == null && $old_matric_attachment == null) {
                $matric_attachment = '';
            } else {
                $matric_attachment = base_url() . $matric_attachment_file;
            }

            if ($req_diploma_file == null && $old_req_diploma != null) {
                $diploma = $old_req_diploma;
            } elseif ($req_diploma_file == null && $old_req_diploma == null) {
                $diploma = '';
            } else {
                $diploma = base_url() . $req_diploma_file;
            }

            if ($req_nbi_file == null && $old_req_nbi_file != null) {
                $nbi = $old_req_nbi_file;
            } elseif ($req_nbi_file == null && $old_req_nbi_file == null) {
                $nbi = '';
            } else {
                $nbi = base_url() . $req_nbi_file;
            }

            if ($req_birth_cert_file == null && $old_req_birth_cert_file != null) {
                $birth_cert = $old_req_birth_cert_file;
            } elseif ($req_birth_cert_file == null && $old_req_birth_cert_file == null) {
                $birth_cert = '';
            } else {
                $birth_cert = base_url() . $req_birth_cert_file;
            }

            if ($req_cert_married_file == null && $old_req_cert_married_file != null) {
                $cert_married = $old_req_cert_married_file;
            } elseif ($req_cert_married_file == null && $old_req_cert_married_file == null) {
                $cert_married = '';
            } else {
                $cert_married = base_url() . $req_cert_married_file;
            }

            if ($req_work_permit_file == null && $old_req_work_permit_file != null) {
                $work_permit = $old_req_work_permit_file;
            } elseif ($req_work_permit_file == null && $old_req_work_permit_file == null) {
                $work_permit = '';
            } else {
                $work_permit = base_url() . $req_work_permit_file;
            }

            if ($req_id_picture_file == null && $old_req_id_picture_file != null) {
                $id_picture = $old_req_id_picture_file;
            } elseif ($req_id_picture_file == null && $old_req_id_picture_file == null) {
                $id_picture = '';
            } else {
                $id_picture = base_url() . $req_id_picture_file;
            }

            if ($req_drug_test_file == null && $old_req_drug_test_file != null) {
                $drug_test = $old_req_drug_test_file;
            } elseif ($req_drug_test_file == null && $old_req_drug_test_file == null) {
                $drug_test = '';
            } else {
                $drug_test = base_url() . $req_drug_test_file;
            }

            if ($req_driver_license_file == null && $old_req_driver_license_file != null) {
                $driver_license = $old_req_driver_license_file;
            } elseif ($req_driver_license_file == null && $old_req_driver_license_file == null) {
                $driver_license = '';
            } else {
                $driver_license = base_url() . $req_driver_license_file;
            }

            $data['employee'] = (object)$postData = [
                'employee_id' => $this->input->post('employee_id', true),
                'pos_id' => $this->input->post('pos_id', true),
                'first_name' => $this->input->post('first_name', true),
                'middle_name' => $this->input->post('middle_name'),
                'last_name' => $this->input->post('last_name', true),
                'maiden_name' => $this->input->post('maiden_name'),
                'emp_code' => $this->input->post('emp_code'),
                'email' => $this->input->post('email', true),
                'personal_email' => $this->input->post('personal_email', true),
                'phone' => $this->input->post('phone', true),
                'alter_phone' => $this->input->post('alter_phone', true),
                'emp_cnic' => $this->input->post('emp_cnic', true),
                'emp_exp_start_date' => $this->input->post('emp_exp_start_date', true),
                'emp_exp_end_date' => $this->input->post('emp_exp_end_date', true),
                'emp_address' => $this->input->post('emp_address', true),
                'masters_degree_title' => $this->input->post('masters_degree_title', true),
                'masters_majors' => $this->input->post('masters_majors', true),
                'masters_year_completion' => $this->input->post('masters_year_completion', true),
                'masters_institute' => $this->input->post('masters_institute', true),
                'masters_location' => $this->input->post('masters_location', true),
                'masters_cgpa' => $this->input->post('masters_cgpa', true),
                'bachelors_degree_title' => $this->input->post('bachelors_degree_title', true),
                'bachelors_majors' => $this->input->post('bachelors_majors', true),
                'bachelors_year_completion' => $this->input->post('bachelors_year_completion', true),
                'bachelors_institute' => $this->input->post('bachelors_institute', true),
                'bachelors_location' => $this->input->post('bachelors_location', true),
                'bachelors_cgpa' => $this->input->post('bachelors_cgpa', true),
                'inter_degree_title' => $this->input->post('inter_degree_title', true),
                'inter_majors' => $this->input->post('inter_majors', true),
                'inter_year_completion' => $this->input->post('inter_year_completion', true),
                'inter_institute' => $this->input->post('inter_institute', true),
                'inter_location' => $this->input->post('inter_location', true),
                'inter_percentage' => $this->input->post('inter_percentage', true),
                'matric_degree_title' => $this->input->post('matric_degree_title', true),
                'matric_majors' => $this->input->post('matric_majors', true),
                'matric_year_completion' => $this->input->post('matric_year_completion', true),
                'matric_institute' => $this->input->post('matric_institute', true),
                'matric_location' => $this->input->post('matric_location', true),
                'matric_percentage' => $this->input->post('matric_percentage', true),
                'present_address' => $this->input->post('present_address', true),
                'parmanent_address' => $this->input->post('parmanent_address', true),
                'picture' => (!empty($img) ? $img : $this->input->post('old_image')),
                'benefit_name' => implode(',', $this->input->post('benefit_name', true)),
                'emp_grade' => $this->input->post('emp_grade', true),
                'benefit_accural_date' => $this->input->post('benefit_accural_date', true),
                'benefit_status' => $this->input->post('benefit_status', true),
                'dept_id' => $this->input->post('division', true),
                'state' => $this->input->post('state', true),
                'city' => $this->input->post('city', true),
                'zip' => $this->input->post('zip_code', true),
                'citizenship' => $this->input->post('citizenship', true),
                'account_title' => $this->input->post('account_title', true),
                'bank_name' => $this->input->post('bank_name', true),
                'account_number' => $this->input->post('account_number', true),
                'iban_number' => $this->input->post('iban_number', true),
                'duty_type' => $this->input->post('duty_type', true),
                'hire_date' => date("Y-m-d", strtotime(!empty($this->input->post('hiredate', true)) ? $this->input->post('hiredate', true) : '')),
                'original_hire_date' => date("Y-m-d", strtotime(!empty($this->input->post('ohiredate', true)) ? $this->input->post('ohiredate', true) : '')),
                'termination_date' => date("Y-m-d", strtotime(!empty($this->input->post('terminatedate', true)) ? $this->input->post('terminatedate', true) : '')),
                'termination_reason' => $this->input->post('termreason', true),
                'voluntary_termination' => $this->input->post('volunt_termination', true),
                'rehire_date' => date("Y-m-d", strtotime(!empty($this->input->post('rehiredate', true)) ? $this->input->post('rehiredate', true) : '')),
                'rate_type' => $this->input->post('rate_type', true),
                'rate' => $this->input->post('rate', true),
                'pay_frequency' => $this->input->post('pay_frequency', true),
                'pay_frequency_txt' => $this->input->post('pay_f_text', true),
                'hourly_rate2' => $this->input->post('h_rate2', true),
                'hourly_rate3' => $this->input->post('h_rate3', true),
                'home_department' => $this->input->post('h_department', true),
                'department_text' => $this->input->post('h_dep_text', true),
                'class_code' => $this->input->post('c_code', true),
                'class_code_desc' => $this->input->post('c_code_d', true),
                'class_acc_date' => date("Y-m-d", strtotime(!empty($this->input->post('class_acc_date', true)) ? $this->input->post('class_acc_date', true) : '')),
                'class_status' => $this->input->post('class_sst', true),
                'is_manager' => $this->input->post('is_manager', true),
                'super_visor_id' => $this->input->post('supervisorname', true),
                'supervisor_report' => $this->input->post('reports', true),
                'dob' => date("Y-m-d", strtotime(!empty($this->input->post('dob', true)) ? $this->input->post('dob', true) : '')),
                'gender' => $this->input->post('gender', true),
                'marital_status' => $this->input->post('marital_status', true),
                'ethnic_group' => $this->input->post('ethnic', true),
                'eeo_class_gp' => $this->input->post('eeo_class', true),
                'ssn' => $this->input->post('ssn', true),
                'work_in_state' => $this->input->post('w_s', true),
                'live_in_state' => $this->input->post('l_in_s', true),
                'home_email' => $this->input->post('h_email', true),
                'business_email' => $this->input->post('b_email', true),
                'home_phone' => $this->input->post('h_phone', true),
                'business_phone' => $this->input->post('w_phone', true),
                'cell_phone' => $this->input->post('c_phone', true),
                'emerg_contct' => $this->input->post('em_contact', true),
                'emrg_h_phone' => $this->input->post('e_h_phone', true),
                'emrg_w_phone' => $this->input->post('e_w_phone', true),
                'emgr_contct_relation' => $this->input->post('e_c_relation', true),
                'name_emg_contact_person_1' => $this->input->post('name_emg_contact_person_1', true),
                'relation_emg_contact_person_1' => $this->input->post('relation_emg_contact_person_1', true),
                'phone_emg_contact_person_1' => $this->input->post('phone_emg_contact_person_1', true),
                'alt_phone_emg_contact_person_1' => $this->input->post('alt_phone_emg_contact_person_1', true),
                'name_emg_contact_person_2' => $this->input->post('name_emg_contact_person_2', true),
                'relation_emg_contact_person_2' => $this->input->post('relation_emg_contact_person_2', true),
                'phone_emg_contact_person_2' => $this->input->post('phone_emg_contact_person_2', true),
                'alt_phone_emg_contact_person_2' => $this->input->post('alt_phone_emg_contact_person_2', true),
                'alt_em_contct' => $this->input->post('alt_em_cont', true),
                'alt_emg_h_phone' => $this->input->post('a_e_h_phone', true),
                'alt_emg_w_phone' => $this->input->post('a_e_w_phone', true),
                'password' => (!empty($this->input->post('password', true)) ? md5($this->input->post('password', true)) : $this->input->post('old_password', true)),
                'resume' => $resume,
                'id_card_front' => $id_card_front,
                'id_card_back' => $id_card_back,
                'signed_nda' => $signed_nda,
                'signed_offer_letter' => $signed_offer_letter,
                'master_attachment' => $master_attachment,
                'bachelors_attachment' => $bachelors_attachment,
                'inter_attachment' => $inter_attachment,
                'matric_attachment' => $matric_attachment,
                'req_diploma_check' => $this->input->post('req_diploma_check', true),
                'req_diploma_date' => $this->input->post('req_diploma_date', true),
                'req_diploma_file' => $diploma,
                'req_nbi_check' => $this->input->post('req_nbi_check', true),
                'req_nbi_date' => $this->input->post('req_nbi_date', true),
                'req_nbi_file' => $nbi,
                'req_birth_cert_check' => $this->input->post('req_birth_cert_check', true),
                'req_birth_cert_date' => $this->input->post('req_birth_cert_date', true),
                'req_birth_cert_file' => $birth_cert,
                'req_cert_married_check' => $this->input->post('req_cert_married_check', true),
                'req_cert_married_date' => $this->input->post('req_cert_married_date', true),
                'req_cert_married_file' => $cert_married,
                'req_work_permit_check' => $this->input->post('req_work_permit_check', true),
                'req_work_permit_date' => $this->input->post('req_work_permit_date', true),
                'req_work_permit_file' => $work_permit,
                'req_id_picture_check' => $this->input->post('req_id_picture_check', true),
                'req_id_picture_date' => $this->input->post('req_id_picture_date', true),
                'req_id_picture_file' => $id_picture,
                'req_drug_test_check' => $this->input->post('req_drug_test_check', true),
                'req_drug_test_date' => $this->input->post('req_drug_test_date', true),
                'req_drug_test_file' => $drug_test,
                'req_driver_license_check' => $this->input->post('req_driver_license_check', true),
                'req_driver_license_date' => $this->input->post('req_driver_license_date', true),
                'req_driver_license_file' => $driver_license,
                'probation_start_date' => $this->input->post('probation_start_date', true),
                'probation_end_date' => $this->input->post('probation_end_date', true),
                'evaluation_by' => $this->input->post('evaluation_by', true),
                'evaluation_status' => $this->input->post('evaluation_status', true),
                'probation_status' => $this->input->post('probation_status', true),
                'shift_start' => $this->input->post('shift_start', true),
                'shift_end' => $this->input->post('shift_end', true),
            ];

            $coa = $this->Employees_model->headcode();
            if ($coa->HeadCode != NULL) {
                $headcode = $coa->HeadCode + 1;
            } else {
                $headcode = "502020000001";
            }

            $employee_id = $this->input->post('employee_id', true);
            $c_code = $employee_id;
            $c_name = $this->input->post('first_name', true) . $this->input->post('last_name', true);
            $c_acc = $c_code . '-' . $c_name;
            $createby = $this->session->userdata('fullname');
            $createdate = date('Y-m-d H:i:s');

            $accHead = [
                'HeadName' => $c_acc,
            ];


            if ($this->Employees_model->update_employee($postData)) {

                $emp_id = $this->input->post('employee_id', true);
                $supId = $this->input->post('supervisorname', true);
                $supIdArr = array(
                    'employee_id' => $emp_id,
                    'supervisor_id' => $supId,
                );

                $this->Employees_model->update_resignation_supervisor($supIdArr);

                $employee_old_useremail = $this->input->post('old_useremail', true);
                $user_his = $this->db->select('*')
                    ->from('user')
                    ->where('email', $employee_old_useremail)
                    ->get()
                    ->num_rows();

                if ($user_his > 0) {

                    $userData = array(
                        'firstname' => $this->input->post('first_name', true),
                        'lastname' => $this->input->post('last_name', true),
                        'email' => $this->input->post('user_email', true),
                        'password' => (!empty($this->input->post('password', true)) ? md5($this->input->post('password', true)) : $this->input->post('old_password', true)),
                        'image' => (!empty($img) ? substr($img, 2) : $this->input->post('old_image'))
                    );
                    $this->db->where('email', $this->input->post('old_useremail', true))
                        ->update("user", $userData);

                }

                $this->db->where('HeadName', $old_accname)
                    ->update("acc_coa", $accHead);
                $this->db->where('employee_id', $this->input->post('employee_id', true))
                    ->delete('custom_table');
                $this->db->where('employee_id', $this->input->post('employee_id', true))
                    ->delete('employee_benifit');
                $this->db->where('employee_id', $this->input->post('employee_id', true))
                    ->delete('professional_experience');
                $this->db->where('employee_id', $this->input->post('employee_id', true))
                    ->delete('certificate_and_trainings');
                $this->db->where('employee_id', $this->input->post('employee_id', true))
                    ->delete('dependent');

                for ($i = 0; $i < sizeof($customr_field); $i++) {
                    $custom = [
                        'custom_field' => $customr_field[$i],
                        'custom_data_type' => $customr_field_type[$i],
                        'custom_data' => $customr_value[$i],
                        'employee_id' => $this->input->post('employee_id', true),
                    ];
                    if (!empty($customr_field[$i])) {
                        $this->db->insert('custom_table', $custom);
                    }
                }

                for ($i = 0; $i < sizeof($p_e_company_name); $i++) {
                    $custom_exp = [
                        'p_e_company_name' => $p_e_company_name[$i],
                        'p_e_start_date' => $p_e_start_date[$i],
                        'p_e_end_date' => $p_e_end_date[$i],
                        'p_e_skill_name' => $p_e_skill_name[$i],
                        'p_e_designation' => $p_e_designation[$i],
                        'p_e_location' => $p_e_location[$i],
                        'employee_id' => $this->input->post('employee_id', true),
                    ];
                    if (!empty($p_e_company_name[$i])) {
                        $this->db->insert('professional_experience', $custom_exp);
                    }
                }

                for ($i = 0; $i < sizeof($c_t_name); $i++) {
                    $custom_cert = [
                        'c_t_name' => $c_t_name[$i],
                        'c_t_start_date' => $c_t_start_date[$i],
                        'c_t_end_date' => $c_t_end_date[$i],
                        'c_t_institute' => $c_t_institute[$i],
                        'c_t_location' => $c_t_location[$i],
                        'employee_id' => $employee_id,
                    ];
                    if (!empty($c_t_name[$i])) {
                        $this->db->insert('certificate_and_trainings', $custom_cert);
                    }
                }

                for ($i = 0; $i < sizeof($dependent_name); $i++) {
                    $custom_dep = [
                        'dependent_name' => $dependent_name[$i],
                        'dependent_relation' => $dependent_relation[$i],
                        'dependent_cnic' => $dependent_cnic[$i],
                        'dependent_dob' => $dependent_dob[$i],
                        'dependent_benefit' => $dependent_benefit[$i],
                        'employee_id' => $employee_id,
                    ];

                    if (!empty($dependent_name[$i])) {
                        $this->db->insert('dependent', $custom_dep);
                    }
                }

                for ($i = 0; $i < count($benifit_code); $i++) {

                    $benifit = [
                        'bnf_cl_code' => $benifit_code[$i],
                        'bnf_cl_code_des' => $benifit_code_desc[$i],
                        'bnff_acural_date' => date("Y-m-d", strtotime(!empty($benifit_acc_date[$i]) ? $benifit_acc_date[$i] : date('Y-m-d'))),
                        'bnf_status' => $benift_status[$i],
                        'employee_id' => $this->input->post('employee_id', true),
                    ];
                    if (!empty($benifit_code[$i])) {
                        $this->db->insert('employee_benifit', $benifit);
                    }
                }

                if($this->input->post('is_manager', true) == '1'){
                    $isthis_manager = [
                        'dept_id' => $this->input->post('division', true),
                        'super_visor_id' => $this->input->post('employee_id', true),
                    ];
                    $this->Employees_model->update_manager_employee($isthis_manager);
                }
                $this->session->set_flashdata('message', display('update_successfully'));
                redirect("employee/Employees/update_employee_form/" . $id);
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
        } else {

            $benefit_ids = $this->Employees_model->get_benefit_ids($id);
            $benefit_ids = $benefit_ids[0]->benefit_name;
            $benefit_ids_array = explode(",", "$benefit_ids");

            $benefit_names_obj = $this->Employees_model->get_benefit_names($benefit_ids_array);

            $data['emp_history'] = $this->Employees_model->emp_list();

            $data['data'] = $this->Employees_model->employee_updateForm($id);
            $data['module'] = "employee";
            $data['page'] = "update_employee_form";
            $data['emplist'] = $this->Employees_model->emp_list_dropdown();
            $data['benefitlist'] = $this->Employees_model->benefit_list_dropdown();
            $data['skillslist'] = $this->Employees_model->skills_list_dropdown();
            $data['dropdowndept'] = $this->Employees_model->dropdowndept();
            $data['designation'] = $this->Employees_model->designation();
            $data['supervisor'] = $this->Employees_model->supervisorlist();
            $data['custominfo'] = $this->Employees_model->customifo($id);
            $data['documentsinfo'] = $this->Employees_model->documentsinfo($id);
            $data['certificationsinfo'] = $this->Employees_model->certificationsinfo($id);
            $data['dependentsinfo'] = $this->Employees_model->dependentsinfo($id);
            $data['benifit'] = $this->Employees_model->benifit($id);
            $data['bb'] = $this->Employees_model->get_pos($id);
            $data['country_list'] = $this->Country_model->state();
            $data['vacation_list'] = $this->Employees_model->get_vacations();

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

        }
    }


    public function randID()
    {
        $result = "";
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        $charArray = str_split($chars);
        for ($i = 0; $i < 7; $i++) {
            $randItem = array_rand($charArray);
            $result .= "" . $charArray[$randItem];
        }
        return "E" . $result;
    }

    // employee search
    public function employee_search()
    {
        $keyword = $this->input->post('what_you_search', true);
        $search_result = $this->Employees_model->employee_search($keyword);
        $data['emp_history'] = $search_result;
        $data['module'] = "employee";
        $data['page'] = "employee_view";
        echo Modules::run('template/layout', $data);
    }

    public function change_employee_status()
    {
        $employee_id = $this->input->post('employee_id', true);
        $status = $this->input->post('status', true);

        $postData = [
            'employee_id' => $employee_id,
            'employee_status' => $status,
        ];

        if ($this->Employees_model->update_status($postData)) {
            echo "<div class='alert alert-success'>Status Updated</div>";
        }
    }

    public function get_vacation_time_list()
    {
        $vacation_list = $this->Employees_model->get_vacation_list();
        $result = array();
        $i = 1;
        foreach ($vacation_list as $key => $value) {

            $button = '<button class="btn btn-xs btn-success" onclick="edit_vacation_ajax(' . $value['vacation_id'] . ')">
                        <i class="fa fa-pencil"></i></button>';

            $button .= " ";

            $button .= '<button class="btn btn-xs btn-danger" onclick="delete_vacation_ajax(' . $value['vacation_id'] . ')">
                        <i class="fa fa-trash"></i></button>';

            $result['data'][] = array(
                $i++,
                $value['vacation_date'],
                $value['vacation_hours'],
                $value['vacation_description'],
                $button

            );
        }
        echo json_encode($result);
    }

    /*
    |------------------------------------------------------
    | Vacation Time
    |--------------------------------------------------------
    */
    public function create_vacation_time()
    {
        $postData = [
            'vacation_date' => $this->input->post('vacation_date', true),
            'vacation_hours' => $this->input->post('vacation_hours', true),
            'vacation_description' => $this->input->post('vacation_description', true),
            'employee_id' => $this->input->post('employee_id', true),
        ];

        $add_vacation = $this->Employees_model->create_vacation($postData);

        if ($add_vacation == true) {
            echo 1;
        } else {
            echo 2;
        }
    }

    public function update_vacation_time()
    {
        $postData = [
            'vacation_date' => $this->input->post('vacation_date', true),
            'vacation_hours' => $this->input->post('vacation_hours', true),
            'vacation_description' => $this->input->post('vacation_description', true),
            'vacation_id' => $this->input->post('vacation_id', true),
        ];

        $update_vacation = $this->Employees_model->update_vacation($postData);

        if ($update_vacation == true) {
            echo 1;
        } else {
            echo 2;
        }

    }

    public function get_edit_vacation()
    {
        $vacation_id = $this->input->post('vacation_id', true);
        $resultData = $this->Employees_model->get_single_vacation($vacation_id);
        echo json_encode($resultData);
    }

    public function delete_vacation_time()
    {
        $vacation_id = $this->input->post('vacation_id', true);
        $delete_vacation = $this->Employees_model->delete_vacation($vacation_id);

        if ($delete_vacation == true) {
            echo 1;
        } else {
            echo 2;
        }
    }

    /*
   |------------------------------------------------------
   | Personal Time
   |--------------------------------------------------------
   */

    public function get_personal_time_list()
    {
        $personal_list = $this->Employees_model->get_personal_list();
        $result = array();
        $i = 1;
        foreach ($personal_list as $key => $value) {

            $button = '<button class="btn btn-xs btn-success" onclick="edit_personal_ajax(' . $value['personal_id'] . ')">
                        <i class="fa fa-pencil"></i></button>';

            $button .= " ";

            $button .= '<button class="btn btn-xs btn-danger" onclick="delete_personal_ajax(' . $value['personal_id'] . ')">
                        <i class="fa fa-trash"></i></button>';

            $result['data'][] = array(
                $i++,
                $value['personal_date'],
                $value['personal_hours'],
                $value['personal_description'],
                $button

            );
        }
        echo json_encode($result);
    }

    public function create_personal_time()
    {
        $postData = [
            'personal_date' => $this->input->post('personal_date', true),
            'personal_hours' => $this->input->post('personal_hours', true),
            'personal_description' => $this->input->post('personal_description', true),
            'employee_id' => $this->input->post('employee_id', true),
        ];

        $add_personal = $this->Employees_model->create_personal($postData);

        if ($add_personal == true) {
            echo 1;
        } else {
            echo 2;
        }
    }

    public function get_edit_personal()
    {
        $personal_id = $this->input->post('personal_id', true);
        $resultData = $this->Employees_model->get_single_personal($personal_id);
        echo json_encode($resultData);
    }

    public function update_personal_time()
    {
        $postData = [
            'personal_date' => $this->input->post('personal_date', true),
            'personal_hours' => $this->input->post('personal_hours', true),
            'personal_description' => $this->input->post('personal_description', true),
            'personal_id' => $this->input->post('personal_id', true),
        ];

        $update_personal = $this->Employees_model->update_personal($postData);

        if ($update_personal == true) {
            echo 1;
        } else {
            echo 2;
        }

    }

    public function delete_personal_time()
    {
        $personal_id = $this->input->post('personal_id', true);
        $delete_personal = $this->Employees_model->delete_personal($personal_id);

        if ($delete_personal == true) {
            echo 1;
        } else {
            echo 2;
        }
    }

    /*
    |------------------------------------------------------
    | Disciplinary Action
    |--------------------------------------------------------
    */

    public function get_disciplinary_action_list()
    {
        $disciplinary_list = $this->Employees_model->get_disciplinary_list();
        $result = array();
        $i = 1;
        foreach ($disciplinary_list as $key => $value) {

            $button = '<button class="btn btn-xs btn-success" onclick="edit_disciplinary_ajax(' . $value['da_id'] . ')">
                        <i class="fa fa-pencil"></i></button>';

            $button .= " ";

            $button .= '<button class="btn btn-xs btn-danger" onclick="delete_disciplinary_ajax(' . $value['da_id'] . ')">
                        <i class="fa fa-trash"></i></button>';

            $result['data'][] = array(
                $i++,
                $value['disciplinary_date'],
                $value['disciplinary_comments'],
                $button

            );
        }
        echo json_encode($result);
    }

    public function create_disciplinary_action()
    {
        $postData = [
            'disciplinary_date' => $this->input->post('disciplinary_date', true),
            'disciplinary_comments' => $this->input->post('disciplinary_comments', true),
            'employee_id' => $this->input->post('employee_id', true),
        ];

        $add_action = $this->Employees_model->create_disciplinary($postData);

        if ($add_action == true) {
            echo 1;
        } else {
            echo 2;
        }
    }

    public function get_edit_disciplinary()
    {
        $da_id = $this->input->post('da_id', true);
        $resultData = $this->Employees_model->get_single_disciplinary($da_id);
        echo json_encode($resultData);
    }

    public function update_disciplinary_time()
    {
        $postData = [
            'disciplinary_date' => $this->input->post('disciplinary_date', true),
            'disciplinary_comments' => $this->input->post('disciplinary_comments', true),
            'da_id' => $this->input->post('da_id', true),
        ];

        $update_disciplinary = $this->Employees_model->update_disciplinary($postData);

        if ($update_disciplinary == true) {
            echo 1;
        } else {
            echo 2;
        }

    }

    public function delete_disciplinary_action()
    {
        $da_id = $this->input->post('da_id', true);
        $delete_disciplinary = $this->Employees_model->delete_disciplinary($da_id);

        if ($delete_disciplinary == true) {
            echo 1;
        } else {
            echo 2;
        }
    }


    /*
    |------------------------------------------------------
    | Wages
    |--------------------------------------------------------
    */

    public function get_wage_history_list()
    {
        $wage_list = $this->Employees_model->get_wage_history();
        $result = array();
        $i = 1;
        foreach ($wage_list as $key => $value) {

            $button = '<button class="btn btn-xs btn-success" onclick="edit_wage_ajax(' . $value['wage_id'] . ')">
                        <i class="fa fa-pencil"></i></button>';

            $button .= " ";

            $button .= '<button class="btn btn-xs btn-danger" onclick="delete_wage_ajax(' . $value['wage_id'] . ')">
                        <i class="fa fa-trash"></i></button>';

            $result['data'][] = array(
                $i++,
                $value['wage_start_date'],
                $value['wage_end_date'],
                $value['wage_job_title'],
                $value['wage_department'],
                $value['wage_name'],
                $value['wage_band'],
                $value['wage_step'],
                $button

            );
        }
        echo json_encode($result);
    }

    public function create_wage_history()
    {
        $postData = [
            'wage_job_title' => $this->input->post('wage_job_title', true),
            'wage_name' => $this->input->post('wage_name', true),
            'wage_type' => $this->input->post('wage_type', true),
            'wage_band' => $this->input->post('wage_band', true),
            'wage_step' => $this->input->post('wage_step', true),
            'wage_start_date' => $this->input->post('wage_start_date', true),
            'wage_end_date' => $this->input->post('wage_end_date', true),
            'wage_department' => $this->input->post('wage_department', true),
            'wage_manager' => $this->input->post('wage_manager', true),
            'wage_comments' => $this->input->post('wage_comments', true),
            'employee_id' => $this->input->post('employee_id', true),
        ];

        $add_wage = $this->Employees_model->create_wage($postData);

        if ($add_wage == true) {
            echo 1;
        } else {
            echo 2;
        }
    }

    public function get_edit_wage()
    {
        $wage_id = $this->input->post('wage_id', true);
        $resultData = $this->Employees_model->get_single_wage($wage_id);
        echo json_encode($resultData);
    }

    public function update_wage_history()
    {
        $postData = [
            'wage_job_title' => $this->input->post('wage_job_title', true),
            'wage_name' => $this->input->post('wage_name', true),
            'wage_type' => $this->input->post('wage_type', true),
            'wage_band' => $this->input->post('wage_band', true),
            'wage_step' => $this->input->post('wage_step', true),
            'wage_start_date' => $this->input->post('wage_start_date', true),
            'wage_end_date' => $this->input->post('wage_end_date', true),
            'wage_department' => $this->input->post('wage_department', true),
            'wage_manager' => $this->input->post('wage_manager', true),
            'wage_comments' => $this->input->post('wage_comments', true),
            'wage_id' => $this->input->post('wage_id', true),
        ];

        $update_wage = $this->Employees_model->update_wage($postData);

        if ($update_wage == true) {
            echo 1;
        } else {
            echo 2;
        }

    }

    public function delete_wage_history()
    {
        $wage_id = $this->input->post('wage_id', true);
        $delete_wage = $this->Employees_model->delete_wage($wage_id);

        if ($delete_wage == true) {
            echo 1;
        } else {
            echo 2;
        }
    }

    // Employee Salary Paid info
    public function EmployeePayment()
    {
        $sal_id = $this->input->post('sal_id');
        $employee_id = $this->input->post('employee_id');
        $emplyeeinfo = $this->db->select('first_name,last_name')->from('employee_history')->where('employee_id', $employee_id)->get()->row();
        $data = array(
            'employee_id' => $employee_id,
            'Ename' => $emplyeeinfo->first_name . $emplyeeinfo->last_name,
            'salP_id' => $sal_id,
        );
        echo json_encode($data);
    }

    // confirm payment

    public function payconfirm($id = null)
    {

        $this->form_validation->set_rules('paytype', display('payment_type'), 'required');
        if ($this->form_validation->run()) {
            $postData = [
                'emp_sal_pay_id' => $this->input->post('emp_sal_pay_id', true),
                'payment_due' => 'paid',
                'payment_date' => date('Y-m-d'),
                'payment_type' => $this->input->post('paytype', true),
                'bank_name' => $this->input->post('bank_name', true),
                'paid_by' => $this->session->userdata('fullname'),
            ];

            $emp_id = $this->input->post('employee_id', true);
            $c_name = $this->db->select('first_name,last_name')->from('employee_history')->where('employee_id', $emp_id)->get()->row();
            $c_acc = $emp_id . '-' . $c_name->first_name . $c_name->last_name;
            $coatransactionInfo = $this->db->select('HeadCode')->from('acc_coa')->where('HeadName', $c_acc)->get()->row();
            $COAID = $coatransactionInfo->HeadCode;
            $pay_type = $this->input->post('paytype', true);

            $bankname = $this->input->post('bank_name', true);
            $bankhead = $this->db->select('HeadCode')->from('acc_coa')->where('HeadName', $bankname)->get()->row()->HeadCode;

            $CashinHandDebit = array(
                'VNo' => $this->input->post('emp_sal_pay_id', true),
                'Vtype' => 'Salary',
                'VDate' => date('Y-m-d'),
                'COAID' => 1020101,
                'Narration' => 'Cash in hand Debit For Employee Id' . $this->input->post('employee_id', true),
                'Debit' => 0,
                'Credit' => intval(str_replace(',', '', $this->input->post('total_salary', true))),
                'IsPosted' => 1,
                'CreateBy' => $this->session->userdata('id'),
                'CreateDate' => date('Y-m-d H:i:s'),
                'IsAppove' => 1
            );

            // Expense for salary payment
            $expense = array(
                'VNo' => $this->input->post('emp_sal_pay_id', true),
                'Vtype' => 'Salary',
                'VDate' => date('Y-m-d'),
                'COAID' => 401,
                'Narration' => 'salary payment for ' . $this->input->post('employee_id', true),
                'Debit' => intval(str_replace(',', '', $this->input->post('total_salary', true))),
                'Credit' => 0,
                'IsPosted' => 1,
                'CreateBy' => $this->session->userdata('id'),
                'CreateDate' => date('Y-m-d H:i:s'),
                'IsAppove' => 1
            );
            $accpayable = array(
                'VNo' => $this->input->post('emp_sal_pay_id', true),
                'Vtype' => 'Salary',
                'VDate' => date('Y-m-d'),
                'COAID' => $COAID,
                'Narration' => 'Salary For Employee Id' . $this->input->post('employee_id', true),
                'Debit' => intval(str_replace(',', '', $this->input->post('total_salary', true))),
                'Credit' => 0,
                'IsPosted' => 1,
                'CreateBy' => $this->session->userdata('id'),
                'CreateDate' => date('Y-m-d H:i:s'),
                'IsAppove' => 1
            );

            $banktransaction = array(
                'VNo' => $this->input->post('emp_sal_pay_id', true),
                'Vtype' => 'Salary',
                'VDate' => date('Y-m-d'),
                'COAID' => $bankhead,
                'Narration' => 'Employee Salary Payment',
                'Debit' => 0,
                'Credit' => intval(str_replace(',', '', $this->input->post('total_salary', true))),
                'IsPosted' => 1,
                'CreateBy' => $this->session->userdata('id'),
                'CreateDate' => date('Y-m-d H:i:s'),
                'IsAppove' => 1
            );


            if ($this->Employees_model->update_payment($postData)) {

                $this->db->insert('acc_transaction', $accpayable);
                $this->db->insert('acc_transaction', $expense);
                if ($pay_type == 1) {
                    $this->db->insert('acc_transaction', $CashinHandDebit);
                } else {
                    $this->db->insert('acc_transaction', $banktransaction);
                }
                redirect('payroll/Payroll/payslip/' . $this->input->post('emp_sal_pay_id', true));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
                redirect($_SERVER['HTTP_REFERER']);
            }


        } else {
            $this->session->set_flashdata('exception', display('please_try_again'));
            redirect($_SERVER['HTTP_REFERER']);
        }
    }

    /*
    |------------------------------------------------------
    | Finger Print Device Information
    |--------------------------------------------------------
    */
    function device_user()
    {
        $this->permission->module('employee', 'read')->redirect();
        $device_ip = $this->deviceData()->device_ip;
        $data['connect'] = '';
        $data['disableDevice'] = '';
        $data['users'] = '';
        $data['enableDevice'] = '';
        $data['disconnect'] = '';
        $data['module'] = "employee";
        $data['page'] = "device/userlist";
        echo Modules::run('template/layout', $data);
    }

    /*
|--------------------------------------------------------
| Finger print Device information
|--------------------------------------------------------
*/
    public function deviceData()
    {
        return $this->db->select('*')->from('deviceinfo')->get()->row();
    }

    public function payslip()
    {
        $data['title'] = 'payslip';
        $data['module'] = "employee";
        $data['page'] = "payslip";
        echo Modules::run('template/layout', $data);
    }

    public function bulk_import_csv()
    {
        if (isset($_FILES["upload_csv_file"]["name"]) && $_FILES["upload_csv_file"]["name"]) {

            $postData = array();

            $path = $_FILES["upload_csv_file"]["tmp_name"];
            $object = PHPExcel_IOFactory::load($path);
            foreach ($object->getWorksheetIterator() as $sale) {

                $highestRow = $sale->getHighestRow();
                $highestColumn = $sale->getHighestColumn();
                for ($row = 2; $row <= $highestRow; $row++) {
                    $firstName = $sale->getCellByColumnAndRow(0, $row)->getValue();
                    $lastName = $sale->getCellByColumnAndRow(1, $row)->getValue();
                    $empCode = $sale->getCellByColumnAndRow(2, $row)->getValue();
                    $phone_num = $sale->getCellByColumnAndRow(3, $row)->getValue();
                    $department_name = $sale->getCellByColumnAndRow(4, $row)->getValue();
                    $position = $sale->getCellByColumnAndRow(5, $row)->getValue();
                    $hireDate = $sale->getCellByColumnAndRow(6, $row)->getValue();
                    $probationDate = $sale->getCellByColumnAndRow(7, $row)->getValue();
                    $rate_type = $sale->getCellByColumnAndRow(8, $row)->getValue();
                    $rate_amount = $sale->getCellByColumnAndRow(9, $row)->getValue();
                    $pay_frequency = $sale->getCellByColumnAndRow(10, $row)->getValue();
                    $dutyType = $sale->getCellByColumnAndRow(11, $row)->getValue();
                    $date_of_birth = $sale->getCellByColumnAndRow(12, $row)->getValue();
                    $gender = $sale->getCellByColumnAndRow(13, $row)->getValue();
                    $religionField = $sale->getCellByColumnAndRow(14, $row)->getValue();
                    $work_in_state = $sale->getCellByColumnAndRow(15, $row)->getValue();
                    $live_in_state = $sale->getCellByColumnAndRow(16, $row)->getValue();
                    $citizenship = $sale->getCellByColumnAndRow(17, $row)->getValue();
                    $accountTitle = $sale->getCellByColumnAndRow(18, $row)->getValue();
                    $bankName = $sale->getCellByColumnAndRow(19, $row)->getValue();
                    $accountNumber = $sale->getCellByColumnAndRow(20, $row)->getValue();
                    $ibanNumber = $sale->getCellByColumnAndRow(21, $row)->getValue();
                    $emergContctPersonName = $sale->getCellByColumnAndRow(22, $row)->getValue();
                    $emergContctPersonRelation = $sale->getCellByColumnAndRow(23, $row)->getValue();
                    $emergContctPersonPhone = $sale->getCellByColumnAndRow(24, $row)->getValue();
                    $empCnic = $sale->getCellByColumnAndRow(25, $row)->getValue();
                    $country = $sale->getCellByColumnAndRow(26, $row)->getValue();
                    $city_name = $sale->getCellByColumnAndRow(27, $row)->getValue();
                    $zip_code = $sale->getCellByColumnAndRow(28, $row)->getValue();
                    $empExpStartDate = $sale->getCellByColumnAndRow(29, $row)->getValue();
                    $empExpEndDate = $sale->getCellByColumnAndRow(30, $row)->getValue();
                    $bachelorsDegreeTitle = $sale->getCellByColumnAndRow(31, $row)->getValue();
                    $bachelorsMajors = $sale->getCellByColumnAndRow(32, $row)->getValue();
                    $bachelorsYearCompletion = $sale->getCellByColumnAndRow(33, $row)->getValue();
                    $bachelorsInstitute = $sale->getCellByColumnAndRow(34, $row)->getValue();
                    $bachelorsLocation = $sale->getCellByColumnAndRow(35, $row)->getValue();
                    $bachelorsCgpa = $sale->getCellByColumnAndRow(36, $row)->getValue();
                    $personalEmail = $sale->getCellByColumnAndRow(37, $row)->getValue();
                    $email = $sale->getCellByColumnAndRow(38, $row)->getValue();
                    $user_password = $sale->getCellByColumnAndRow(39, $row)->getValue();

                    if ($firstName == null) {
                        $first_name = '';
                    } else {
                        $first_name = $firstName;
                    }

                    if ($lastName == null) {
                        $last_name = '';
                    } else {
                        $last_name = $lastName;
                    }

                    if ($phone_num == null) {
                        $phone = '';
                    } else {
                        $phone = $phone_num;
                    }

                    if ($hireDate == null) {
                        $hire_date = '';
                    } else {
                        $date = str_replace('/', '-', $hireDate);
                        $hire_date = date('Y-m-d', strtotime($date));
                    }

                    if ($probationDate == null) {
                        $original_hire_date = '';
                    } else {
                        $date = str_replace('/', '-', $probationDate);
                        $original_hire_date = date('Y-m-d', strtotime($date));
                    }

                    if ($rate_amount == null) {
                        $rate = '';
                    } else {
                        $rate = $rate_amount;
                    }

                    if ($date_of_birth == null) {
                        $dob = '';
                    } else {
                        $date = str_replace('/', '-', $date_of_birth);
                        $dob = date('Y-m-d', strtotime($date));
                    }

                    if ($empCode == null) {
                        $emp_code = '';
                    } else {
                        $emp_code = $empCode;
                    }

                    if ($empCnic == null) {
                        $emp_cnic = '';
                    } else {
                        $emp_cnic = $empCnic;
                    }

                    if ($country == null) {
                        $state = '';
                    } else {
                        $state = $country;
                    }

                    if ($city_name == null) {
                        $city = '';
                    } else {
                        $city = $city_name;
                    }

                    if ($zip_code == null) {
                        $zip = '';
                    } else {
                        $zip = $zip_code;
                    }

                    if ($empExpStartDate == null) {
                        $emp_exp_start_date = '';
                    } else {
                        $emp_exp_start_date = $empExpStartDate;
                    }

                    if ($empExpEndDate == null) {
                        $emp_exp_end_date = '';
                    } else {
                        $emp_exp_end_date = $empExpEndDate;
                    }

                    if ($bachelorsDegreeTitle == null) {
                        $bachelors_degree_title = '';
                    } else {
                        $bachelors_degree_title = $bachelorsDegreeTitle;
                    }

                    if ($bachelorsMajors == null) {
                        $bachelors_majors = '';
                    } else {
                        $bachelors_majors = $bachelorsMajors;
                    }

                    if ($bachelorsYearCompletion == null) {
                        $bachelors_year_completion = '';
                    } else {
                        $bachelors_year_completion = $bachelorsYearCompletion;
                    }

                    if ($bachelorsInstitute == null) {
                        $bachelors_institute = '';
                    } else {
                        $bachelors_institute = $bachelorsInstitute;
                    }

                    if ($bachelorsLocation == null) {
                        $bachelors_location = '';
                    } else {
                        $bachelors_location = $bachelorsLocation;
                    }

                    if ($bachelorsCgpa == null) {
                        $bachelors_cgpa = '';
                    } else {
                        $bachelors_cgpa = $bachelorsCgpa;
                    }

                    if ($religionField == null) {
                        $ethnic_group = '';
                    } else {
                        $ethnic_group = $religionField;
                    }

                    if ($accountTitle == null) {
                        $account_title = '';
                    } else {
                        $account_title = $accountTitle;
                    }

                    if ($bankName == null) {
                        $bank_name = '';
                    } else {
                        $bank_name = $bankName;
                    }

                    if ($accountNumber == null) {
                        $account_number = '';
                    } else {
                        $account_number = $accountNumber;
                    }

                    if ($ibanNumber == null) {
                        $iban_number = '';
                    } else {
                        $iban_number = $ibanNumber;
                    }

                    if ($emergContctPersonName == null) {
                        $name_emg_contact_person_1 = '';
                    } else {
                        $name_emg_contact_person_1 = $emergContctPersonName;
                    }

                    if ($emergContctPersonRelation == null) {
                        $relation_emg_contact_person_1 = '';
                    } else {
                        $relation_emg_contact_person_1 = $emergContctPersonRelation;
                    }

                    if ($emergContctPersonPhone == null) {
                        $phone_emg_contact_person_1 = '';
                    } else {
                        $phone_emg_contact_person_1 = $emergContctPersonPhone;
                    }

                    if ($personalEmail == null) {
                        $personal_email = '';
                    } else {
                        $personal_email = $personalEmail;
                    }

                    if ($user_password == null) {
                        $password = '00000000';
                    } else {
                        $password = $user_password;
                    }


                    $department_id = $this->db->select('*')
                        ->from('department')
                        ->where('department_name', $department_name)
                        ->get()
                        ->result();

                    if ($department_id == null) {
                        $dept_id = '';
                    } else {
                        $dept_id = $department_id["0"]->dept_id;
                    }

                    $position_id = $this->db->select('*')
                        ->from('position')
                        ->where('position_name', $position)
                        ->get()
                        ->result();

                    if ($position_id == null) {
                        $pos_id = '';
                    } else {
                        $pos_id = $position_id["0"]->pos_id;
                    }

                    if ($rate_type == "Wages") {
                        $rate_type = 1;
                    } else if ($rate_type == "Salary") {
                        $rate_type = 2;
                    } else {
                        $rate_type = '';
                    }

                    if ($pay_frequency == "Weekly") {
                        $pay_frequency = 1;
                    } else if ($pay_frequency == "Biweekly") {
                        $pay_frequency = 2;
                    } else if ($pay_frequency == "Monthly") {
                        $pay_frequency = 4;
                    } else if ($pay_frequency == "Annual") {
                        $pay_frequency = 3;
                    } else {
                        $pay_frequency = '';
                    }

                    if ($dutyType == "Intern") {
                        $duty_type = 1;
                    } else if ($dutyType == "Full Time") {
                        $duty_type = 2;
                    } else if ($dutyType == "Part Time") {
                        $duty_type = 3;
                    } else if ($dutyType == "Contructual") {
                        $duty_type = 4;
                    } else if ($dutyType == "Other") {
                        $duty_type = 5;
                    } else {
                        $duty_type = '';
                    }

                    if ($gender == "Male") {
                        $gender = 1;
                    } else if ($gender == "Female") {
                        $gender = 2;
                    } else {
                        $gender = '';
                    }

                    $postData[] = [
                        'first_name' => $first_name,
                        'last_name' => $last_name,
                        'phone' => $phone,
                        'dept_id' => $dept_id,
                        'pos_id' => $pos_id,
                        'hire_date' => $hire_date,
                        'original_hire_date' => $original_hire_date,
                        'rate_type' => $rate_type,
                        'rate' => $rate,
                        'pay_frequency' => $pay_frequency,
                        'duty_type' => $duty_type,
                        'dob' => $dob,
                        'gender' => $gender,
                        'ethnic_group' => $ethnic_group,
                        'work_in_state' => $work_in_state,
                        'live_in_state' => $live_in_state,
                        'citizenship' => $citizenship,
                        'account_title' => $account_title,
                        'account_number' => $account_number,
                        'bank_name' => $bank_name,
                        'iban_number' => $iban_number,
                        'name_emg_contact_person_1' => $name_emg_contact_person_1,
                        'relation_emg_contact_person_1' => $relation_emg_contact_person_1,
                        'phone_emg_contact_person_1' => $phone_emg_contact_person_1,
                        'emp_code' => $emp_code,
                        'emp_cnic' => $emp_cnic,
                        'state' => $state,
                        'city' => $city,
                        'zip' => $zip,
                        'emp_exp_start_date' => $emp_exp_start_date,
                        'emp_exp_end_date' => $emp_exp_end_date,
                        'bachelors_degree_title' => $bachelors_degree_title,
                        'bachelors_majors' => $bachelors_majors,
                        'bachelors_year_completion' => $bachelors_year_completion,
                        'bachelors_institute' => $bachelors_institute,
                        'bachelors_location' => $bachelors_location,
                        'bachelors_cgpa' => $bachelors_cgpa,
                        'personal_email' => $personal_email,
                        'email' => $email,
                        'password' => md5($password),
                    ];

                }

            }

            foreach ($postData as $data) {

                $user_email = $this->db->select('*')
                    ->from('employee_history')
                    ->where('email', $data["email"])
                    ->get()
                    ->result();

                if ($user_email != null) {

                    if ($this->Employees_model->update_employee_csv($data)) {

                        $employee_old_useremail = $data["email"];
                        $user_his = $this->db->select('*')
                            ->from('user')
                            ->where('email', $employee_old_useremail)
                            ->get()
                            ->num_rows();

                        if ($user_his > 0) {

                            $userData = array(
                                'firstname' => $data['first_name'],
                                'lastname' => $data['last_name'],
                                'email' => $data['email'],
                                'password' => md5($data['password']),
                                'is_admin' => 0,
                            );
                            $this->db->where('email', $data['email'])
                                ->update("user", $userData);

                        }

                    }

                } else {

                    $employee_h = $this->db->select('employee_id')
                        ->from('employee_history')
                        ->order_by('emp_his_id', 'desc')
                        ->get()
                        ->row();
                    $max_id = $employee_h->employee_id;
                    if (!empty($max_id)) {
                        $employee_id = $max_id + 1;
                    } else {
                        $employee_id = 1;
                    }

                    $emp_id_arr = array('employee_id' => $employee_id);

                    $dataArr = array_merge($data, $emp_id_arr);

                    if ($this->Employees_model->create_employee($dataArr)) {

                        $userData = array(
                            'firstname' => $data['first_name'],
                            'lastname' => $data['last_name'],
                            'email' => $data['email'],
                            'password' => md5($data['password']),
                            'is_admin' => 0,
                            'image' => (!empty($img) ? substr($img, 2) : ''),
                        );
                        $this->db->insert('user', $userData);
                        $user_id = $this->db->insert_id();
                        $rolData = array(
                            'fk_role_id' => 1,
                            'fk_user_id' => $user_id
                        );
                        $this->db->insert('sec_user_access_tbl', $rolData);
                    }
                }


            }
            $this->session->set_flashdata('message', display('save_successfully'));
            redirect("employee/Employees/manageemployee");

        }
    }

    public function employee_filter()
    {
        $this->permission->module('employee', 'read')->redirect();

        $employe_status = $this->input->post('employee_status', true);
        $employee_job_status = $this->input->post('employee_job_status', true);
        $duty_type = $this->input->post('duty_type', true);


        if (!empty($employe_status) && !empty($employee_job_status) && !empty($duty_type)) {
            if ($employe_status == 5) {
                $employe_status = 0;
            } else {
                $employe_status = $employe_status;
            }

            $data['emp_history'] = $this->Employees_model->emp_status_dropdown($employe_status, $employee_job_status, $duty_type);
            $data['module'] = "employee";

        } else if (!empty($employe_status) && !empty($employee_job_status) && empty($duty_type)) {
            if ($employe_status == 5) {
                $employe_status = 0;
            } else {
                $employe_status = $employe_status;
            }
            $data['emp_history'] = $this->Employees_model->emp_status($employe_status, $employee_job_status);
            $data['module'] = "employee";
        } else if (empty($employe_status) && !empty($employee_job_status) && !empty($duty_type)) {
            $data['emp_history'] = $this->Employees_model->emp_date($employee_job_status, $duty_type);
            $data['module'] = "employee";
        } else if (!empty($employe_status) && empty($employee_job_status) && !empty($duty_type)) {
            echo "if 4 working";
            if ($employe_status == 5) {
                $employe_status = 0;
            } else {
                $employe_status = $employe_status;
            }
            $data['emp_history'] = $this->Employees_model->emp_status_type($employe_status, $duty_type);
            $data['module'] = "employee";
        } else if (!empty($employe_status) && empty($employee_job_status) && empty($duty_type)) {
            if ($employe_status == 5) {
                $employe_status = 0;
            } else {
                $employe_status = $employe_status;
            }
            $data['emp_history'] = $this->Employees_model->employee_status_type($employe_status);
            $data['module'] = "employee";
        } else if (empty($employe_status) && !empty($employee_job_status) && empty($duty_type)) {
            $data['emp_history'] = $this->Employees_model->employee_job_status($employee_job_status);
            $data['module'] = "employee";
        } else if (empty($employe_status) && empty($employee_job_status) && !empty($duty_type)) {
            $data['emp_history'] = $this->Employees_model->duty_type($duty_type);
            $data['module'] = "employee";
        } else {
            redirect("employee/Employees/manageemployee");
        }
        $data['page'] = "employee_view";
        echo Modules::run('template/layout', $data);
    }

    public function update_salary_position($id = null)
    {

        $date = $date = date('Y-m-d');

        $current_salary = $this->input->post('current_salary', true);
        $current_designation = $this->input->post('position_modal_sal', true);
        $change_date = $date;
        $employee_id = $this->input->post('hidden_id_model_conformation', true);

        $firstName = $this->input->post('fname_modal_sal', true);
        $lastName = $this->input->post('lname_modal_sal');
        $empEmail = $this->input->post('email_modal_sal', true);
        $salary = $this->input->post('salary', true);
        $position_id = $this->input->post('designation', true);
        $comment = $this->input->post('comment', true);

        $designationn = $this->Employees_model->designation(); // Set By Inam

        foreach ($designationn as $d) {
            if ($d->pos_id == $position_id) {
                $position = $d->position_name;
                break;
            }
        }

        if (true) {

            $currentData = [
                'old_salary' => $current_salary,
                'old_designation' => $current_designation,
                'change_date' => $change_date,
                'employee_id' => $employee_id,
            ];

            $this->Employees_model->emp_salary_log($currentData);

            $postData = [
                'employee_id' => $employee_id,
                'rate' => $this->input->post('salary', true),
                'pos_id' => $this->input->post('designation', true),
            ];

            if ($this->Employees_model->update_salary_position($postData)) {

                $this->session->set_flashdata('message', display('successfully_updated'));
            } else {

                $this->session->set_flashdata('exception', display('please_try_again'));
            }

            $msg = "Dear $firstName $lastName" . "\nYour Data has been Updated in HR portal 
              \n Your New Salary is $salary and Possition is $position. 
              \n '$comment'";

            $msg = wordwrap($msg, 70);

            mail($empEmail, "HR Portal Update", $msg);


            redirect('employee/Employees/manageemployee');
        }

    }

    public function update_warning($id = null)
    {

        $current_date = date("Y-m-d");

        $firstName = $this->input->post('fname_modal_ter', true);
        $lastName = $this->input->post('lname_modal_ter', true);
        $empEmail = $this->input->post('email_modal_ter', true);
        $reason = $this->input->post('reason', true);

        $postData = [
            'reason' => $reason,
            'date' => $current_date,
            'employee_id' => $this->input->post('hidden_id_model_termination', true),

        ];

        if ($this->Employees_model->add_warning($postData)) {
            $this->session->set_flashdata('message', display('successfully_updated'));
        } else {
            $this->session->set_flashdata('exception', display('please_try_again'));
        }

        $msg = "Dear $firstName $lastName" . "\nThis is your warning \ndue to '" . $reason . "'";

        $msg = wordwrap($msg, 70);

        mail($empEmail, "HR Portal Update", $msg);

        redirect('employee/Employees/manageemployee');
    }

    public function terminate()
    {

        $firstName = $this->input->post('ter_first_name', true);
        $lastName = $this->input->post('ter_last_name', true);
        $empEmail = $this->input->post('ter_email', true);

        $terminate = 1;
        $terminate_date = date("Y-m-d");
        $terminate_reason = $this->input->post('ter_reason', true);
        $employee_status = 0;
        $employee_id = $this->input->post('ter_emp_id', true);

        $postData = [
            'terminate' => $terminate,
            'terminate_date' => $terminate_date,
            'terminate_reason' => $terminate_reason,
            'employee_status' => $employee_status,
            'employee_id' => $employee_id,
        ];

        if ($this->Employees_model->update_termination($postData)) {
            $this->session->set_flashdata('message', display('successfully_updated'));
        } else {
            $this->session->set_flashdata('exception', display('please_try_again'));
        }

        $msg = "Dear $firstName $lastName" . "\nThis is your warning \ndue to '" . $terminate_reason . "'";

        $msg = wordwrap($msg, 70);

        mail($empEmail, "HR Portal Update", $msg);

        redirect('employee/Employees/manageemployee');
    }

}