<?php

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

class Form extends CI_Controller
{

    function __construct()
    {
        /* Call the Model constructor */
        parent::__construct();
        /* Get System Variable */
        $this->data['var'] = $this->app->get_var_sys();

        /* Check Authen & Permission User */
        if (empty($this->session->userdata("user_profile")->id)) {
            redirect('authen', 'refresh');
            exit();
        } else {
            /* Get Permission Module */
            $this->data['permission'] = @$this->app->get_permission($this->uri->uri_string());
            $this->data['timestamp'] = @$this->app->last_updated_table("leavemaster", "AND user_name ='" . $this->session->userdata("user_profile")->user_name . "'");
        }
    }

    public function index()
    {

        $id = $this->uri->segment(3);

        $this->data['navbar'] = 'layout/navbar';
        $this->data['sidebar'] = 'layout/sidebar';
        $this->data['footer'] = 'layout/footer';
        $this->data['page'] = 'leave/form';

        $sql = "SELECT company_leavetype.*, leavetype.leavetype_name, leavetype.leavetype_color, leavetype.leavetype_icon, leavetype.leavetype_description 
        FROM company_leavetype 
        INNER JOIN leavetype ON leavetype.id = company_leavetype.leavetype_id
        WHERE leavetype.id ='" . $id . "' 
        ORDER BY leavetype.sort";
        $this->data['leavetype'] = $this->db->query($sql)->row();

        /* leave_status IN ('0','2') | นับเฉพาะ (0)รออนุมัติ และ (2)อนุมัติ เท่านั้น เพื่อหักวันลาคงเหลือ */
        $sql = "SELECT company_leavetype.id AS company_leavetype_id, company_leavetype.company_id, company_leavetype.leavetype_id, company_leavetype.num, company_leavetype.per_round,company_leavetype. collect, company_leavetype.advance_notice_day, company_leavetype.month ,
                (
                SELECT IFNULL(SUM(leave_qty),0) AS leave_qty FROM leavemaster 
                    WHERE leave_status IN ('0','2') 
                    AND company_leavetype_id = company_leavetype.id 
                    AND user_name = '" . $this->session->userdata("user_profile")->user_name . "' 
                    AND (created_at BETWEEN CONCAT(YEAR(now()),CONCAT(CONCAT('-',(company_leavetype.month+1)),'-01 00:00:00')) AND CONCAT(YEAR(DATE_ADD(now(), INTERVAL 1 YEAR)),CONCAT('-',CONCAT((company_leavetype.month)),'-31 23:59:59')))
                        
                ) AS leave_qty
                FROM company_leavetype 
                WHERE company_id = '" . $this->session->userdata("user_profile")->company_id . "'  AND leavetype_id ='" . $this->data['leavetype']->leavetype_id . "' 
                ORDER BY company_leavetype.leavetype_id ASC";
        // echo $sql;
        $this->data['leave'] = $this->db->query($sql)->row();

        $this->load->view("layout/main", $this->data);
    }

