<?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();

        $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 NOT IN ('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)),'-30 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()
    {

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

        $data = array(
            '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'),
            '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();
        }

        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 . "'"));
    }

}
