<?php

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

class Leave_qty 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("set_leave_qty", ($this->session->userdata("user_profile")->id !== '1' ? "AND company_id ='" . $this->session->userdata("user_profile")->company_id . "'" : ""));
        }
    }

    public function index()
    {
        $this->data['navbar'] = 'layout/navbar';
        $this->data['sidebar'] = 'layout/sidebar';
        $this->data['footer'] = 'layout/footer';
        $this->data['page'] = 'setting/set_leave_qty';
        $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 DISTINCT set_leave_qty.company_id, set_leave_qty.datetime, set_leave_qty.leave_qty_description, company.company_name FROM set_leave_qty 
        INNER JOIN company ON set_leave_qty.company_id = company.id 
        WHERE set_leave_qty.record_status='N' ";
        if ($this->session->userdata("user_profile")->id !== '1') {
            $sql .= "AND set_leave_qty.company_id = '" . $this->session->userdata("user_profile")->company_id . "' ";
        }
        $sql .= "ORDER BY set_leave_qty.company_id ASC,set_leave_qty.datetime DESC";
        $data['data'] = $this->db->query($sql)->result();
        echo json_encode($data);
    }


    /* Add Data */
    public function add()
    {
        /* เริ่ม Transactions */
        $this->db->trans_begin();
        $datetime = date('Y-m-d H:i:s');
        $company_id = $this->input->post('company_id');
        $leave_qty_description = $this->input->post('leave_qty_description');
        $created_by = $this->session->userdata("user_profile")->user_name;

        $sql = "INSERT INTO set_leave_qty (company_id, datetime, user_name, leave_qty, leave_qty_description, created_by, created_at)
        SELECT '$company_id', '$datetime', user_name, leave_qty, '$leave_qty_description', '$created_by', '$datetime'
        FROM sys_user
        WHERE company_id = $company_id";
        $this->db->query($sql);

        $data = array(

            'leave_qty' => 0,
            'updated_by' => $this->session->userdata("user_profile")->user_name,
            'updated_at' => date('Y-m-d H:i:s')
        );
        $this->db->where('company_id', $company_id);
        if (!$this->db->update('sys_user', $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($this->agent->referrer());
    }

    /* Restore Data */
    public function restore()
    {
        /* เริ่ม Transactions */
        $this->db->trans_begin();
        $company_id = urldecode($this->uri->segment(4));
        $datetime = urldecode($this->uri->segment(5));
        $sql = "SELECT user_name, leave_qty FROM set_leave_qty 
        WHERE company_id = '$company_id' AND datetime ='$datetime' ";

        foreach ($this->db->query($sql)->result() as $item) {
            $data = array(
                'leave_qty' => $item->leave_qty,
                'updated_by' => $this->session->userdata("user_profile")->user_name,
                'updated_at' => date('Y-m-d H:i:s')
            );
            $this->db->where('company_id', $company_id);
            $this->db->where('user_name', $item->user_name);
            if (!$this->db->update('sys_user', $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->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()));
            $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('datetime', $id);
        if (!$this->db->delete('set_leave_qty')) {
            $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());
    }

    /* Change Active Data */

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

        $status = explode('.', $this->uri->segment(4));
        $data = array(
            'is_active' => ($status[1] == 1 ? 0 : 1),
            'updated_by' => $this->session->userdata("user_profile")->user_name,
            'updated_at' => date('Y-m-d H:i:s')
        );
        $id = $status[0];
        $this->db->where('id', $id);
        if (!$this->db->update('set_leave_qty', $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());
    }

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

    /* get updated row */
    public function timestamp()
    {
        echo json_encode($this->app->last_updated_table("set_leave_qty", ($this->session->userdata("user_profile")->id !== '1' ? "AND company_id ='" . $this->session->userdata("user_profile")->company_id . "'" : "")));
    }
}
