<?php

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

class Manage 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()
    {
        $this->data['navbar'] = 'layout/navbar';
        $this->data['sidebar'] = 'layout/sidebar';
        $this->data['footer'] = 'layout/footer';
        $this->data['page'] = 'leave/manage';
        $this->load->view("layout/main", $this->data);
    }

    /* Get Data to List Table */

    public function ajax_list()
    {
        header('Access-Control-Allow-Origin: *');
        ini_set('max_execution_time', 300);
        $sql = "SELECT leavemaster.* "
            . ", sys_user.user_name "
            . ", sys_user.user_fullname "
            . ", title.title_name "
            . ", manage.manage_name "
            . ", company.company_name "
            . ", division.division_name "
            . ", section.section_name "
            . ", position.position_name "
            . ", sys_group.group_name, sys_group.group_description "
            . "FROM sys_user "
            . "LEFT JOIN company ON sys_user.company_id = company.id "
            . "LEFT JOIN title ON sys_user.title_id = title.id "
            . "LEFT JOIN manage ON sys_user.manage_id = manage.id "
            . "LEFT JOIN division ON sys_user.division_id = division.id "
            . "LEFT JOIN section ON sys_user.section_id = section.id "
            . "LEFT JOIN position ON sys_user.position_id = position.id "
            . "LEFT JOIN sys_group ON sys_user.group_id = sys_group.id "
            . "INNER JOIN leavemaster ON leavemaster.user_name = sys_user.user_name "
            . "WHERE sys_user.record_status = 'N' "
            . "ORDER BY leavemaster.created_at ASC";
        $data['data'] = $this->db->query($sql)->result();
        echo json_encode($data);
    }

    /* Get Data to Item */

    public function ajax_data()
    {
        header('Access-Control-Allow-Origin: *');
        ini_set('max_execution_time', 300);
        $id = $this->input->post('id');
        $sql = "SELECT * FROM leavemaster WHERE record_status='N' AND id = '" . $id . "'";
        $data = $this->db->query($sql)->row();
        echo json_encode($data);
    }

    /* Edit Data */
    public function edit()
    {
        /* เริ่ม Transactions */
        $this->db->trans_begin();

        $id = $this->input->post('id');
        $data = array(
            'leavemaster_name' => $this->input->post('leavemaster_name'),
            'leavemaster_email' => $this->input->post('leavemaster_email'),
            'leavemaster_description' => $this->input->post('leavemaster_description'),
            'updated_by' => $this->session->userdata("user_profile")->user_name,
            'updated_at' => date('Y-m-d H:i:s')
        );

        $this->db->where('id', $id);
        if (!$this->db->update('leavemaster', $data)) {
            $db_error = $this->db->error();
            $this->session->set_flashdata('type', 'error');
            $this->session->set_flashdata('msg', 'ERROR [CODE] : ' . $db_error['code']);
            /* 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->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($this->agent->referrer());
    }

    /* Delete Data */
    public function delete()
    {
        /* เริ่ม Transactions */
        $this->db->trans_begin();

        $id = urldecode($this->uri->segment(4));
        $this->db->where('id', $id);
        if (!$this->db->delete('leavemaster')) {
            $db_error = $this->db->error();
            $this->session->set_flashdata('type', 'error');
            $this->session->set_flashdata('msg', 'ERROR [CODE] : ' . $db_error['code']);
            /* 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->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($this->agent->referrer());
    }

    /* <!-- ============================================================== -->
      <!-- 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 . "'"));
    }

    function ajax_exist()
    {
        /* Check Exist Variable name */
        header('Access-Control-Allow-Origin: *');
        ini_set('max_execution_time', 300);
        $leavemaster = $_REQUEST["leavemaster"];
        $sql = "SELECT leavemaster FROM leavemaster WHERE record_status='N' AND leavemaster ='" . trim($leavemaster) . "'";
        if ($this->db->query($sql)->num_rows() == 0) {
            echo "true";
        } else {
            echo "false";
        }
    }
}