    /* Add Data */
    public function save()
    {

        $file_upload = NULL;
        $file_attach = NULL;

        list($approved_by, $approve_fullname, $approve_email) = explode("|", $this->input->post('approved_by'));

        $cc_to = array();
        if (!empty($this->input->post('cc_to'))) {
            foreach ($this->input->post('cc_to') as $cc) {
                $cc_to[] = explode("|", $cc);
            }
        }

        /* Filename => Attach */
        if (!empty($_FILES['files']['name'])) {
            $this->load->library('upload');
            $files_name = $this->session->userdata("user_profile")->company_id . '-' . $this->session->userdata("user_profile")->id . '-' . time();

            $config['upload_path'] =  './upload/leave/';  // โฟลเดอร์ 
            $config['file_name'] = $files_name;  // ชื่อไฟล์ ถ้าไม่กำหนดจะเป็นตามชื่อเดิม $_FILES['files']['name']
            $config['allowed_types'] = 'jpg|png|pdf'; // ปรเเภทไฟล์ 
            $config['max_size']     = '0';  // ขนาดไฟล์ (kb)  0 คือไม่จำกัด ขึ้นกับกำหนดใน php.ini ปกติไม่เกิน 2MB (2,048)
            $config['overwrite']     = true;  // 

            $this->upload->initialize($config);    // เรียกใช้การตั้งค่า  
            $this->upload->do_upload('files'); // ทำการอัพโหลดไฟล์จาก input file ชื่อ files

            if ($this->upload->display_errors()) { // ถ้าเกิดข้อมผิดพลาดในการอัพโหลดไฟล์
                $this->session->set_flashdata('type', 'error');
                $this->session->set_flashdata('msg', 'ERROR [CODE] : ' . $this->upload->display_errors());
                $this->app->write_log('error-' . $this->router->fetch_class() . '-' . $this->router->fetch_method() . '=> ' . $this->session->flashdata('msg') . ': ' . $this->upload->display_errors(), '');
                redirect($this->agent->referrer()); // ย้อนกลับไปหน้าแบบฟอร์ม
                die();
            } else {  // หากไม่มีข้อผิดพลาดใดๆ เกิดข้อ ก็บันทึกข้อมูลส่วนอื่นตามปกติ
                $file_upload = $this->upload->data('file_name');  // ถ้าอัพโหลดได้ เราสามารถเรียกดูข้อมูลไฟล์ที่อัพได้
                $file_attach = './upload/leave/' . $file_upload;
            }
        }

        /* เริ่ม Transactions */
        $this->db->trans_begin();

        $data = array(
            'company_id' => $this->session->userdata("user_profile")->company_id,
            'user_id' => $this->session->userdata("user_profile")->id,
            'user_name' => $this->session->userdata("user_profile")->user_name,
            'leave_status' => $this->input->post('leave_status'),
            'company_leavetype_id' => $this->input->post('company_leavetype_id'),
            'period' => $this->input->post('period'),
            'leave_qty' => $this->input->post('leave_qty'),
            'leave_from' => $this->input->post('leave_from'),
            'leave_to' => $this->input->post('leave_to'),
            'leave_tel' => $this->input->post('leave_tel'),
            'leave_address' => $this->input->post('leave_address'),
            'leave_remark' => $this->input->post('leave_remark'),
            'approved_by' => $approved_by,
            'file_upload' => $file_upload,
            'created_by' => $this->session->userdata("user_profile")->user_name,
            'created_at' => date('Y-m-d H:i:s'),
            'record_status' => 'N'
        );
        if (!$this->db->insert('leavemaster', $data)) {
            $db_error = $this->db->error();
            $this->session->set_flashdata('type', 'error');
            $this->session->set_flashdata('msg', 'ERROR [CODE] : ' . $db_error['code']);
        } else {
            $this->session->set_flashdata('type', 'success');
            $this->session->set_flashdata('msg', 'Completed');
            $this->app->write_log($this->router->fetch_class() . '-' . $this->router->fetch_method() . '=> ' . $this->session->flashdata('msg'), json_encode($this->db->last_query()));
        }

        /* ถ้ามีการผิดพลาดให้ทำการ Rollback ข้อมูล */
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            /* Create Log Data  */
            $this->app->write_log('error-' . $this->router->fetch_class() . '-' . $this->router->fetch_method() . '=> ' . $this->session->flashdata('msg') . ': ' . $db_error['message'], json_encode($this->db->last_query()));
        } else {
            /* ถ้าไม่มีข้อผิดพลาดให้ยืนยันการทำงาน */
            $this->db->trans_commit();
            /*
        send mail
        load mail library
         */
            $this->load->helper('mail');

            $html = "
            <p>ผู้ขอลา : " . $this->session->userdata("user_profile")->user_fullname . "</p>
            <p>แผนก/ฝ่าย : " . $this->session->userdata("user_profile")->division_name . "/" . $this->session->userdata("user_profile")->section_name . "</p>
            <p>วันที่ลา : [" . $this->input->post('period') . "] " . $this->input->post('leave_from') . " ถึง " . $this->input->post('leave_to') . " (" . $this->input->post('leave_qty') . " วัน) </p>
            <p>เบอร์โทรติดต่อ : " . $this->input->post('leave_tel') . "</p>
            <p>ที่อยู่ (สามารถติดต่อได้) : " . $this->input->post('leave_address') . "</p>
            <p>ลาเนื่องจาก :  " . $this->input->post('leave_remark') . "</p>
            <p>กรุณากดลิงก์เพื่อทำรายการอนุมัติใบลาเพื่ออนุมัติ : <a href='" . base_url('leave/manage') . "'>link</a></p>
            ";
            send_mail($approve_email, $approve_fullname, $cc_to, "แจ้งเตือนมีผู้ทำการขอลา", $html, $file_attach);
        }
        redirect('leave/manage');
    }


    /* <!-- ============================================================== -->
      <!-- Function -->
      <!-- ============================================================== --> */

    /* get updated row */
    public function timestamp()
    {
        echo json_encode(@$this->app->last_updated_table("leavemaster", "AND user_name ='" . $this->session->userdata("user_profile")->user_name . "'"));
    }
}
