<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Exam extends MY_Controller {

    function __construct() {
        parent::__construct();

        if ($this->logged_user = $this->session->userdata('user')) {
            $this->login->checkModuleAccess(4);

            $this->logged_module = $_SESSION['module_data'];

            $this->load->model('admin/model_user');
            $this->load->model('admin/model_company');
            $this->load->model('hr/model_exam');
        } else {
            redirect(base_url());
        }
    }

    public function index() {
        $this->examSetup();
    }

    public function exam_list_admin() {
        $this->load->model('hr/model_exam');

        $data = array(
            'exam_list' => $this->model_exam->get_exam_list_admin(),
            'staff_list' => $this->model_user->getUsers2(),
            'page_setup' => $this->template->pageSetup('HR', '', 'Professional Exam / Courses'),
        );

        $this->template->view('hr/exam/exam_list', $data);
    }

    public function save_exams() {
        if (!empty($this->input->post('exam_result'))) {
            $result = $this->input->post('exam_result');
        } else {
            $result = NULL;
        }

        $paper_code = $this->input->post('exam_papercode');
        $staff_id = $this->input->post('exam_staffid');

        $count_paper_code = $this->model_exam->get_count_paper_code($paper_code, $staff_id);

        if ($count_paper_code[0]->count >= 2) {

            $this->session->set_flashdata('error', "System failed to save Professional Exam / Courses. This Paper Code already registered 2 times.");

            if ($this->session->userdata('module_data')['role'] == 'admin') {
                redirect(base_url('hr/exam/examSetup'));
            } else {
                redirect(base_url('hr/exam/examSetup/' . $_SESSION['user']['id']));
            }
        } else {

            $insert_data = array(
                'staff_id' => $staff_id,
                'programme_id' => $this->input->post('exam_programme'),
                'paper_code' => $paper_code,
                'title' => $this->input->post('exam_papertitle'),
                'exam_date' => date("Y-m-d", strtotime($this->input->post('exam_date'))),
                'status' => $this->input->post('exam_status'),
                'result' => $result,
                'created_by' => $_SESSION['user']['id'],
            );

            $insert_exam = $this->model_exam->save_exam($insert_data);

            if ($insert_exam) {
                $this->examEmail('new_exam', $insert_exam);
                $this->session->set_flashdata('success', "Successfully save Professional Exam / Courses.");
            } else {
                $this->session->set_flashdata('error', "System failed to save Professional Exam / Courses.");
            }

            if ($this->session->userdata('module_data')['role'] == 'admin') {
                redirect(base_url('hr/exam/examSetup'));
            } else {
                redirect(base_url('hr/exam/examSetup/' . $_SESSION['user']['id']));
            }
        }
    }

    public function delete_exam() {
        $set = array
            (
            'is_delete' => 1,
            'updated_by' => $_SESSION['user']['id'],
        );

        $where = array
            (
            'id' => $this->input->post('exam_id'),
        );

        $delete_exam = $this->model_exam->update_exam($set, $where);

        if ($delete_exam) {
            print json_encode(array(
                "status" => "Success",
                "msg" => "Successfully delete Professional Exam / Courses."
            ));
        } else {
            print json_encode(array(
                "status" => "Error",
                "msg" => "System failed to delete Professional Exam / Courses."
            ));
        }
    }

    public function edit_exams() {
        if (!empty($this->input->post('exam_result_edit')) || $this->input->post('exam_result_edit') != NULL) {
            $result = $this->input->post('exam_result_edit');
        } else {
            $result = NULL;
        }

        $set = array
            (
            'staff_id' => $this->input->post('exam_staffid_edit'),
            'programme' => $this->input->post('exam_programme_edit'),
            'paper_code' => $this->input->post('exam_papercode_edit'),
            'title' => $this->input->post('exam_papertitle_edit'),
            'exam_date' => date("Y-m-d", strtotime($this->input->post('exam_date_edit'))),
            'status' => $this->input->post('exam_status_edit'),
            'result' => $result,
            'updated_by' => $_SESSION['user']['id'],
        );

        $where = array
            (
            'id' => $this->input->post('exam_examid_edit'),
        );

        $update_exam = $this->model_exam->update_exam($set, $where);

        if ($update_exam) {
            $this->session->set_flashdata('success', "Successfully edit Professional Exam / Courses.");
        } else {
            $this->session->set_flashdata('error', "System failed to edit Professional Exam / Courses.");
        }

        if ($this->session->userdata('module_data')['role'] == 'admin') {
            redirect(base_url('hr/exam/examSetup'));
        } else {
            redirect(base_url('hr/exam/examSetup/' . $_SESSION['user']['id']));
        }
    }

    public function clone_exams() {
        if (!empty($this->input->post('exam_result_clone')) || $this->input->post('exam_result_clone') != NULL) {
            $result = $this->input->post('exam_result_clone');
        } else {
            $result = NULL;
        }

        $paper_code = $this->input->post('exam_papercode_clone_hidden');
        $staff_id = $this->input->post('exam_staffid_clone_hidden');

        $count_paper_code = $this->model_exam->get_count_paper_code($paper_code, $staff_id);

        if ($count_paper_code[0]->count >= 2) {

            $this->session->set_flashdata('error', "System failed to clone Professional Exam / Courses. This Paper Code already registered 2 times.");

            if ($this->session->userdata('module_data')['role'] == 'admin') {
                redirect(base_url('hr/exam/examSetup'));
            } else {
                redirect(base_url('hr/exam/examSetup/' . $_SESSION['user']['id']));
            }
        } else {
            $insert_data = array(
                'staff_id' => $staff_id,
                'programme' => $this->input->post('exam_programme_clone_hidden'),
                'paper_code' => $paper_code,
                'title' => $this->input->post('exam_papertitle_clone_hidden'),
                'exam_date' => date("Y-m-d", strtotime($this->input->post('exam_date_clone'))),
                'status' => $this->input->post('exam_status_clone'),
                'result' => $result,
                'created_by' => $_SESSION['user']['id'],
            );

            $insert_exam = $this->model_exam->save_exam($insert_data);

            if ($insert_exam) {
                $this->examEmail('clone_exam', $insert_exam);
                $this->session->set_flashdata('success', "Successfully clone Professional Exam / Courses.");
            } else {
                $this->session->set_flashdata('error', "System failed to clone Professional Exam / Courses.");
            }

            if ($this->session->userdata('module_data')['role'] == 'admin') {
                redirect(base_url('hr/exam/examSetup'));
            } else {
                redirect(base_url('hr/exam/examSetup/' . $_SESSION['user']['id']));
            }
        }
    }

    public function check_study_leave() {
        $exam_id = $this->input->post('exam_id');

        $contain_study_leave = $this->model_exam->get_study_leave($exam_id);

        if ($contain_study_leave) {
            print json_encode(array(
                "status" => "Error",
                "msg" => "This Professional Exam / Courses contain study leave recorded."
            ));
        } else {
            print json_encode(array(
                "status" => "Success",
                "msg" => "Success"
            ));
        }
    }

    public function create_study_leave_allocation() {
        $this->load->model('hr/model_exam');

        $staff_id = $this->input->post('leave_staffid');
        $exam_id = $this->input->post('leave_examid');
        $add_balance = $this->input->post('leave_addDays');
        $year = date('Y');
        $examDate = $this->db->query('select * from hr__exam where id=' . $exam_id)->row()->exam_date;

        // set from and to date. to is day before exam. $add_balance days excluding weekend
        $tdate = date_create($examDate);
        $i = 0;
        while ($i < intval($add_balance)) {
            date_sub($tdate, date_interval_create_from_date_string('1 days'));
            if ((date('N', $tdate->getTimestamp()) < 6)) {
                if ($i == 0) {
                    $ed = date_format($tdate, 'Y-m-d');
                }
                $i++;
            }
        }
        $sd = date_format($tdate, 'Y-m-d');

        $set = array
            (
            'allocation_status' => 1,
            'updated_by' => $_SESSION['user']['id'],
        );

        $where = array
            (
            'id' => $exam_id,
        );

        $update_exam = $this->model_exam->update_exam($set, $where);

        $allocation_check = $this->model_exam->check_existing_study_leave_allocation($staff_id, $year);

        if (!empty($allocation_check)) {

            $set_allocation = array
                (
                'balance_entitled' => $allocation_check[0]['balance_entitled'] + $add_balance,
                'leave_entitled' => $allocation_check[0]['balance_entitled'] + $add_balance,
                'leave_balance' => $allocation_check[0]['leave_balance'] + $add_balance,
                'updated_by' => $_SESSION['user']['id'],
            );

            $where_allocation = array
                (
                'id' => $allocation_check[0]['id'],
            );

            $update_study_leave_allocation = $this->model_exam->update_study_leave_allocation($set_allocation, $where_allocation);
        } else {

            $insert_data = array(
                'user_id' => $staff_id,
                'year' => $year,
                'type_id' => 7,
                'paper_id' => $exam_id,
                'date_from' => $sd,
                'date_to' => $ed,
                'expiry_date' => $examDate,
                'balance_entitled' => $add_balance,
                'leave_entitled' => $add_balance,
                'leave_balance' => $add_balance,
                'created_by' => $_SESSION['user']['id']
            );

            $create_study_leave_allocation = $this->model_exam->insert_study_leave_allocation($insert_data);
        }

        $this->examEmail('allocate_leave', $exam_id);

        $this->session->set_flashdata('success', "Successfully Setup Study Leave Allocation.");

        redirect(base_url('hr/exam/examSetup'));
    }

    public function get_exam_filter() {

        $staff_id = (!empty($this->input->post('exam_filter_staff')) || $this->input->post('exam_filter_staff') != -1) ? $this->input->post('exam_filter_staff') : null;
        $exam_status = (!empty($this->input->post('exam_filter_exam_status')) || $this->input->post('exam_filter_exam_status') != -1) ? $this->input->post('exam_filter_exam_status') : null;
        $sl_status = (!empty($this->input->post('exam_filter_sl_status')) || $this->input->post('exam_filter_sl_status') != -1) ? $this->input->post('exam_filter_sl_status') : null;
        $exam_result = (!empty($this->input->post('exam_filter_exam_result')) || $this->input->post('exam_filter_exam_result') != -1) ? $this->input->post('exam_filter_exam_result') : null;
        $exam_date = (!empty($this->input->post('exam_filter_exam_date')) || $this->input->post('exam_filter_exam_date') != -1) ? $this->input->post('exam_filter_exam_date') : null;

        $where = array();

        if ($staff_id > -1) {
            $this->session->set_userdata('exam_filter_staff', $staff_id);
            $where['a.staff_id'] = $staff_id;
        } else {
            $this->session->set_userdata('exam_filter_staff', 'ALL');
        }

        if ($exam_status > -1) {
            $this->session->set_userdata('exam_filter_exam_status', $exam_status);
            $where['a.status'] = $exam_status;
        } else {
            $this->session->set_userdata('exam_filter_exam_status', 'ALL');
        }

        if ($sl_status > -1) {
            $this->session->set_userdata('exam_filter_sl_status', $sl_status);
            $where['a.allocation_status'] = $sl_status;
        } else {
            $this->session->set_userdata('exam_filter_sl_status', 'ALL');
        }

        if ($exam_result > -1) {
            $this->session->set_userdata('exam_filter_exam_result', $exam_result);
            $where['a.result'] = $exam_result;
        } else {
            $this->session->set_userdata('exam_filter_exam_result', 'ALL');
        }

        if (!empty($exam_date) && $exam_date > 0) {
            $this->session->set_userdata('exam_filter_exam_date', $exam_date);
            $where['a.exam_date'] = date("Y-m-d", strtotime($exam_date));
        } else {
            $this->session->set_userdata('exam_filter_exam_date', 'ALL');
        }

        $select = array('a.*, b.name as staff_name, c.name as department_name, d.name as branch_name');
        $where['a.is_delete'] = 0;

        $join = array
            (
            array('user__employment_detail b', 'a.staff_id = b.id', 'left outer'),
            array('company__department c', 'b.department_id = c.id', 'left outer'),
            array('company__branch d', 'c.branch_id = d.id', 'left outer'),
        );

        $orderBy['a.ID'] = 'desc';

        $table = $this->model_exam->exam__filter('hr__exam a', $select, $where, $join, $orderBy, null, (!empty($having)) ? $having : null, (!empty($or_having)) ? $or_having : null);

        // echo $this->db->last_query();

        $data = array
            (
            'status' => 'success',
            'message' => '',
            'table' => $table,
            'exam_filter_staff' => $this->input->post('exam_filter_staff'),
            'exam_filter_exam_status' => $this->input->post('exam_filter_exam_status'),
            'exam_filter_sl_status' => $this->input->post('exam_filter_sl_status'),
            'exam_filter_exam_result' => $this->input->post('exam_filter_exam_result'),
            'exam_filter_exam_date' => $this->input->post('exam_filter_exam_date'),
        );

        $this->session->set_userdata('hr__exam', $data['table']);
        echo json_encode($data);
        return true;
    }

    public function print_examList() {
        $date = date("d-m-Y");
        $data['title'] = 'PROFESSIONAL EXAM / COURSES LIST AS AT ' . $date;

        if (!empty($this->session->userdata('exam_filter_staff'))) {
            $data['staff_list'] = $this->model_user->getUsers2($this->session->userdata('exam_filter_staff'));
        }

        if ($this->session->userdata('hr__exam') && $this->session->userdata('hr__exam') != 'No Data') {
            $data['exam_list'] = $this->session->userdata('hr__exam');
        } else {
            $data['exam_list'] = $this->model_exam->get_exam_list_admin();
        }

        $this->load->view('hr/exam/report/header.php');
        $this->load->view('hr/exam/report/exam_report_all', $data);
        $this->load->view('hr/exam/report/footer.php');
    }

    public function examEmail($mode, $id) {
        if ($mode == 'new_exam') {

            $form_detail = array();
            $data['data_exam'] = $this->model_exam->getExamListByID($id);
            // $form_requestor_detail 	= $this->model_user->getUsersEmails(array('c.module_id IN (4)','c.access_lvl IN ("admin")','c.status = 0','c.is_delete = 0','d.department_id IN (2)','d.is_delete = 0','d.status = 0'));

            $form_requestor_detail = array('0' => array('primary_email' => 'hanini@salihin.com.my'));

            if ($form_requestor_detail) {
                foreach ($form_requestor_detail as $key => $value) {
                    $form_requestor_email = ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);

                    $emailSubject = 'New Professional Exam / Courses Request by ' . $data['data_exam'][0]->staff_name;
                    $emailMessage = 'A new professional exam / courses was received for your reference. Kindly review the details and assign the allocation for the respective request. <br> Paper Code : ' . $data['data_exam'][0]->paper_code . ' <br> Link : ' . base_url('hr/exam/examSetup');
                    $emailDetailForm = $form_detail;

                    $emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $form_requestor_email);
                }
            }

            return $id;

        } else if ($mode == 'clone_exam') {  

            $form_detail = array();
            $data['data_exam'] = $this->model_exam->getExamListByID($id);

            // $form_requestor_detail 	= $this->model_user->getUsersEmails(array('c.module_id IN (4)','c.access_lvl IN ("admin")','c.status = 0','c.is_delete = 0','d.department_id IN (2)','d.is_delete = 0','d.status = 0'));

            $form_requestor_detail = array('0' => array('primary_email' => 'hanini@salihin.com.my'));

            if ($form_requestor_detail) {
                foreach ($form_requestor_detail as $key => $value) {
                    $form_requestor_email = ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);

                    $emailSubject = 'Cloned Professional Exam / Courses Request by ' . $data['data_exam'][0]->staff_name;
                    $emailMessage = 'Cloned professional exam / courses was received for your reference. Kindly review the details and assign the allocation for the respective request. <br> Paper Code : ' . $data['data_exam'][0]->paper_code . ' <br> Link : ' . base_url('hr/exam/examSetup');
                    $emailDetailForm = $form_detail;

                    $emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $form_requestor_email);
                }
            }

            return $id;

        } else if($mode == 'allocate_leave'){

            $form_detail = array();
            $data['data_exam'] = $this->model_exam->getExamListByID($id);

            $form_requestor_detail   = $this->model_user->getUsersEmails(array('b.id = '.$data['data_exam'][0]->staff_id));

            if ($form_requestor_detail) {
                foreach ($form_requestor_detail as $key => $value) {
                    $form_requestor_email = ($value['primary_email']) ? $value['primary_email'] : (($value['secondary_email']) ? $value['secondary_email'] : $value['email']);

                    $emailSubject = 'Study Leave Allocation';
                    $emailMessage = 'Your study leave request for ' . $data['data_exam'][0]->paper_code . ' was approved. Thank you.';
                    $emailDetailForm = $form_detail;

                    $emailSend = $this->send_copy_email($emailSubject, $emailMessage, $emailDetailForm, $form_requestor_email);
                }
            }

            return $id;

        }
    }

    private function send_copy_email($subject = '', $message = '', $detail_form = array(), $user_email = array()) {
        $email_data['subject'] = $subject;
        $email_data['message'] = $message;
        $email_data['emailDetailForm'] = $detail_form;
        $email_data['emails'] = [];

        if (!is_array($user_email)) {
            array_push($email_data['emails'], $user_email);
        } else {
            $email_data['emails'] = $user_email;
        }

        $this->load->library('email');
        $this->load->library('parser');
        $this->load->library('encrypt');

        $email_template = $this->load->view("template/email/header", "", true);
        $email_template .= $this->load->view("template/email/body/serviceForm", $email_data, true);
        $email_template .= $this->load->view("template/email/footer", "", true);

        $this->email->from('noreply@salihin.com.my')
                ->to($email_data['emails'])
                ->subject($subject)
                ->message($email_template)
                ->set_mailtype("html");

        $send = $this->email->send(); //comment this if dont want to send email 
        // $send = 1;

        if ($send) {
            $this->session->set_flashdata('success', "Successfully Send Email. Thank you.");
        } else {
            $this->session->set_flashdata('error', "System failed to Send Email. Please try again.");
        }

        return $send;
    }

}
