<?php

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

class Variable 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("sys_variable");
        }
    }

    public function index()
    {
        $this->data['navbar'] = 'layout/navbar';
        $this->data['sidebar'] = 'layout/sidebar';
        $this->data['footer'] = 'layout/footer';
        $this->data['page'] = 'sys/variable';
        $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 * FROM sys_variable WHERE record_status='N' ORDER BY sort ASC";
        $data['data'] = $this->db->query($sql)->result();
        /* Init $items NULL */
        $items['data'] = array();
        foreach ($data['data'] as $key => $item) {
            $items['data'][$key]['variable_name'] = $item->variable_name;
            $items['data'][$key]['variable_description'] = $item->variable_description;
            $items['data'][$key]['is_active'] = $item->is_active;
            $items['data'][$key]['created_by'] = $item->created_by;
        }
        echo json_encode($items);
    }

    /* Get Data to Item */

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

    /* Sort Data List Table */

    function sort()
    {
        $data = array(
            'sort' => $this->input->post('newPos'),
            'updated_by' => $this->session->userdata("user_profile")->user_name,
            'updated_at' => date('Y-m-d H:i:s')
        );
        $variable_name = $this->input->post('variable_name');
        $this->db->where('variable_name', $variable_name);
        $this->db->update('sys_variable', $data);
        $this->app->write_log('Config => Sort data', json_encode($this->db->last_query()));
    }

    /* Add Data */

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

        $data = array(
            'sort' => $this->input->post('sort'),
            'variable_name' => $this->input->post('variable_name'),
            'variable_description' => $this->input->post('variable_description'),
            '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('sys_variable', $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());
    }

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

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

        $this->db->where('variable_name', $variable_name);
        if (!$this->db->update('sys_variable', $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();

        $variable_name = urldecode($this->uri->segment(4));
        $this->db->where('variable_name', $variable_name);
        if (!$this->db->delete('sys_variable')) {
            $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')
        );
        $variable_name = $status[0];
        $this->db->where('variable_name', $variable_name);
        if (!$this->db->update('sys_variable', $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("sys_variable"));
    }


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