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

class Employees_performance extends MX_Controller
{

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

        ));
        $this->load->model('employee/employees_model'); 

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

    }

    private function _send_emp_notification_email($email, $name, $score, $comments, $id, $appraised_by) {
        // Load the email library if not already loaded
        $this->load->library('email');
        
        // Define the message
        $message = "
            $name $email has commented on the appraisal. 
            Summary of the appraisal comments:
            Full Name: $name
            Appraisal Score: $score
            Appraised By: $appraised_by
            Comments By Employee: $comments
    
            Click on the link to login and view the detailed report:  https://pti.tppa-ng.com/pti/employee/employees_performance/employee_performance_update/$id.
            ";
    
        // Set up email configuration
        $this->email->from('no-reply@pti.tppa-ng.com', 'PTI Appraisal');
        $this->email->to($email);
        $this->email->subject('Appraisal Notification');
        $this->email->message($message);
    
        // Send the email and log any errors
        if (!$this->email->send()) {
            log_message('error', 'Email not sent: '.$this->email->print_debugger());
        }
    }
    
    private function _send_notification_email($email, $firstname, $lastname, $score, $appraised_by, $counter_signed_by, $comments) {
        // Load the email library if not already loaded
        $this->load->library('email');
        
        // Define the message
        $message = "
            Your appraisal for the quarter has been conducted. 
            Summary of the appraisal:
            Full Name: $firstname $lastname
            Appraisal Score: $score
            Appraised By: $appraised_by
            Counter Signed By: $counter_signed_by
            Comments By Officer: $comments
    
            Click on the link to login and view the detailed report: https://pti.tppa-ng.com/pti/dashboard/home.
            ";
    
        // Set up email configuration
        $this->email->from('no-reply@pti.tppa-ng.com', 'PTI Appraisal');
        $this->email->to($email);
        $this->email->subject('Appraisal Notification');
        $this->email->message($message);
    
        // Send the email and log any errors
        if (!$this->email->send()) {
            log_message('error', 'Email not sent: '.$this->email->print_debugger());
        }
    }
    

    public function paerformance_sub_category_view()
    {

        $this->permission->check_label('emp_performance')->read()->access();

        $data['title'] = display('perform_sub_category');
        $data['perform_sub_categories'] = $this->Employee_performance_model->paerformance_sub_categories();
        $data['module'] = "employee";
        $data['page'] = "emp_performance/list";

        echo Modules::run('template/layout', $data);
    }
    public function create_performance_sub_category()
    {
        $this->permission->module('performance_category', 'create')->redirect();

        $data['title'] = display('perform_sub_category');
        #-------------------------------#
        $this->form_validation->set_rules('name', display('name'), 'required|max_length[50]');
        $this->form_validation->set_rules('details', display('details'), 'max_length[200]');
        #-------------------------------#
        if ($this->form_validation->run() === true) {

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

            $postData['CreateDate'] = date('Y-m-d');
            $postData['CreateBy'] = $this->session->userdata('id');

            if ($this->Employee_performance_model->create_paerformance_sub_category($postData)) {
                $this->session->set_flashdata('message', display('successfully_saved'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }

        } else {
            $this->session->set_flashdata('exception', validation_errors());

        }

        redirect("employee/employees_performance/paerformance_sub_category_view");
    }

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

        $data['title'] = display('manage_sub_category');
        $data['perform_sub_categories'] = $this->Employee_performance_model->paerformance_sub_categories();
        $data['module'] = "employee";
        $data['page'] = "emp_performance/manage_performance_subcategory";

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

    public function update_performance_sub_category($id = null)
    {

        $this->permission->module('performance_category', 'update')->redirect();

        $data['title'] = display('update_sub_category');

        $this->form_validation->set_rules('id', null, 'required|max_length[11]');
        $this->form_validation->set_rules('name', display('name'), 'required|max_length[50]');
        $this->form_validation->set_rules('details', display('details'), 'max_length[200]');

        #-------------------------------#

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

            $postData = [
                'id' => $this->input->post('id', true),
                'name' => $this->input->post('name', true),
                'details' => $this->input->post('details', true),

            ];

            $postData['UpdateDate'] = date('Y-m-d');
            $postData['UpdateBy'] = $this->session->userdata('id');

            if ($this->Employee_performance_model->update_paerformance_sub_category($postData)) {
                $this->session->set_flashdata('message', display('successfully_updated'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }
            redirect("employee/employees_performance/manage_performance_sub_category");

        } else {

            $data['data'] = $this->Employee_performance_model->paerformance_sub_category_by_id($id);
            $data['module'] = "employee";
            $data['page'] = "emp_performance/update_performance_subcategory";

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

    }

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

        if ($this->Employee_performance_model->paerformance_sub_category_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_performance/manage_performance_sub_category");
    }

    /*Points giving starts*/

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

        $data['title'] = display('category_wise_performance');
        $data['category_wise_performances'] = $this->Employee_performance_model->category_wise_performances();
        $data['employee'] = $this->Employees_model->employee();
        $data['paerform_sub_category_list'] = $this->Employee_performance_model->paerform_sub_category_list();
        $data['module'] = "employee";
        $data['page'] = "emp_performance/emp_cat_perform_list";

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

    public function add_performance_by_sub_category()
    {
        $this->permission->module('category_wise_performance', 'create')->redirect();

        $data['title'] = display('category_wise_performance');
        #-------------------------------#
        $this->form_validation->set_rules('employee_id', display('employee_name'), 'required');
        $this->form_validation->set_rules('sub_cat_id', display('sub_category'), 'required');
        $this->form_validation->set_rules('points', display('point'), 'required');
        #-------------------------------#
        if ($this->form_validation->run() === true) {

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

            $postData['CreateDate'] = date('Y-m-d');
            $postData['CreateBy'] = $this->session->userdata('id');

            // Check point already given for any specific category to an employee, then not allow to create same..
            $paerform_by_sub_category_and_empid = $this->Employee_performance_model->paerform_by_sub_category_and_empid($postData['employee_id'], $postData['sub_cat_id']);
            if ($paerform_by_sub_category_and_empid) {

                $this->session->set_flashdata('exception', "Point given to the employee for the selected category for current month !");
                redirect("employee/employees_performance/category_performance_view");
            }

            if ($this->Employee_performance_model->performance_by_sub_category($postData)) {
                $this->session->set_flashdata('message', display('successfully_saved'));
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }

        } else {
            $this->session->set_flashdata('exception', validation_errors());

        }

        redirect("employee/employees_performance/category_performance_view");
    }

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

        $data['title'] = display('manage_category_wise_performance');
        $data['category_wise_performances'] = $this->Employee_performance_model->category_wise_performances();
        $data['module'] = "employee";
        $data['page'] = "emp_performance/manage_category_wise_performance";

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

    public function update_category_wise_performance($id = null)
    {

        $this->permission->module('category_wise_performance', 'update')->redirect();

        $data['data'] = $category_wise_performance_info = $this->Employee_performance_model->category_wise_performances_by_id($id);

        $data['title'] = display('update_category_wise_performance');

        $this->form_validation->set_rules('id', null, 'required|max_length[11]');

        $this->form_validation->set_rules('points', display('point'), 'required');

        #-------------------------------#

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

            $postData = [
                'id' => $this->input->post('id', true),
                'points' => $this->input->post('points', true),

            ];

            $postData['UpdateDate'] = date('Y-m-d');
            $postData['UpdateBy'] = $this->session->userdata('id');

            // Check, if the update request exceeds the existing record(which going tp update) creation month and year comparing with current date...
            $exsting_record_create_year = date('Y', strtotime($category_wise_performance_info->CreateDate));
            $exsting_record_create_month = date('m', strtotime($category_wise_performance_info->CreateDate));

            if ((int) $exsting_record_create_year == (int) date('Y') && (int) $exsting_record_create_month == (int) date('m')) {

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

            } else {

                $this->session->set_flashdata('exception', "You can not update old performace record !");
            }

            redirect("employee/employees_performance/manage_category_wise_performance_view");

        } else {

            $data['employee'] = $this->Employees_model->employee();
            $data['paerform_sub_category_list'] = $this->Employee_performance_model->paerform_sub_category_list();
            $data['module'] = "employee";
            $data['page'] = "emp_performance/update_category_wise_performance";

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

    }

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

        if ($this->Employee_performance_model->category_wise_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_performance/manage_category_wise_performance_view");
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////
    /* Employee performance as per Gambia client Appraisal shared file*/

    public function emp_performance_list()
{
    // Check permission
    $permission = $this->permission->check_label('emp_performance')->read()->access();

    // Initialize employee ID
    $employee_id = null;
    $userRole = $this->session->userdata('userRole');

    // Check if the permission is read-only and if employee ID is stored in the session
    if ($userRole == 1) {
        $employee_id = $this->session->userdata('employee_id'); // Assuming employee ID is stored in session
         // Fetch employee performance list based on the presence of employee ID
    $data['emp_performances'] = $this->Employee_performance_model->emp_performance_appraisal_list($employee_id);

    }
    else{
         // Fetch employee performance list based on the presence of employee ID
    $data['emp_performances'] = $this->Employee_performance_model->emp_performance_appraisal_list();

    }
   
     // Check if the user is an admin
     $data['is_admin'] = $this->session->userdata('isAdmin'); 
     $data['userRole'] = $this->session->userdata('userRole');

    $data['title'] = display('emp_performance');
    $data['module'] = "employee";
    $data['page'] = "emp_perform_appraisal/list";

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

public function fetch_employee_info() {
    $employee_id = $this->input->post('employee_id');

    if ($employee_id) {
        // Fetch employee details
        $emp_details = $this->employees_model->employee_details($employee_id);

        $duties_details = $this->employees_model->dutieslist($employee_id);
        
        // Fetch academic qualifications
        $academic = $this->employees_model->academiclist();
        
        // Fetch professional qualifications
        $professional = $this->employees_model->professionlist();

        //prepare selection of form
        $position_name = $emp_details->position_name;
        $options = [
            'Senior Non Academic' => 'Senior Staff Non Academic ',
            'Senior Academic' => 'Senior Staff Academic',
            'Management Staff' => 'Management Staff Academic ',
            'Management Staff Non' => 'Management Staff Non Academic ',
            'Annual Performance' => 'Junior Staff'
        ];
        
        $selected_position = $emp_details->position_name;
        
        $emp_select_html = '<span class="w-250 fw-700">Staff status :</span>
        <select id="staff_select" name="staff_status" class="form-control"
            aria-describedby="basic-addon1" onchange="showRows()">
            <option value="" disabled selected>Select Staff Status</option>';
        
        foreach ($options as $key => $value) {
            if ($selected_position == $value) {
                $emp_select_html .= '<option value="' . $key . '">' . $value . '</option>';
            }
        }
        
        $emp_select_html .= '</select>';

    

        // Prepare employee details HTML
        $emp_details_html = '
            <table class="table table-hover" width="100%">
                <caption class="resumecaption">' . display('positional_information') . '</caption>
                <tr><th>' . display('division') . '</th><td>' . $emp_details->department_name . '</td></tr>
                <tr><th>' . display('designation') . '</th><td>' . $emp_details->position_name . '</td></tr>
                <tr><th>' . display('duty_type') . '</th><td>' . ($emp_details->duty_type == 1 ? 'Full Time' : ($emp_details->duty_type == 2 ? 'Part Time' : ($emp_details->duty_type == 3 ? 'Contractual' : 'Other'))) . '</td></tr>
                <tr><th>Date of Employment</th><td>' . $emp_details->date_of_employment . '</td></tr>
                <tr><th>Date and Grade of Last Promotion</th><td>' . $emp_details->date_of_last_promotion . '</td></tr>
                <tr><th>' . display('rate_type') . '</th><td>' . ($emp_details->rate_type == 1 ? 'Hourly' : 'Salary') . '</td></tr>
                <tr><th>Appointment Confirmed</th><td>' . $emp_details->appointment_confirmed . '</td></tr>
                <tr><th>Qualification</th><td>' . $emp_details->qualification . '</td></tr>
                <tr><th>' . display('super_visor_name') . '</th><td>' . $emp_details->supervisor_name . '</td></tr>
                <tr><th>Ist Supervisor</th><td>' . ($emp_details->is_supervisor ? 'Yes' : 'No') . '</td></tr>
            </table>';

        // Prepare academic qualifications HTML
        $academic_html = '';
        foreach ($academic as $item) {
            if ($item->user_email == $emp_details->email){
            $academic_html .= '
                <tr>
                
                    <td><textarea class="form-control" readonly>' . $item->institution . '</textarea></td>
                    <td><input type="date" class="form-control" value="' . $item->duration_from . '" readonly></td>
                    <td><input type="date" class="form-control" value="' . $item->duration_to . '" readonly></td>
                    <td><textarea class="form-control" readonly>' . $item->qualification . '</textarea></td>
                </tr>';
        }
    }
        // Prepare professional qualifications HTML
        $professional_html = '';
        foreach ($professional as $item) {
            if ($item->user_email == $emp_details->email){
            $professional_html .= '
                <tr>
                    <td><textarea class="form-control" readonly>' . $item->qualification . '</textarea></td>
                    <td><textarea class="form-control" readonly>' . $item->awarding_body . '</textarea></td>
                    <td><input type="date" class="form-control" value="' . $item->date_of_award . '" readonly></td>
                </tr>';
        }
    }
        // Return data as JSON
        echo json_encode([
            'duties_id' => $employee_id,
            'emp_select_html' => $emp_select_html,
            'emp_details_html' => $emp_details_html,
            'academic_html' => $academic_html,
            'professional_html' => $professional_html
        ]);
    } else {
        echo json_encode(['error' => 'No employee selected']);
    }
}



    public function add_employee_performance()
    {
        // $this->permission->module('emp_performance','create')->redirect();
        $this->permission->check_label('emp_performance')->create()->access();

        // Get employee list from the model
         $employees = $this->Employees_model->employee();

       // Fetch user duties for each employee
        foreach ($employees as $key => $value) {
            $user_duties[$key] = $this->db->select('*')->from('user_emp_exp')->where('emp_per_id', $key)->get()->row();
        }

        $data['title'] = display('emp_performance');
        $data['employee'] = $employees;
        $data['module'] = "employee";
        $data['user_duties'] = $user_duties;
        $data['page'] = "emp_perform_appraisal/add_employee_performance";

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

    public function getduties() {
        // Retrieve the updated value (user ID) from POST data
        $updated_value = $_POST['updated_value'] ?? null;
    
        // Check if updated_value is provided
        if (!$updated_value) {
            echo 'No user ID provided';
            return;
        }
    
        // Fetch the duty for the specific employee using the updated_value
        $user_duty = $this->db->select('*')
                              ->from('user_emp_exp')
                              ->where('emp_per_id', $updated_value)
                              ->get()
                              ->row();
    
        // Check if the duty was found
        if ($user_duty) {
            // Decode the JSON data for key duties and responsibilities
            $key_duties_res_data = json_decode($user_duty->key_duties_res, true);
            $key_goals_data = json_decode($user_duty->key_goals, true);
            $teaching_experience = json_decode($user_duty->exp_teaching, true);
            $professional_experience = json_decode($user_duty->exp_professional, true);
            $research_experience = json_decode($user_duty->exp_research, true);
            $research_unpublish_experience = json_decode($user_duty->exp_research_unpublish, true);
    
            // Generate the HTML for the "Key Duties and Responsibilities" section
            $html = '
                        <div class="table-responsive">
                            <table class="table table-bordered" id="request_table_dev_plan">
                                <thead>
                                    <tr>
                            <th width="25%"><span id="junior1">DUTIES AND RESPONSIBILITES</span><span
                                    id="junior_1">SPECIAL CONTRIBUTIONS MADE TO ACTIVITIES</span></th>
                            <th width="25%"><span id="junior2">SPECIAL CONTRIBUTIONS MADE TO ACTIVITIES</span><span
                                    id="junior_2">IMPROVEMENT TO BE ON UNFAVOURABLE REPORT</span></th>
                            <th width="25%">CONDITION THAT FACILITATED YOUR PERFORMANCE</th>
                            <th width="25%">CONDITIONS THAT HINDERED ACHIEVING BETTER PERFORMANCE</th>


                        </tr>
                                </thead>
                                <tbody id="key_duties_res">';
    
            // Loop through the data and generate rows
            if (!empty($key_duties_res_data)) {
                foreach ($key_duties_res_data as $duty) {
                    $html .= '<tr>
                                <td>
                                    <textarea name="duties_responsibilites[]" class="form-control" readonly>' . htmlspecialchars($duty['duties_responsibilites']) . '</textarea>
                                </td>
                                <td>
                                    <textarea name="special_contributions[]" class="form-control" readonly>' . htmlspecialchars($duty['special_contributions']) . '</textarea>
                                </td>
                                <td>
                                    <textarea name="duties_perf_circumstances[]" class="form-control" readonly>' . htmlspecialchars($duty['duties_perf_circumstances']) . '</textarea>
                                </td>
                                <td>
                                    <textarea name="duties_perf_circumstances_bad[]" class="form-control" readonly>' . htmlspecialchars($duty['duties_perf_circumstances_bad']) . '</textarea>
                                </td>
                              </tr>';
                }
            } else {
                $html .= '<tr><td colspan="4">No duties and responsibilities found.</td></tr>';
            }
    
            $html .= '    </tbody>
                            </table>
                        </div>
                   ';
                   $html_mgt = '';

                   // Start generating HTML
                   $html_academic = '
                               <h3 class="mb-20">A: ASSESSMENT OF JOB PERFORMANCE</h3>
                               <h4>3.1 EXPERIENCE</h4>
                               <h4>(a) Teaching experience. (Please indicate institution, your designation, area of specification, subject(s) taught and dates)</h4>
                               <table class="table table-bordered">
                                   <thead>
                                       <tr>
                                           <th>INSTITUTION</th>
                                           <th>DESIGNATION</th>
                                           <th>AREA OF SPECIALIZATIONS</th>
                                           <th>SUBJECTS TAUGHT</th>
                                           <th>DATE</th>
                                       </tr>
                                   </thead>
                                   <tbody id="add_exp_teaching">';
           
                   // Teaching Experience
                   if (!empty($teaching_experience)) {
                       foreach ($teaching_experience as $index => $teaching) {
                           $html_academic .= '<tr>
                                       <td><textarea id="exp_institution_' . $index . '" name="exp_institutions[]" class="form-control" rows="1" readonly>' . htmlspecialchars($teaching['institution']) . '</textarea></td>
                                       <td><input type="text" id="exp_designation_' . $index . '" name="exp_designation[]" class="form-control" value="' . htmlspecialchars($teaching['designation']) . '" readonly></td>
                                       <td><input type="text" id="exp_specialization_' . $index . '" name="exp_specialization[]" class="form-control" value="' . htmlspecialchars($teaching['specialization']) . '" readonly></td>
                                       <td><input type="text" id="exp_subjects_' . $index . '" name="exp_subject[]" class="form-control" value="' . htmlspecialchars($teaching['subject']) . '" readonly></td>
                                       <td><input type="text" id="exp_date_' . $index . '" name="exp_date[]" class="form-control" value="' . htmlspecialchars($teaching['date']) . '" readonly></td>
                                     </tr>';
                       }
                   } else {
                       $html_academic .= '<tr><td colspan="5">No Teaching Experience Found.</td></tr>';
                   }
           
                   $html_academic .= '</tbody>
                           </table>';
           
                   // Professional Experience
                   $html_academic .= '<h4>(b) Professional Experience</h4>
                             <table class="table table-bordered">
                                 <thead>
                                     <tr>
                                         <th>EMPLOYER\'S NAME</th>
                                         <th>DESIGNATION</th>
                                         <th>NATURE OF DUTY</th>
                                         <th>FROM</th>
                                         <th>TO</th>
                                     </tr>
                                 </thead>
                                 <tbody id="exp_professional">';
           
                   if (!empty($professional_experience)) {
                       foreach ($professional_experience as $index => $professional) {
                           $html_academic .= '<tr>
                                       <td><textarea id="exp_institution_professional_' . $index . '" name="exp_institutions_professional[]" class="form-control" rows="1" readonly>' . htmlspecialchars($professional['institution']) . '</textarea></td>
                                       <td><input type="text" id="exp_designation_professional_' . $index . '" name="exp_designation_professional[]" class="form-control" value="' . htmlspecialchars($professional['designation']) . '" readonly></td>
                                       <td><textarea id="exp_duty_professional_' . $index . '" name="exp_duty_professional[]" class="form-control" rows="2" readonly>' . htmlspecialchars($professional['duty']) . '</textarea></td>
                                       <td><input type="text" id="exp_date_start_professional_' . $index . '" name="exp_date_start_professional[]" class="form-control" value="' . htmlspecialchars($professional['date_start']) . '" readonly></td>
                                       <td><input type="text" id="exp_date_end_professional_' . $index . '" name="exp_date_end_professional[]" class="form-control" value="' . htmlspecialchars($professional['date_end']) . '" readonly></td>
                                     </tr>';
                       }
                   } else {
                       $html_academic .= '<tr><td colspan="5">No Professional Experience Found.</td></tr>';
                   }
           
                   $html_academic .= '</tbody>
                           </table>';
           
                   // Research Description
                   $html_academic .= '<h4>3.2 RESEARCH/PROJECT/INVENTION/INNOVATION/DESIGNATION</h4>
                             <h4>(a) Brief Description (if any)</h4>
                             <table class="table table-bordered">
                                 <tr>
                                     <td><textarea id="exp_description" name="exp_description" class="form-control" rows="4" readonly>' . htmlspecialchars($user_duty->exp_description) . '</textarea></td>
                                 </tr>
                             </table>';
           
                   // Research Projects
                   $html_academic .= '<h4>(b) Research/Project/Innovation/Design completed but not yet published or patented</h4>
                             <table class="table table-bordered">
                                 <thead>
                                     <tr>
                                         <th style="text-align:center">TOPIC</th>
                                         <th style="text-align:center">DATE</th>
                                     </tr>
                                 </thead>
                                 <tbody id="exp_research">';
           
                   if (!empty($research_experience)) {
                       foreach ($research_experience as $index => $research) {
                           $html_academic .= '<tr>
                                       <td><textarea id="exp_researh_topic_' . $index . '" name="exp_researh_topic[]" class="form-control" rows="2" readonly>' . htmlspecialchars($research['topic']) . '</textarea></td>
                                       <td><input type="text" id="exp_researh_date_' . $index . '" name="exp_researh_date[]" class="form-control" value="' . htmlspecialchars($research['date']) . '" readonly></td>
                                     </tr>';
                       }
                   } else {
                       $html_academic .= '<tr><td colspan="2">No Research Projects Found.</td></tr>';
                   }
           
                   $html_academic .= '</tbody>
                           </table>';
           
                   // Recognised Publications
                   $html_academic .= '<h4>(c) RECOGNISED PUBLICATIONS/EXHIBITIONS/DESIGNS</h4>
                             <table class="table table-bordered">
                                 <tr>
                                     <td><textarea id="recognised_publications" name="recognised_publications" class="form-control" rows="4" readonly>' . htmlspecialchars($user_duty->recognized_publications) . '</textarea></td>
                                 </tr>
                             </table>';
           
                   // Unpublished Papers
                   $html_academic .= '<h4>3.3 Unpublished papers read at Conference (with names of conferences and date(s))</h4>
                             <table class="table table-bordered">
                                 <thead>
                                     <tr>
                                         <th style="text-align:center">TITLE</th>
                                         <th style="text-align:center">WHERE READ</th>
                                         <th style="text-align:center">DATE</th>
                                     </tr>
                                 </thead>
                                 <tbody id="exp_research_unpublish">';
           
                   if (!empty($research_unpublish_experience)) {
                       foreach ($research_unpublish_experience as $index => $unpublish) {
                           $html_academic .= '<tr>
                                       <td><textarea id="exp_unpublish_topic_' . $index . '" name="exp_unpublish_topic[]" class="form-control" rows="2" readonly>' . htmlspecialchars($unpublish['topic']) . '</textarea></td>
                                       <td><textarea id="exp_unpublish_read_' . $index . '" name="exp_unpublish_read[]" class="form-control" rows="2" readonly>' . htmlspecialchars($unpublish['read']) . '</textarea></td>
                                       <td><input type="text" id="exp_unpublish_date_' . $index . '" name="exp_unpublish_date[]" class="form-control" value="' . htmlspecialchars($unpublish['date']) . '" readonly></td>
                                     </tr>';
                       }
                   } else {
                       $html_academic .= '<tr><td colspan="3">No Unpublished Papers Found.</td></tr>';
                   }
           
                   $html_academic .= '</tbody>
                           </table>';
           
                   // Other Activities Within the Institute
                   $html_academic .= '</tbody>
                        </table>
                        <h4>3.4 Other activities within the institute</h4>
                        <table class="table table-bordered">
                            <tr>
                                <td><textarea name="exp_other_activities" class="form-control" rows="4" placeholder="Maximum 500 words" readonly>' . htmlspecialchars($user_duties->exp_other_activities) . '</textarea></td>
                            </tr>
                        </table>
                        <h4>3.5 Other relevant activities outside normal institute work</h4>
                        <table class="table table-bordered">
                            <tr>
                                <td><textarea name="exp_other_activities_out" class="form-control" rows="4" placeholder="Maximum 500 words" readonly>' . htmlspecialchars($user_duties->exp_other_activities_out) . '</textarea></td>
                            </tr>
                        </table>';

                        $html_non_academic = '
                        <h3 class="mb-20">A: ASSESSMENT OF JOB PERFORMANCE</h3>
                        <table class="table table-bordered" id="request_table">
                            <thead>
                                <tr>
                                    <th>RESPONSIBILITIES: TASK AND TARGET</th>
                                    <th>GENERAL ASSESSMENT</th>
                                </tr>
                                <tr>
                                    <td><b>Briefly List the major responsibilities, in order of importance for each responsibility. Note specific goals set during period under review<b></td>
                                    <td><b>Rating the employee on each task and target by commenting the grade that most accurately describe your rating.<br><br> Rating Criteria: POOR, FAIR, GOOD, VERY GOOD, EXCELLENT</b></td>
                                </tr>
                            </thead>
                            <tbody id="key_goals_item">';
    
            // Loop through the data and generate rows
            if (!empty($key_goals_data)) {
                foreach ($key_goals_data as $index => $goal) {
                    $html_non_academic .= '<tr>
                                <td><textarea id="key_goals" name="key_goals[]" class="form-control" rows="2" readonly>' . htmlspecialchars($goal['key_goals']) . '</textarea></td>
                                <td>
                                <select id="rating_' . $index . '" name="rating[]" class="form-control rating"
                                    aria-describedby="basic-addon1" onchange="displaySelectedValue(this)">
                                    <option value="" disabled selected>Select Rating</option>
                                    <option value="1">POOR</option>
                                    <option value="2">FAIR</option>
                                    <option value="3">GOOD</option>
                                    <option value="4">VERY GOOD</option>
                                    <option value="5">EXCELLENT</option>
                                </select>
                            </td>
                                
                                 <td>
                                <span>Score: </span> <input type="text" id="valueDisplay_' . $index . '" name="key_goals_score[]"
                                    style="border:0px; width: 45px;" value="" readonly></input>
                            </td>
                              </tr>';
                }
            } else {
                $html_non_academic .= '<tr><td colspan="2">No key goals found.</td></tr>';
            }
    
            $html_non_academic .= '</tbody>
                        <tfoot>
                            <tr>
                                <td colspan="2" class="text-right"><strong>Total Score:</strong></td>
                                <td><input class="fw-700" style="border:0px; width: 45px;" id="totalScore" name="totalScore" value="" readonly><b>%</b></td>
                            </tr>
                        </tfoot>
                    </table>
                ';
    
                      
            //Output the generated HTML

            echo json_encode([
                'preliminary' => $html,
                'academic'  => $html_academic,
                'non_academic' => $html_non_academic,
                'management_staff'=>$html_mgt
                
            ]);
           // echo $html;
            
        } else {
            echo 'No duty found for the provided user ID';
        }
        
        
    }
    
    

    public function save_employee_performance()
    {

        $this->permission->check_label('emp_performance')->create()->access();

        $data['title'] = display('emp_performance');
        #-------------------------------#
        $this->form_validation->set_rules('employee_id', display('employee_name'), 'required');
        $this->form_validation->set_rules('review_period', display('review_period'), 'required');
        //$this->form_validation->set_rules('calculatedScore', display('calculatedScore'));
        $this->form_validation->set_rules('employee_growth', display('employee_growth'));
        $this->form_validation->set_rules('employee_comments', display('employee_comments'), 'max_length[500]');
        $this->form_validation->set_rules('growth_comments', display('growth_comments'), 'max_length[500]');
        $this->form_validation->set_rules('staff_status', display('staff_status'));
        #-------------------------------#
        if ($this->form_validation->run() === true) {

            $id = $this->input->post('employee_id', true);

            $get_emp_name_and_email = $this->Employee_performance_model->employee_performance_email_and_name_by_id($id);
            $emp_first_name = $get_emp_name_and_email->first_name;
            $emp_last_name = $get_emp_name_and_email->last_name;
            $emp_email = $get_emp_name_and_email->email;

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

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

            $exp_description = $this->input->post('exp_description', true);

            $topics_research = $this->input->post('exp_researh_topic');
            $dates_research = $this->input->post('exp_researh_date');

            $topics_unpublish = $this->input->post('exp_unpublish_topic');
            $reads_unpublish = $this->input->post('exp_unpublish_read');
            $dates_unpublish = $this->input->post('exp_unpublish_date');

            $recognized_publications = $this->input->post('recognised_publications');

            $exp_other_activities = $this->input->post('exp_other_activities');
            $exp_other_activities_out = $this->input->post('exp_other_activities_out');
            $exp_general_remarks = $this->input->post('exp_general_remarks', true);
            $exp_serve_date_start = $this->input->post('exp_serve_date_start', true);
            $exp_serve_date_end = $this->input->post('exp_serve_date_end', true);

            $key_goals = $this->input->post('key_goals', true);
            $rating = $this->input->post('rating', true);
            $key_goals_score = $this->input->post('key_goals_score', true);
            $key_total_goals_score = $this->input->post('key_total_goals_score', true);

            $key_duties_res = $this->input->post('duties_responsibilites', true);
            $special_contributions = $this->input->post('special_contributions', true);
            $duties_perf_circumstances = $this->input->post('duties_perf_circumstances', true);
            $duties_perf_circumstances_bad = $this->input->post('duties_perf_circumstances_bad',true);

            $assesment_c_score = (int) $this->input->post('assesment_c_total_score', true);

            $major_strenght = $this->input->post('major_strength', true);
            $major_strenght_effect = $this->input->post('major_strenght_effect', true);

            $major_weakness = $this->input->post('major_weakness', true);
            $major_weakness_correction = $this->input->post('major_weakness_correction', true);

            $demonstrated_score = (int) $this->input->post('demonstrated_score', true);
            $timeliness_score = (int) $this->input->post('timeliness_score', true);
            $impact_score = (int) $this->input->post('impact_score', true);
            $overall_score = (int) $this->input->post('overall_score', true);
            $beyond_duty = (int) $this->input->post('beyond_duty', true);

            $interpersonal = (int) $this->input->post('interpersonal_score', true);
            $attendance = (int) $this->input->post('attendance_score', true);
            $work_relationship = (int) $this->input->post('work_relationship', true);
            $communication = (int) $this->input->post('communication_score', true);
            $contributing = (int) $this->input->post('contributing_score', true);
            $problem_solving = (int) $this->input->post('problem_solving_score', true);
            $decision_making = (int) $this->input->post('decision_making_score', true);
            $managerial_potentials = (int) $this->input->post('managerial_potentials_score', true);

			$mgt_leadership = (int) $this->input->post('leadership', true);
			$mgt_leadership1 =  $this->input->post('leadership_build', true);

			$mgt_decision1 = (int) $this->input->post('decision_making_cap1', true);
			$mgt_decision2 = (int) $this->input->post('decision_making_cap2', true);
			$mgt_decision3 = (int) $this->input->post('decision_making_cap3', true);
			$mgt_decision4 = $this->input->post('decision_making_cap1', true);

			$mgt_management1 = (int) $this->input->post('management_com1', true);
			$mgt_management2 = (int) $this->input->post('management_com2', true);
			$mgt_management3 = (int) $this->input->post('management_com3', true);
			$mgt_management4 =  $this->input->post('management_com4', true);

			$functional1 = (int) $this->input->post('functional1', true);
			$functional2 = (int) $this->input->post('functional2', true);
			$functional3 = (int) $this->input->post('functional3', true);
			$functional4 =  $this->input->post('functional4', true);

            $overall_evaluation = (int) $this->input->post('overall_evaluation', true);
            $growth_evaluation = $this->input->post('employee_growth', true);

            $recommand_areas = $this->input->post('recommand_areas', true);
            $expected_outcomes = $this->input->post('expected_outcomes', true);
            $responsible_person = $this->input->post('responsible_person', true);
            $start_date = $this->input->post('start_date', true);
            $end_date = $this->input->post('end_date', true);
           
            $promotion = $this->input->post('promotion', true);
            $reward_promotion = $this->input->post('reward_promotion', true);
            $reward_salary = $this->input->post('reward_salary', true);
            $merit_award = $this->input->post('merit_award', true);
            $reward_amount_merit = $this->input->post('reward_amount_merit', true);
            $reward_citation = $this->input->post('reward_citation', true);
            $annual_increment = $this->input->post('annual_increment', true);  // Missing true parameter added
            $reward_amount_annual = $this->input->post('reward_amount_annual', true);
            $other_increment = $this->input->post('other_increment', true);
            $reward_sprcify = $this->input->post('reward_sprcify', true);
            $redeployment = $this->input->post('redeployment', true);
            $reward_job = $this->input->post('reward_job', true);
            $disciplinary_action = $this->input->post('disciplinary_action', true);
            $reward_dept = $this->input->post('reward_dept', true);
            $reward_specify = $this->input->post('reward_specify', true); 
            $reward_comments = $this->input->post('reward_comments', true);

            $assesment_d_score = (int) $this->input->post('assesment_d_total_score', true);
           
            $assesment_b_score = (int) $this->input->post('assesment_b_total_score', true);
            $assesment_a_score = (int) $this->input->post('assesment_a_total_score', true);

          
            $calculatedScore = (int) $this->input->post('calculatedScore', true);

            $signingOfficerName = $this->input->post('signingOfficerName', true);
            $signingOfficerSignature = $this->input->post('signingOfficerSignature', true);
            $signingOfficerDate = $this->input->post('signingOfficerDate', true);
            $signingOfficerDesignation = $this->input->post('signingOfficerDesignation', true);
            $signingOfficerNRDate = $this->input->post('signingOfficerNRDate', true);
            $signingOfficeremail = $this->input->post('signingOfficeremail', true);
            

            $counterOfficerName = $this->input->post('counterOfficerName', true);
            $counterOfficerSignature = $this->input->post('counterOfficerSignature', true);
            $counterOfficerDate = $this->input->post('counterOfficerDate', true);
            $counterOfficerDesignation = $this->input->post('counterOfficerDesignation', true);
            $counterOfficerNRDate = $this->input->post('counterOfficerNRDate', true);
            
            $postData = [
                'employee_id' => $this->input->post('employee_id', true),
                'review_period' => $this->input->post('review_period', true),
                'position_of_supervisor' => $this->input->post('position_of_supervisor', true),
                'employee_growth' => $this->input->post('employee_growth', true),
                'employee_comments' => $this->input->post('employee_comments', true),
                'growth_comments' => $this->input->post('growth_comments', true),
                'status' => $this->input->post('staff_status', true),
                 
            ];

            $postData['date'] = date('Y-m-d');
            $postData['create_date'] = date('Y-m-d');
            $postData['create_by'] = $this->session->userdata('id');
            // Performance Serial key generate
            $time = strtotime("now");
            $postData['perform_sl'] = 'SL' . $time . rand(0, 1000) . $this->input->post('employee_id', true);


            $emp_per_id = $this->Employee_performance_model->create_emp_paerformance($postData);


            if ($emp_per_id) {


                //Academic Evaluation
                $postData_aacademic = array();

                $postData_aacademic[] = [
                    'quality_teaching' => (int) $this->input->post('quality_teaching', true),
                    'quality_teaching_score' => (int) $this->input->post('quality_teaching_score', true),
                    'current_research' => (int) $this->input->post('current_research', true),
                    'current_research_score' => (int) $this->input->post('current_research_score', true),
                    'quality_research' => (int) $this->input->post('quality_research', true),
                    'quality_research_score' => (int) $this->input->post('quality_research_score', true),
                    'quality_publication' => (int) $this->input->post('quality_publication', true),
                    'quality_publication_score' => (int) $this->input->post('quality_publication_score', true),
                    'department_responsibilities' => (int) $this->input->post('department_responsibilities', true),
                    'department_responsibilities_score' => (int) $this->input->post('department_responsibilities_score', true),
                    'contribution' => (int) $this->input->post('contribution', true),
                    'contribution_score' => (int) $this->input->post('contribution_score', true),
                    'relationship_colleagues' => (int) $this->input->post('relationship_colleagues', true),
                    'relationship_colleagues_score' => (int) $this->input->post('relationship_colleagues_score', true),
                    'acceptance_responsibility' => (int) $this->input->post('acceptance_responsibility', true),
                    'acceptance_responsibility_score' => (int) $this->input->post('acceptance_responsibility_score', true),
                    'management_staff' => (int) $this->input->post('management_staff', true),
                    'management_staff_score' => (int) $this->input->post('management_staff_score', true),
                    'punctuality' => (int) $this->input->post('punctuality', true),
                    'punctuality_score' => (int) $this->input->post('punctuality_score', true),
                    'appearance' => (int) $this->input->post('appearance', true),
                    'appearance_score' => (int) $this->input->post('appearance_score', true),
                ];
                $postData_aacademic_json = json_encode($postData_aacademic);

                $postData_academic = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 5,
                    'academic_evaluation' => $postData_aacademic_json,
                    'exp_signature' => $this->input->post('exp_signature', true),
                    'exp_signature_date' => $this->input->post('exp_signature_date', true),
                ];
                $this->db->insert('gmb_emp_academic',$postData_academic);

                //Insert data for QUALITY
                $postData_quality = [
					'emp_per_id'                => $emp_per_id,
					'emp_perform_type_id'       => 3,
					'emp_perform_criteria_id'   => 13,
					'emp_perform_eval'          => (int)$this->input->post('quality', true),
					'score'                     => (int)$this->input->post('quality_score', true),
					'comments'                  => $this->input->post('quality_comments', true),
				];

				$this->db->insert('gmb_emp_evaluation_values', $postData_quality);


                // Insert data for WORK OUTPUT
                $postData_work_output = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 3,
                    'emp_perform_criteria_id' => 14,
                    'emp_perform_eval' => (int) $this->input->post('work_output', true),
                    'score' => (int) $this->input->post('work_output_score', true),
                    'comments' => $this->input->post('work_output_comments', true),
                ];
                $this->db->insert('gmb_emp_evaluation_values', $postData_work_output);

				// Insert data for DEPENDABILITY
                $postData_dependability = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 3,
                    'emp_perform_criteria_id' => 15,
                    'emp_perform_eval' => (int) $this->input->post('dependability', true),
                    'score' => (int) $this->input->post('dependability_score', true),
                    'comments' => $this->input->post('dependability_comments', true),
                ];
                $this->db->insert('gmb_emp_evaluation_values', $postData_dependability);

				// Insert data for JOB ATTITUDE
                $postData_job_attitude = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 3,
                    'emp_perform_criteria_id' => 16,
                    'emp_perform_eval' => (int) $this->input->post('job_attitude', true),
                    'score' => (int) $this->input->post('job_attitude_score', true),
                    'comments' => $this->input->post('job_attitude_comments', true),
                ];
                $this->db->insert('gmb_emp_evaluation_values', $postData_job_attitude);

				// Insert data for ADAPTABILITY
                $postData_adaptability = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 3,
                    'emp_perform_criteria_id' => 17,
                    'emp_perform_eval' => (int) $this->input->post('adaptability', true),
                    'score' => (int) $this->input->post('adaptability_score', true),
                    'comments' => $this->input->post('adaptability_comments', true),
                ];
                $this->db->insert('gmb_emp_evaluation_values', $postData_adaptability);

				// Insert data for JOB KNOWLEDGE
                $postData_job_knowledge = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 3,
                    'emp_perform_criteria_id' => 18,
                    'emp_perform_eval' => (int) $this->input->post('job_knowledge', true),
                    'score' => (int) $this->input->post('job_knowledge_score', true),
                    'comments' => $this->input->post('job_knowledge_comments', true),
                ];
                $this->db->insert('gmb_emp_evaluation_values', $postData_job_knowledge);

				// Insert data for ATTENDANCE
                $postData_attendance = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 3,
                    'emp_perform_criteria_id' => 19,
                    'emp_perform_eval' => (int) $this->input->post('attendance', true),
                    'score' => (int) $this->input->post('attendance_score', true),
                    'comments' => $this->input->post('attendance_comments', true),
                ];
                $this->db->insert('gmb_emp_evaluation_values', $postData_attendance);

				// Insert data for PHYSICAL FITNESS
                $postData_physical_fitness = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 3,
                    'emp_perform_criteria_id' => 20,
                    'emp_perform_eval' => (int) $this->input->post('physical_fitness', true),
                    'score' => (int) $this->input->post('physical_fitness_score', true),
                    'comments' => $this->input->post('physical_fitness_comments', true),
                ];
                $this->db->insert('gmb_emp_evaluation_values', $postData_physical_fitness);

				// Insert data for COOPERATIVENESS
                $postData_cooperativeness = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 3,
                    'emp_perform_criteria_id' => 21,
                    'emp_perform_eval' => (int) $this->input->post('cooperativeness', true),
                    'score' => (int) $this->input->post('cooperativeness_score', true),
                    'comments' => $this->input->post('cooperativeness_comments', true),
                ];
                $this->db->insert('gmb_emp_evaluation_values', $postData_cooperativeness);

				// Insert data for LEARNING CAPACITY
                $postData_learning_capacity = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 3,
                    'emp_perform_criteria_id' => 22,
                    'emp_perform_eval' => (int) $this->input->post('learning_capacity', true),
                    'score' => (int) $this->input->post('learning_capacity_score', true),
                    'comments' => $this->input->post('learning_capacity_comments', true),
                ];
                $this->db->insert('gmb_emp_evaluation_values', $postData_learning_capacity);


                

                /*Assesment_a data*/
                $postData_a_demonstrated = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 1,
                    'emp_perform_criteria_id' => 1,
                    'emp_perform_eval' => (int) $this->input->post('demonstrated', true),
                    'score' => (int) $this->input->post('demonstrated_score', true),
                    'comments' => $this->input->post('demonstrated_comments', true),
                ];
                $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                $postData_a_demonstrated = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 1,
                    'emp_perform_criteria_id' => 2,
                    'emp_perform_eval' => (int) $this->input->post('timeliness', true),
                    'score' => (int) $this->input->post('timeliness_score', true),
                    'comments' => $this->input->post('timeliness_score_commnets', true),
                ];
                $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                $postData_a_demonstrated = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 1,
                    'emp_perform_criteria_id' => 3,
                    'emp_perform_eval' => (int) $this->input->post('impact', true),
                    'score' => (int) $this->input->post('impact_score', true),
                    'comments' => $this->input->post('impact_score_commnets', true),
                ];
                $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                $postData_a_demonstrated = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 1,
                    'emp_perform_criteria_id' => 4,
                    'emp_perform_eval' => (int) $this->input->post('overall', true),
                    'score' => (int) $this->input->post('overall_score', true),
                    'comments' => $this->input->post('overall_score_commnets', true),
                ];
                $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                $postData_a_demonstrated = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 1,
                    'emp_perform_criteria_id' => 5,
                    'emp_perform_eval' => (int) $this->input->post('beyond_duty', true),
                    'score' => (int) $this->input->post('beyond_duty', true),
                    'comments' => $this->input->post('beyond_duty_commnets', true),
                ];
                $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                /*Assesment_b data*/
                $postData_a_demonstrated = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 2,
                    'emp_perform_criteria_id' => 6,
                    'emp_perform_eval' => (int) $this->input->post('interpersonal', true),
                    'score' => (int) $this->input->post('interpersonal_score', true),
                    'comments' => $this->input->post('interpersonal_commnets', true),
                ];
                $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                $postData_a_demonstrated = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 2,
                    'emp_perform_criteria_id' => 7,
                    'emp_perform_eval' => (int) $this->input->post('work_relationship', true),
                    'score' => (int) $this->input->post('work_relationship_score', true),
                    'comments' => $this->input->post('work_relationship_commnets', true),
                ];
                $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                $postData_a_demonstrated = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 2,
                    'emp_perform_criteria_id' => 8,
                    'emp_perform_eval' => (int) $this->input->post('communication', true),
                    'score' => (int) $this->input->post('communication_score', true),
                    'comments' => $this->input->post('communication_commnets', true),
                ];
                $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                $postData_a_demonstrated = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 2,
                    'emp_perform_criteria_id' => 9,
                    'emp_perform_eval' => (int) $this->input->post('contributing', true),
                    'score' => (int) $this->input->post('contributing_score', true),
                    'comments' => $this->input->post('contributing_commnets', true),
                ];
                $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                $postData_problem_solving = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 2,
                    'emp_perform_criteria_id' => 10,
                    'emp_perform_eval' => (int) $this->input->post('problem_solving', true),
                    'score' => (int) $this->input->post('problem_solving_score', true),
                    'comments' => $this->input->post('problem_solving_comments', true),
                ];
                $this->db->insert('gmb_emp_perform_values', $postData_problem_solving);

                $postData_decision_making = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 2,
                    'emp_perform_criteria_id' => 11,
                    'emp_perform_eval' => (int) $this->input->post('decision_making', true),
                    'score' => (int) $this->input->post('decision_making_score', true),
                    'comments' => $this->input->post('decision_making_comments', true),
                ];
                $this->db->insert('gmb_emp_perform_values', $postData_decision_making);

                $postData_managerial_potentials = [
                    'emp_per_id' => $emp_per_id,
                    'emp_perform_type_id' => 2,
                    'emp_perform_criteria_id' => 12,
                    'emp_perform_eval' => (int) $this->input->post('managerial_potentials', true),
                    'score' => (int) $this->input->post('managerial_potentials_score', true),
                    'comments' => $this->input->post('managerial_potentials_comments', true),
                ];
                $this->db->insert('gmb_emp_perform_values', $postData_managerial_potentials);

                  
				

				//Management Evaluation Form
				$postData_mgt_leadership[] = [
					'emp_perform_type_id' => 4,
					'leadership' =>  $this->input->post('leadership', true),
					'leadership_score' =>  $this->input->post('leadership_score', true),
					'leadership_comments' => $this->input->post('leadership_commnets', true),
					'leadership1' => $this->input->post('leadership_build', true),
				

				];
				
				$postData_mgt_management[] = [
					'emp_perform_type_id' => 4,
					'mgt_management1' =>  $this->input->post('management_com1', true),
					'mgt_management1_score' =>  $this->input->post('management_com1_score', true),
					'mgt_management1_comments' => $this->input->post('management_com1_commnets', true),
					'mgt_management2' =>  $this->input->post('management_com2', true),
					'mgt_management2_score' =>  $this->input->post('management_com2_score', true),
					'mgt_management2_comments' => $this->input->post('management_com2_commnets', true),
					'mgt_management3' =>  $this->input->post('management_com3', true),
					'mgt_management3_score' =>  $this->input->post('management_com3_score', true),
					'mgt_management3_comments' => $this->input->post('management_com3_commnets', true),
					'mgt_management4' =>  $this->input->post('management_com4', true),
					
				];

				$postData_mgt_decision[] = [
					'emp_perform_type_id' => 4,
					'mgt_descision1' =>  $this->input->post('decision_making_cap1', true),
					'mgt_descision1_score' =>  $this->input->post('decision_making_cap1_score', true),
					'mgt_descision1_comments' => $this->input->post('decision_making_cap1_commnets', true),
					'mgt_descision2' =>  $this->input->post('decision_making_cap2', true),
					'mgt_descision2_score' =>  $this->input->post('decision_making_cap2_score', true),
					'mgt_descision2_comments' => $this->input->post('decision_making_cap2_commnets', true),
					'mgt_descision3' =>  $this->input->post('decision_making_cap3', true),
					'mgt_descision3_score' =>  $this->input->post('decision_making_cap3_score', true),
					'mgt_descision3_comments' => $this->input->post('decision_making_cap3_commnets', true),
					'mgt_descision4' => $this->input->post('decision_making_cap4', true),
					
				];
				
				$postData_mgt_functional[] = [
					'emp_perform_type_id' => 4,
					'mgt_functional1' =>  $this->input->post('functional1', true),
					'mgt_functional1_score' => $this->input->post('functional1_score', true),
					'mgt_functional1_comments' => $this->input->post('functional1_commnets', true),
					'mgt_functional2' => $this->input->post('functional2', true),
					'mgt_functional2_score' => $this->input->post('functional2_score', true),
					'mgt_functional2_comments' => $this->input->post('functional2_commnets', true),
					'mgt_functional3' =>  $this->input->post('functional3', true),
					'mgt_functional3_score' => $this->input->post('functional3_score', true),
					'mgt_functional3_comments' => $this->input->post('functional3_commnets', true),
					'mgt_functional4' =>  $this->input->post('functional4', true),
					
				];
				
				  // Convert array to JSON string
				  $mgt_leadership_json = json_encode($postData_mgt_leadership);
				  $mgt_decision_json = json_encode($postData_mgt_decision);
				  $mgt_management_json = json_encode($postData_mgt_management);
				  $mgt_functional_json = json_encode($postData_mgt_functional);
  
				  // Initialize employee management data array
				  $mgt_data = [
					  'emp_per_id' => $emp_per_id,
					  'emp_perform_type_id' => 4,
					  'leadership_mgt' => $mgt_leadership_json,
					  'decision_mgt' => $mgt_decision_json,
					  'comptence_mgt' => $mgt_management_json,
					  'functional_mgt' => $mgt_functional_json,
					 
				  ];
  
				  // Insert data into MGT database
				
				 $this->db->insert('gmb_emp_mgt_values', $mgt_data);
				  

                
              
                //  Senior JOB Assessment
                // Initialize teaching experience array outside the loop
                $teaching_experience = array();
                $professional_experience = array();
                $research_experience = array();
                $research_unpublish_experience = array();

                // Loop through each set of form data
                for ($i = 0; $i < count($institutions); $i++) {
                    // Add form data to teaching experience array
                    $teaching_experience[] = array(
                        'institution' => $institutions[$i],
                        'designation' => $designations[$i],
                        'specialization' => $specializations[$i],
                        'subject' => $subjects[$i],
                        'date' => $dates[$i],
                    );
                }

                // Combine exp_professional form data into an array
                for ($i = 0; $i < count($institutions_prof); $i++) {
                    $institutions_proff = isset($institutions_prof[$i]) ? $institutions_prof[$i] : '';
                    $designations_proff = isset($designations_prof[$i]) ? $designations_prof[$i] : '';
                    $duty = isset($duties_prof[$i]) ? $duties_prof[$i] : '';
                    //$subject = isset($subjects_prof[$i]) ? $subjects_prof[$i] : '';
                    $dates_start_proff = isset($dates_start_prof[$i]) ? $dates_start_prof[$i] : '';
                    $date_end_proff = isset($dates_end_prof[$i]) ? $dates_end_prof[$i] : '';

                    $professional_experience[] = array(
                        'institution' => $institutions_proff,
                        'designation' => $designations_proff,
                        'duty' => $duty,
                        //'subject' => $subject,
                        'date_start' => $dates_start_proff,
                        'date_end' => $date_end_proff,
                    );
                }

                // Combine exp_research form data into an array
                for ($i = 0; $i < count($topics_research); $i++) {
                    $topic_res = isset($topics_research[$i]) ? $topics_research[$i] : '';
                    $date_res = isset($dates_research[$i]) ? $dates_research[$i] : '';

                    $research_experience[] = array(
                        'topic' => $topic_res,
                        'date' => $date_res,
                    );
                }

                // Combine exp_professional form data into an array
                for ($i = 0; $i < count($topics_unpublish); $i++) {
                    $topic_un = isset($topics_unpublish[$i]) ? $topics_unpublish[$i] : '';
                    $read_un = isset($reads_unpublish[$i]) ? $reads_unpublish[$i] : '';
                    $date_un = isset($dates_unpublish[$i]) ? $dates_unpublish[$i] : '';

                    $research_unpublish_experience[] = array(
                        'topic' => $topic_un,
                        'read' => $read_un,
                        'date' => $date_un,
                    );
                }

                // Convert array to JSON string
                $professional_experience_json = json_encode($professional_experience);
                $teaching_experience_json = json_encode($teaching_experience);
                $research_experience_json = json_encode($research_experience);
                $research_unpublish_experience_json = json_encode($research_unpublish_experience);

                // Initialize employee experience data array
                $emp_exp_data = [
                    'emp_per_id' => $emp_per_id,
                    'exp_teaching' => $teaching_experience_json,
                    'exp_professional' => $professional_experience_json,
                    'exp_description' => $exp_description,
                    'exp_research' => $research_experience_json,
                    'recognized_publications' => $recognized_publications,
                    'exp_research_unpublish' => $research_unpublish_experience_json,
                    'exp_other_activities' => $exp_other_activities,
                    'exp_other_activities_out' => $exp_other_activities_out,
                    'exp_general_remarks' => $exp_general_remarks,
                    'exp_serve_date_start' => $exp_serve_date_start,
                    'exp_serve_date_end'=> $exp_serve_date_end
                ];

                // Insert data into database if institutions array is not empty
                // if (!empty($institutions)) {
                    $this->db->insert('gmb_emp_exp', $emp_exp_data);
                // }

                //[{}]
                //
            //Assessment


            $perform_key_scores =[
            'emp_per_id' => (isset($emp_per_id) && !empty($emp_per_id)) ? $emp_per_id : null,
            'employee_id' => $this->input->post('employee_id', true),
            'key_total_goals_score' =>  (isset($key_total_goals_score) && !empty($key_total_goals_score)) ? $key_total_goals_score : 0,
            'employee_growth' => (isset($employee_growth) && !empty($employee_growth)) ? $employee_growth :1,
            'overall_evaluation' => (isset($overall_evaluation) && !empty($overall_evaluation)) ? $overall_evaluation :1,
            'scores_a' => (isset($assesment_a_score) && !empty($assesment_a_score)) ? $assesment_a_score : 0,
            'scores_b' => (isset($assesment_b_score) && !empty($assesment_b_score)) ? $assesment_b_score : 0,
            'scores_c' => (isset($assesment_c_score) && !empty($assesment_c_score)) ? $assesment_c_score : 0,
            'scores_d' => (isset($assesment_d_score) && !empty($assesment_d_score)) ? $assesment_d_score : 0,
            'total_scores' => (isset($calculatedScore) && !empty($calculatedScore)) ? $calculatedScore : null,
           ];

           $this->db->insert('gmb_perform_key_scores',  $perform_key_scores); 

                // Insert F. KEY GOALS FOR NEXT REVIEW PERIOD
                $key_goals_data = array();
                $major_strenght_data = array();
                $major_weakness_data = array();
                $key_duties_res_data = array();
                
                for ($j = 0; $j < count($key_duties_res); $j++) {
                    $key_duties_res_data[] = [
                        'duties_responsibilites' =>  $key_duties_res[$j],
                        'special_contributions' =>  (isset($special_contributions[$j]) && !empty($special_contributions[$j])) ? $special_contributions[$j] : null,
                        'duties_perf_circumstances' =>  (isset($duties_perf_circumstances[$j]) && !empty($duties_perf_circumstances[$j])) ? $duties_perf_circumstances[$j] : null,
                        'duties_perf_circumstances_bad' => (isset($duties_perf_circumstances_bad[$j]) && !empty($duties_perf_circumstances_bad[$j])) ? $duties_perf_circumstances_bad[$j] : null,
                    ];
                }
                
                for ($i = 0; $i < count($key_goals); $i++) {
                    $key_goals_data[] = [
                        'key_goals' => $key_goals[$i],
                        'rating' => (isset($rating[$i]) && !empty($rating[$i])) ? $rating[$i] : null,
                        'key_goals_score' => (isset($key_goals_score[$i]) && !empty($key_goals_score[$i])) ? $key_goals_score[$i] : null,
                    ];
                }
                
                for ($i = 0; $i < count($major_strenght); $i++) {
                    $major_strenght_data[] = [
                        'major_strenght' => $major_strenght[$i],
                        'major_strenght_effect' => (isset($major_strenght_effect[$i]) && !empty($major_strenght_effect[$i])) ? $major_strenght_effect[$i] : null,
                    ];
                }
                
                for ($i = 0; $i < count($major_weakness); $i++) {
                    $major_weakness_data[] = [
                        'major_weakness' => $major_weakness[$i],
                        'major_weakness_correction' => (isset($major_weakness_correction[$i]) && !empty($major_weakness_correction[$i])) ? $major_weakness_correction[$i] : null,
                    ];
                }
                
                $key_duties_res_data_json = json_encode($key_duties_res_data);
                $key_goals_data_json = json_encode($key_goals_data);
                $major_strenght_data_json = json_encode($major_strenght_data);
                $major_weakness_data_json = json_encode($major_weakness_data);
                
                $perf_key_data = [
                    'emp_per_id' => $emp_per_id,
                    'key_goals' => $key_goals_data_json,
                    'major_strength' => $major_strenght_data_json,
                    'major_weakness' => $major_weakness_data_json,
                    'key_duties_res' => $key_duties_res_data_json
                ];
                
                $this->db->insert('gmb_perform_key_goals_mod', $perf_key_data);
                
                  // Insert E.Training DEVELOPMENT PLAN data into database
                  for ($i = 0; $i < count($recommand_areas); $i++) {
                    $development_plan = [
                        'recommand_areas' => $recommand_areas[$i],
                        'expected_outcomes' => isset($expected_outcomes[$i]) ? $expected_outcomes[$i] : '',
                        'responsible_person' => isset($responsible_person[$i]) ? $responsible_person[$i] : '',
                        'start_date' => (isset($start_date[$i]) && !empty($start_date[$i])) ? $start_date[$i] : null,
                        'end_date' => (isset($end_date[$i]) && !empty($end_date[$i])) ? $end_date[$i] : null,
                        'emp_per_id' => $emp_per_id,
                    ];
                    if (!empty($recommand_areas[$i])) {
                        $this->db->insert('gmb_perform_development_plan', $development_plan);
                    }
                }

                
                    $rewardData = [
                        'emp_per_id' => (isset($emp_per_id) && !empty($emp_per_id)) ? $emp_per_id : null,
                        'promotion' => (isset($promotion) && !empty($promotion)) ? $promotion : null,
                        'reward_promotion' => (isset($reward_promotion) && !empty($reward_promotion)) ? $reward_promotion : null,
                        'reward_salary' => (isset($reward_salary) && !empty($reward_salary)) ? $reward_salary : null,
                        'merit_award' => (isset($merit_award) && !empty($merit_award)) ? $merit_award : null,
                        'reward_amount_merit' => (isset($reward_amount_merit) && !empty($reward_amount_merit)) ? $reward_amount_merit : null,
                        'reward_citation' => (isset($reward_citation) && !empty($reward_citation)) ? $reward_citation : null,
                        'annual_increment' => (isset($annual_increment) && !empty($annual_increment)) ? $annual_increment : null,
                        'reward_amount_annual' => (isset($reward_amount_annual) && !empty($reward_amount_annual)) ? $reward_amount_annual : null,
                        'other_increment' => (isset($other_increment) && !empty($other_increment)) ? $other_increment : null,
                        'reward_sprcify' => (isset($reward_sprcify) && !empty($reward_sprcify)) ? $reward_sprcify : null,  // Assuming typo, should be reward_specify
                        'redeployment' => (isset($redeployment) && !empty($redeployment)) ? $redeployment : null,
                        'reward_job' => (isset($reward_job) && !empty($reward_job)) ? $reward_job : null,
                        'disciplinary_action' => (isset($disciplinary_action) && !empty($disciplinary_action)) ? $disciplinary_action : null,
                        'reward_dept' => (isset($reward_dept) && !empty($reward_dept)) ? $reward_dept : null,
                        'reward_specify' => (isset($reward_specify) && !empty($reward_specify)) ? $reward_specify : null,
                        'reward_comments' => (isset($reward_comments) && !empty($reward_comments)) ? $reward_comments : null,
                    ];
                    $this->db->insert('gmp_emp_reward', $rewardData);

                   $signingOfficer = [
                        'emp_per_id' => (isset($emp_per_id) && !empty($emp_per_id)) ? $emp_per_id : null,
                        'name' => (isset($signingOfficerName) && !empty($signingOfficerName)) ? $signingOfficerName : null,
                        'signature' => (isset($signingOfficerSignature) && !empty($signingOfficerSignature)) ? $signingOfficerSignature : null,
                        'date' => (isset($signingOfficerDate) && !empty($signingOfficerDate)) ? $signingOfficerDate : null,
                        'designation' =>(isset($signingOfficerDesignation) && !empty($signingOfficerDesignation)) ? $signingOfficerDesignation : null,
                        'next_review_date' => (isset($signingOfficerNRDate) && !empty($signingOfficerNRDate)) ? $signingOfficerNRDate : null,
                        'email' => (isset($signingOfficeremail) && !empty($signingOfficeremail)) ? $signingOfficeremail : null,
                        
                   ];
                   $this->db->insert('gmp_emp_signing_officer',  $signingOfficer);
               
                   $counterOfficer = [
                    'emp_per_id' => (isset($emp_per_id) && !empty($emp_per_id)) ? $emp_per_id : null,
                    'name' => (isset($counterOfficerName) && !empty($counterOfficerName)) ? $counterOfficerName : null,
                    'signature' => (isset($counterOfficerSignature) && !empty($counterOfficerSignature)) ? $counterOfficerSignature : null,
                    'date' => (isset($counterOfficerDatee) && !empty($counterOfficerDate)) ? $counterOfficerDate : null,
                    'designation' =>(isset($counterOfficerDesignation) && !empty($counterOfficerDesignation)) ? $counterOfficerDesignation : null,
                    'next_review_date' => (isset($counterOfficerNRDate) && !empty($counterOfficerNRDate)) ? $counterOfficerNRDate : null,
               ];
               $this->db->insert('gmp_emp_counter_officer',  $counterOfficer);

                // ALTER TABLE gmb_perform_key_goals
                // ADD CONSTRAINT fk_emp_per_id
                // FOREIGN KEY (emp_per_id) REFERENCES employee_performance(emp_per_id);
                

                
                // Activity Logs
                addActivityLog("employee_performance", "create", $emp_per_id, "employee_performance", 1, $postData);
                $this->_send_notification_email($emp_email, $emp_first_name, $emp_last_name, $calculatedScore, $signingOfficerName, $counterOfficerName, $reward_comments);

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

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

        }

        redirect("employee/employees_performance/emp_performance_list");

    }

    public function employee_performance_update($id)
    {

        $this->permission->check_label('emp_performance')->update()->access();

        $data['title'] = display('emp_performance');
        $data['employee'] = $this->Employees_model->employee();
        $employee_performance = $this->Employee_performance_model->employee_performance_by_id($id);

        $data['setting'] = $this->db->get('setting')->row();

        // Get all performance criteria data
        $data['id'] = $id;
        $data['employee_id'] = $employee_performance->employee_id;
        $data['perform_sl'] = $employee_performance->perform_sl;
        $data['review_period'] = $employee_performance->review_period;
        $data['position_of_supervisor'] = $employee_performance->position_of_supervisor;
        $data['employee_comments'] = $employee_performance->employee_comments;

        $assesment_a_total_score = 0;
        $assesment_b_total_score = 0;

        $employee_performance = $this->Employee_performance_model->employee_performance_criteria_values($id, 1);
        foreach ($employee_performance as $key => $value) {
            if ((int) $value->emp_perform_criteria_id == 1) {
                $data['demonstrated'] = $value->emp_perform_eval;
                $data['demonstrated_score'] = $value->score;
                $data['demonstrated_comments'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 2) {
                $data['timeliness'] = $value->emp_perform_eval;
                $data['timeliness_score'] = $value->score;
                $data['timeliness_score_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 3) {
                $data['impact'] = $value->emp_perform_eval;
                $data['impact_score'] = $value->score;
                $data['impact_score_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 4) {
                $data['overall'] = $value->emp_perform_eval;
                $data['overall_score'] = $value->score;
                $data['overall_score_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 5) {
                $data['beyond_duty'] = $value->score;
                $data['beyond_duty_commnets'] = $value->comments;
            }

            $assesment_a_total_score = $assesment_a_total_score + (int) $value->score;
        }
        $data['assesment_a_total_score'] = $assesment_a_total_score;

        $employee_performance = $this->Employee_performance_model->employee_performance_criteria_values($id, 2);
        foreach ($employee_performance as $key => $value) {
            if ((int) $value->emp_perform_criteria_id == 6) {
                $data['interpersonal'] = $value->emp_perform_eval;
                $data['interpersonal_score'] = $value->score;
                $data['interpersonal_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 7) {
                $data['attendance'] = $value->emp_perform_eval;
                $data['attendance_score'] = $value->score;
                $data['attendance_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 8) {
                $data['communication'] = $value->emp_perform_eval;
                $data['communication_score'] = $value->score;
                $data['communication_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 9) {
                $data['contributing'] = $value->emp_perform_eval;
                $data['contributing_score'] = $value->score;
                $data['contributing_commnets'] = $value->comments;
            }
            $assesment_b_total_score = $assesment_b_total_score + (int) $value->score;
        }
        $data['assesment_b_total_score'] = $assesment_b_total_score;
        $data['score_final'] = $assesment_a_total_score + $assesment_b_total_score;

        $data['development_plans'] = $this->Employee_performance_model->development_plans($id);
        $data['data_key_goals'] = $this->Employee_performance_model->key_goals_data($id);

        $data['module'] = "employee";
        $data['page'] = "emp_perform_appraisal/update_employee_performance";

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

    }

    public function save_updated_employee_performance($id)
    {

        $this->permission->check_label('emp_performance')->update()->access();

        $data['title'] = display('emp_performance');
        #-------------------------------#
        $this->form_validation->set_rules('employee_id', display('employee_name'), 'required');
        $this->form_validation->set_rules('review_period', display('review_period'), 'required');
        $this->form_validation->set_rules('employee_comments', display('employee_comments'), 'max_length[500]');
        #-------------------------------#
        if ($this->form_validation->run() === true) {

            $recommand_areas = $this->input->post('recommand_areas', true);
            $expected_outcomes = $this->input->post('expected_outcomes', true);
            $responsible_person = $this->input->post('responsible_person', true);
            $start_date = $this->input->post('start_date', true);
            $end_date = $this->input->post('end_date', true);

            $key_goals = $this->input->post('key_goals', true);
            $completion_period = $this->input->post('completion_period', true);

            $demonstrated_score = (int) $this->input->post('demonstrated_score', true);
            $timeliness_score = (int) $this->input->post('timeliness_score', true);
            $impact_score = (int) $this->input->post('impact_score', true);
            $overall_score = (int) $this->input->post('overall_score', true);
            $beyond_duty = (int) $this->input->post('beyond_duty', true);

            $interpersonal = (int) $this->input->post('interpersonal_score', true);
            $attendance = (int) $this->input->post('attendance_score', true);
            $communication = (int) $this->input->post('communication_score', true);
            $contributing = (int) $this->input->post('contributing_score', true);

            // $assesment_a_score = $demonstrated_score + $timeliness_score + $impact_score + $overall_score + $beyond_duty;
            // $assesment_b_score = $interpersonal + $attendance + $communication + $contributing;
            // $assesment_score = 0;
            // $assesment_score = $assesment_a_score + $assesment_b_score;

            $postData = [
                'emp_per_id' => $id,
                'employee_id' => $this->input->post('employee_id', true),
                'review_period' => $this->input->post('review_period', true),
                'position_of_supervisor' => $this->input->post('position_of_supervisor', true),
                'total_scores' => $assesment_score,
                'employee_comments' => $this->input->post('employee_comments', true),
            ];

            $postData['date'] = date('Y-m-d');
            $postData['create_date'] = date('Y-m-d');
            $postData['create_by'] = $this->session->userdata('id');

            $update_respo = $this->Employee_performance_model->update_emp_paerformance($postData);

            if ($update_respo) {

                $respo_all_delete = $this->Employee_performance_model->delete_all_performance_criteria_values($id);

                if ($respo_all_delete) {

                    $emp_per_id = $id;

                    /*Assesment_a data*/
                    $postData_a_demonstrated = [
                        'emp_per_id' => $emp_per_id,
                        'emp_perform_type_id' => 1,
                        'emp_perform_criteria_id' => 1,
                        'emp_perform_eval' => (int) $this->input->post('demonstrated', true),
                        'score' => (int) $this->input->post('demonstrated_score', true),
                        'comments' => $this->input->post('demonstrated_comments', true),
                    ];
                    $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                    $postData_a_demonstrated = [
                        'emp_per_id' => $emp_per_id,
                        'emp_perform_type_id' => 1,
                        'emp_perform_criteria_id' => 2,
                        'emp_perform_eval' => (int) $this->input->post('timeliness', true),
                        'score' => (int) $this->input->post('timeliness_score', true),
                        'comments' => $this->input->post('timeliness_score_commnets', true),
                    ];
                    $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                    $postData_a_demonstrated = [
                        'emp_per_id' => $emp_per_id,
                        'emp_perform_type_id' => 1,
                        'emp_perform_criteria_id' => 3,
                        'emp_perform_eval' => (int) $this->input->post('impact', true),
                        'score' => (int) $this->input->post('impact_score', true),
                        'comments' => $this->input->post('impact_score_commnets', true),
                    ];
                    $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                    $postData_a_demonstrated = [
                        'emp_per_id' => $emp_per_id,
                        'emp_perform_type_id' => 1,
                        'emp_perform_criteria_id' => 4,
                        'emp_perform_eval' => (int) $this->input->post('overall', true),
                        'score' => (int) $this->input->post('overall_score', true),
                        'comments' => $this->input->post('overall_score_commnets', true),
                    ];
                    $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                    $postData_a_demonstrated = [
                        'emp_per_id' => $emp_per_id,
                        'emp_perform_type_id' => 1,
                        'emp_perform_criteria_id' => 5,
                        'emp_perform_eval' => (int) $this->input->post('beyond_duty', true),
                        'score' => (int) $this->input->post('beyond_duty', true),
                        'comments' => $this->input->post('beyond_duty_commnets', true),
                    ];
                    $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                    /*Assesment_b data*/
                    $postData_a_demonstrated = [
                        'emp_per_id' => $emp_per_id,
                        'emp_perform_type_id' => 2,
                        'emp_perform_criteria_id' => 6,
                        'emp_perform_eval' => (int) $this->input->post('interpersonal', true),
                        'score' => (int) $this->input->post('interpersonal_score', true),
                        'comments' => $this->input->post('interpersonal_commnets', true),
                    ];
                    $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                    $postData_a_demonstrated = [
                        'emp_per_id' => $emp_per_id,
                        'emp_perform_type_id' => 2,
                        'emp_perform_criteria_id' => 7,
                        'emp_perform_eval' => (int) $this->input->post('attendance', true),
                        'score' => (int) $this->input->post('attendance_score', true),
                        'comments' => $this->input->post('attendance_commnets', true),
                    ];
                    $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                    $postData_a_demonstrated = [
                        'emp_per_id' => $emp_per_id,
                        'emp_perform_type_id' => 2,
                        'emp_perform_criteria_id' => 8,
                        'emp_perform_eval' => (int) $this->input->post('communication', true),
                        'score' => (int) $this->input->post('communication_score', true),
                        'comments' => $this->input->post('communication_commnets', true),
                    ];
                    $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                    $postData_a_demonstrated = [
                        'emp_per_id' => $emp_per_id,
                        'emp_perform_type_id' => 2,
                        'emp_perform_criteria_id' => 9,
                        'emp_perform_eval' => (int) $this->input->post('contributing', true),
                        'score' => (int) $this->input->post('contributing_score', true),
                        'comments' => $this->input->post('contributing_commnets', true),
                    ];
                    $this->db->insert('gmb_emp_perform_values', $postData_a_demonstrated);

                }

                // Insert E. DEVELOPMENT PLAN data into database
                $respo_dev_plan_delete = $this->Employee_performance_model->delete_all_performance_dev_plan($emp_per_id);

                if ($respo_dev_plan_delete) {

                    for ($i = 0; $i < count($recommand_areas); $i++) {
                        $development_plan = [
                            'recommand_areas' => $recommand_areas[$i],
                            'expected_outcomes' => isset($expected_outcomes[$i]) ? $expected_outcomes[$i] : '',
                            'responsible_person' => isset($responsible_person[$i]) ? $responsible_person[$i] : '',
                            'start_date' => (isset($start_date[$i]) && !empty($start_date[$i])) ? $start_date[$i] : null,
                            'end_date' => (isset($end_date[$i]) && !empty($end_date[$i])) ? $end_date[$i] : null,
                            'emp_per_id' => $emp_per_id,
                        ];
                        if (!empty($recommand_areas[$i])) {
                            $this->db->insert('gmb_perform_development_plan', $development_plan);
                        }
                    }
                }

                // Insert F. KEY GOALS FOR NEXT REVIEW PERIOD
                $respo_key_goals_delete = $this->Employee_performance_model->delete_all_performance_key_goals($emp_per_id);

                if ($respo_key_goals_delete) {

                    for ($i = 0; $i < count($key_goals); $i++) {
                        $key_goals_data = [
                            'key_goals' => $key_goals[$i],
                            'completion_period' => (isset($completion_period[$i]) && !empty($completion_period[$i])) ? $completion_period[$i] : null,
                            'emp_per_id' => $emp_per_id,
                        ];
                        if (!empty($key_goals[$i])) {
                            $this->db->insert('gmb_perform_key_goals', $key_goals_data);
                        }
                    }
                }

                // Activity Logs
                addActivityLog("employee_performance", "update", $id, "employee_performance", 2, $postData);
               

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

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

        } else {
            $this->session->set_flashdata('exception', validation_errors());

        }

        redirect("employee/employees_performance/emp_performance_list");
    }

    public function employee_performance_delete($id)
    {

        $this->permission->check_label('emp_performance')->delete()->access();

        if ($this->Employee_performance_model->delete_employee_performance($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_performance/emp_performance_list");
    }

    public function employee_performance_view($id)
    {

        $this->permission->check_label('emp_performance')->read()->access();

        $data['title'] = display('emp_performance');
        $data['employee'] = $this->Employees_model->employee();
        $employee_performance = $this->Employee_performance_model->employee_performance_by_id($id);
        $employee_info = $this->Employee_performance_model->employee_performance_for_view_by_id($employee_performance->employee_id);
        $employee_scores = $this->Employee_performance_model->employee_performance_key_scores_by_id($id);
        $employee_reward = $this->Employee_performance_model->employee_performance_emp_reward_by_id($id);
        $signingOfficer =  $this->Employee_performance_model->employee_performance_emp_signing_by_id($id);
        $counterOfficer =  $this->Employee_performance_model->employee_performance_emp_counter_signing_by_id($id);
       

        // Get all performance criteria data
        $data['id'] = $id;
        $data['is_admin'] = $this->session->userdata('isAdmin'); 
        $data['userRole'] = $this->session->userdata('userRole');
        $data['employee_id'] = $employee_performance->employee_id;
        $data['empplyee_name'] = $employee_info->first_name . ' ' . $employee_info->last_name;
        $data['empplyee_email'] =  $employee_info->email;
        $data['department_name'] = $employee_info->department_name;
        $data['job_title'] = $employee_info->position_name;
        $data['perform_sl'] = $employee_performance->perform_sl;
        $data['review_period'] = $employee_performance->review_period;
        $data['status'] = $employee_performance->status;
        //$data['employee_growth'] = $employee_performance->employee_growth;
        //$data['overall_evaluation'] = $employee_performance->overall_evaluation;
        $data['position_of_supervisor'] = $employee_performance->position_of_supervisor;
        $data['employee_comments'] = $employee_performance->employee_comments;
        $data['growth_comments'] = $employee_performance->growth_comments;
        $data['total_scores'] = $employee_performance->total_scores;
        $data['performance_year'] = date('Y', strtotime($employee_performance->date));
        

        $data['setting'] = $this->db->get('setting')->row();

        $assesment_a_total_score = 0;
        $assesment_b_total_score = 0;

        $employee_performance = $this->Employee_performance_model->employee_performance_criteria_values($id, 1);
        foreach ($employee_performance as $key => $value) {
            if ((int) $value->emp_perform_criteria_id == 1) {
                $data['demonstrated'] = $value->emp_perform_eval;
                $data['demonstrated_score'] = $value->score;
                $data['demonstrated_comments'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 2) {
                $data['timeliness'] = $value->emp_perform_eval;
                $data['timeliness_score'] = $value->score;
                $data['timeliness_score_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 3) {
                $data['impact'] = $value->emp_perform_eval;
                $data['impact_score'] = $value->score;
                $data['impact_score_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 4) {
                $data['overall'] = $value->emp_perform_eval;
                $data['overall_score'] = $value->score;
                $data['overall_score_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 5) {
                $data['beyond_duty'] = $value->score;
                $data['beyond_duty_commnets'] = $value->comments;
            }

            // $assesment_a_total_score = $assesment_a_total_score + (int) $value->score;
        }
        $data['score']['assesment_a_total_score'] = $assesment_a_total_score;

        $employee_performance = $this->Employee_performance_model->employee_performance_criteria_values($id, 2);
        foreach ($employee_performance as $key => $value) {
            if ((int) $value->emp_perform_criteria_id == 6) {
                $data['interpersonal'] = $value->emp_perform_eval;
                $data['interpersonal_score'] = $value->score;
                $data['interpersonal_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 7) {
                $data['work_relationship'] = $value->emp_perform_eval;
                $data['work_relationship_score'] = $value->score;
                $data['work_relationship_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 8) {
                $data['communication'] = $value->emp_perform_eval;
                $data['communication_score'] = $value->score;
                $data['communication_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 9) {
                $data['contributing'] = $value->emp_perform_eval;
                $data['contributing_score'] = $value->score;
                $data['contributing_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 10) {
                $data['problem_solving'] = $value->emp_perform_eval;
                $data['problem_solving_score'] = $value->score;
                $data['problem_solving_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 11) {
                $data['decision_making'] = $value->emp_perform_eval;
                $data['decision_making_score'] = $value->score;
                $data['decision_making_commnets'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 12) {
                $data['learning_capacity'] = $value->emp_perform_eval;
                $data['learning_capacity_score'] = $value->score;
                $data['learning_capacity_commnets'] = $value->comments;
            }
            // $assesment_b_total_score = $assesment_b_total_score + (int) $value->score;

        }

        $employee_performance = $this->Employee_performance_model->employee_evaluation_criteria_values($id, 3);
       
        foreach ($employee_performance as $key => $value) {
            if ((int) $value->emp_perform_criteria_id == 13) {
                $data['quality'] = $value->emp_perform_eval;
                $data['quality_score'] = $value->score;
                $data['quality_comments'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 14) {
                $data['work_output'] = $value->emp_perform_eval;
                $data['work_output_score'] = $value->score;
                $data['work_output_comments'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 15) {
                $data['dependability'] = $value->emp_perform_eval;
                $data['dependability_score'] = $value->score;
                $data['dependability_comments'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 16) {
                $data['job_attitude'] = $value->emp_perform_eval;
                $data['job_attitude_score'] = $value->score;
                $data['job_attitude_comments'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 17) {
                $data['adaptability'] = $value->emp_perform_eval;
                $data['adaptability_score'] = $value->score;
                $data['adaptability_comments'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 18) {
                $data['job_knowledge'] = $value->emp_perform_eval;
                $data['job_knowledge_score'] = $value->score;
                $data['job_knowledge_comments'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 19) {
                $data['attendance'] = $value->emp_perform_eval;
                $data['attendance_score'] = $value->score;
                $data['attendance_comments'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 20) {
                $data['physical_fitness'] = $value->emp_perform_eval;
                $data['physical_fitness_score'] = $value->score;
                $data['physical_fitness_comments'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 21) {
                $data['cooperativeness'] = $value->emp_perform_eval;
                $data['cooperativeness_score'] = $value->score;
                $data['cooperativeness_comments'] = $value->comments;
            }
            if ((int) $value->emp_perform_criteria_id == 22) {
                $data['learning_capacity'] = $value->emp_perform_eval;
                $data['learning_capacity_score'] = $value->score;
                $data['learning_capacity_comments'] = $value->comments;
            }
        }

        $data['emp_exp']=$this->Employee_performance_model->employee_performance_emp_exp_by_id($id);
        $data['emp_academic']=$this->Employee_performance_model->employee_performance_emp_academic_by_id($id);
        $emp_academic = $data['emp_academic']; 
          foreach ($emp_academic as $key => $row) { 
            $academic_evaluation_data_array = json_decode($row->academic_evaluation, true);
            
            // Check if the decoded data is an array
            if (is_array($academic_evaluation_data_array)) {
                foreach ($academic_evaluation_data_array as $evaluation) {
                    $data['quality_teaching_score'] = $evaluation['quality_teaching_score'];
                    $data['current_research_score'] = $evaluation['current_research_score'];
                    $data['quality_research_score'] = $evaluation['quality_research_score'];
                    $data['quality_publication_score'] = $evaluation['quality_publication_score'];
                    $data['department_responsibilities_score'] = $evaluation['department_responsibilities_score'];
                    $data['contribution_score'] = $evaluation['contribution_score'];
                    $data['relationship_colleagues_score'] = $evaluation['relationship_colleagues_score'];
                    $data['acceptance_responsibility_score'] = $evaluation['acceptance_responsibility_score'];
                    $data['management_staff_score'] = $evaluation['management_staff_score'];
                    $data['punctuality_score'] = $evaluation['punctuality_score'];
                    $data['appearance_score'] = $evaluation['appearance_score'];
                }}}

        $data['emp_mgt']=$this->Employee_performance_model->employee_performance_emp_mgt_by_id($id);
        $emp_mgt = $data['emp_mgt']; 
        foreach ($emp_mgt as $key => $row) { 
            $leadership_mgt_data_array = json_decode($row->leadership_mgt, true);
        
            // Check if JSON decoding was successful
            if (json_last_error() === JSON_ERROR_NONE) {
                // Check if the decoded data is an array
                if (is_array($leadership_mgt_data_array)) {
                    foreach ($leadership_mgt_data_array as $mgt_data) {
                        $data['leadership'] = isset($mgt_data['leadership']) ? $mgt_data['leadership'] : null;
                        $data['leadership_score'] = isset($mgt_data['leadership_score']) ? $mgt_data['leadership_score'] : null;
                        $data['leadership_comments'] = isset($mgt_data['leadership_comments']) ? $mgt_data['leadership_comments'] : null;
                        $data['leadership1'] = isset($mgt_data['leadership1']) ? $mgt_data['leadership1'] : null;
                    }
                } else {
                    echo "Decoded data is not an array.";
                }
            } else {
                echo "JSON decoding error: " . json_last_error_msg();
            }
            
            $decision_mgt_data_array = json_decode($row->decision_mgt, true);

            if (json_last_error() === JSON_ERROR_NONE && is_array($decision_mgt_data_array)) {
                if (is_array($decision_mgt_data_array)) {
                foreach ($decision_mgt_data_array as $mgt_data) {
                    $data['decision_making_cap1'] = isset($mgt_data['mgt_descision1']) ? $mgt_data['mgt_descision1'] : 1;
                    $data['decision_making_cap1_score'] = isset($mgt_data['mgt_descision1_score']) ? $mgt_data['mgt_descision1_score'] : 1;
                    $data['decision_making_cap1_comments'] = isset($mgt_data['mgt_descision1_comments']) ? $mgt_data['mgt_descision1_comments'] : '';

                    $data['decision_making_cap2'] = isset($mgt_data['mgt_descision2']) ? $mgt_data['mgt_descision2'] : 1;
                    $data['decision_making_cap2_score'] = isset($mgt_data['mgt_descision2_score']) ? $mgt_data['mgt_descision2_score'] : 1;
                    $data['decision_making_cap2_comments'] = isset($mgt_data['mgt_descision2_comments']) ? $mgt_data['mgt_descision2_comments'] : '';

                    $data['decision_making_cap3'] = isset($mgt_data['mgt_descision3']) ? $mgt_data['mgt_descision3'] : 1;
                    $data['decision_making_cap3_score'] = isset($mgt_data['mgt_descision3_score']) ? $mgt_data['mgt_descision3_score'] : 1;
                    $data['decision_making_cap3_comments'] = isset($mgt_data['mgt_descision3_comments']) ? $mgt_data['mgt_descision3_comments'] : '';

                    $data['decision_making_cap4'] = isset($mgt_data['mgt_descision4']) ? $mgt_data['mgt_descision4'] : '';
           
                    }
                } else {
                    echo "Decoded data is not an array.";
                }
                    } else {
                echo "JSON decoding error: " . json_last_error_msg();
            }

            $management_competence_data = json_decode($row->comptence_mgt, true);
    
            if (json_last_error() === JSON_ERROR_NONE && is_array($management_competence_data)) {
                foreach ($management_competence_data as $mgt_data) {
                    if (is_array($management_competence_data)) {
                    $data['management_com1'] = isset($mgt_data['mgt_management1']) ? $mgt_data['mgt_management1'] : 1;
                    $data['management_com1_score'] = isset($mgt_data['mgt_management1_score']) ? $mgt_data['mgt_management1_score'] : 1;
                    $data['management_com1_comments'] = isset($mgt_data['mgt_management1_comments']) ? $mgt_data['mgt_management1_comments'] : '';
        
                    $data['management_com2'] = isset($mgt_data['mgt_management2']) ? $mgt_data['mgt_management2'] : 1;
                    $data['management_com2_score'] = isset($mgt_data['mgt_management2_score']) ? $mgt_data['mgt_management2_score'] : 1;
                    $data['management_com2_comments'] = isset($mgt_data['mgt_management2_comments']) ? $mgt_data['mgt_management2_comments'] : '';
        
                    $data['management_com3'] = isset($mgt_data['mgt_management3']) ? $mgt_data['mgt_management3'] : 1;
                    $data['management_com3_score'] = isset($mgt_data['mgt_management3_score']) ? $mgt_data['mgt_management3_score'] : 1;
                    $data['management_com3_comments'] = isset($mgt_data['mgt_management3_comments']) ? $mgt_data['mgt_management3_comments'] : '';
        
                    $data['management_com4'] = isset($mgt_data['mgt_management4']) ? $mgt_data['mgt_management4'] : '';
                }
             else {
                echo "Decoded data is not an array.";
            }
        }
    }
         else {
            echo "JSON decoding error: " . json_last_error_msg();
        }
        
        $functional_competence_data = json_decode($row->functional_mgt, true);
    
    if (json_last_error() === JSON_ERROR_NONE && is_array($functional_competence_data)) {
        foreach ($functional_competence_data as $func_data) {
            if (is_array($functional_competence_data)) {
            $data['functional1'] = isset($func_data['mgt_functional1']) ? $func_data['mgt_functional1'] : 1;
            $data['functional1_score'] = isset($func_data['mgt_functional1_score']) ? $func_data['mgt_functional1_score'] : 1;
            $data['functional1_comments'] = isset($func_data['mgt_functional1_comments']) ? $func_data['mgt_functional1_comments'] : '';

            $data['functional2'] = isset($func_data['mgt_functional2']) ? $func_data['mgt_functional2'] : 1;
            $data['functional2_score'] = isset($func_data['mgt_functional2_score']) ? $func_data['mgt_functional2_score'] : 1;
            $data['functional2_comments'] = isset($func_data['mgt_functional2_comments']) ? $func_data['mgt_functional2_comments'] : '';

            $data['functional3'] = isset($func_data['mgt_functional3']) ? $func_data['mgt_functional3'] : 1;
            $data['functional3_score'] = isset($func_data['mgt_functional3_score']) ? $func_data['mgt_functional3_score'] : 1;
            $data['functional3_comments'] = isset($func_data['mgt_functional3_comments']) ? $func_data['mgt_functional3_comments'] : '';

            $data['functional4'] = isset($func_data['mgt_functional4']) ? $func_data['mgt_functional4'] : '';
        }
        else {
           echo "Decoded data is not an array.";
       }
   }
}
    else {
       echo "JSON decoding error: " . json_last_error_msg();
   }
        }
       
        $data['promotion'] = isset($employee_reward->promotion) && ($employee_reward->promotion != 0 || null) ? 'Yes' : 'No';
        $data['reward_promotion'] = $employee_reward->reward_promotion;
        
        $data['reward_salary'] = $employee_reward->reward_salary;
        
        $data['merit_award'] = isset($employee_reward->merit_award) && $employee_reward->merit_award ? 'Yes' : 'No';
        $data['reward_amount_merit'] = $employee_reward->reward_amount_merit;
        $data['reward_citation'] = $employee_reward->reward_citation;
        
        $data['annual_increment'] = isset($employee_reward->annual_increment) && $employee_reward->annual_increment ? 'Yes' : 'No';
        $data['reward_amount_annual'] = $employee_reward->reward_amount_annual;
        
        $data['other_increment'] = isset($employee_reward->other_increment) && $employee_reward->other_increment ? 'Yes' : 'No';
        $data['reward_sprcify'] = $employee_reward->reward_sprcify;
        
        $data['redeployment'] = isset($employee_reward->redeployment) && $employee_reward->redeployment ? 'Yes' : 'No';
        $data['reward_job'] = $employee_reward->reward_job;
        
        $data['disciplinary_action'] = isset($employee_reward->disciplinary_action) && $employee_reward->disciplinary_action ? 'Yes' : 'No';
        $data['reward_dept'] = $employee_reward->reward_dept;
        $data['reward_specify'] = $employee_reward->reward_specify;

        $data['reward_comments'] = $employee_reward->reward_comments;
        
        
        $data['key_total_goals_score'] = $employee_scores->key_total_goals_score;
        $data['employee_growth'] = $employee_scores->employee_growth;
        $data['overall_evaluation'] = $employee_scores->overall_evaluation;
        $data['assesment_a_total_score'] = $employee_scores->scores_a;
        $data['assesment_b_total_score'] = $employee_scores->scores_b;
        $data['assesment_c_total_score'] = $employee_scores->scores_c;
        $data['assesment_d_total_score'] = $employee_scores->scores_d;
        $data['calculatedScore'] = $employee_scores->total_scores;

        $data['signingOfficerName'] = $signingOfficer->name;
        $data['signingOfficerSignature'] = $signingOfficer->signature;
        $data['signingOfficerDate'] = $signingOfficer->date;
        $data['signingOfficerDesignation'] = $signingOfficer->designation;
        $data['signingOfficerNRDate'] = $signingOfficer->next_review_date;
        $data['signingOfficeremail'] = $signingOfficer->email;
        
        $data['counterOfficerName'] = $counterOfficer->name;
        $data['counterOfficerSignature'] = $counterOfficer->signature;
        $data['counterOfficerDate'] = $counterOfficer->date;
        $data['counterOfficerDesignation'] = $counterOfficer->designation;
        $data['counterOfficerNRDate'] = $counterOfficer->next_review_date;
        

        // $data['assesment_b_total_score'] = $assesment_b_total_score;
        // $data['score_final'] = $assesment_a_total_score + $assesment_b_total_score;

        $data['development_plans'] = $this->Employee_performance_model->development_plans($id);
        $data['data_key_goals'] = $this->Employee_performance_model->key_goals_data($id);

        $data['module'] = "employee";
        $data['page'] = "emp_perform_appraisal/view_employee_performance";

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

    }
    
    public function save_employees_comments($id) {
              $this->form_validation->set_rules('employee_comments', display('employee_comments'), 'max_length[500]');
         if ($this->form_validation->run() === true) {
             $id = $id;
             $comments = $this->input->post('employee_comments', true);
             $name = $this->input->post('employee_name', true);
             $email = $this->input->post('email', true);
             $score = $this->input->post('empCalculatedscore', true);
             $appraised_by = $this->input->post('signname', true);
              $postData = [
               'emp_per_id' => $id,
                'employee_comments' => $this->input->post('employee_comments', true),
            ];
            if( $this->Employee_performance_model->update_emp_comments($postData)){
                $this->session->set_flashdata('message', display('successfully_saved'));
                $this->_send_emp_notification_email($email, $name, $score, $comments, $id, $appraised_by );
                redirect("employee/Employees_performance/emp_performance_list");
            } else {
                $this->session->set_flashdata('exception', display('please_try_again'));
            }

         }
         else {
            $this->session->set_flashdata('exception', validation_errors());

        }
        
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////

}