<?php

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

class Section 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("section", ($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'] = 'sys/section';
        $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 section.*, company.company_name, division.division_name 
        FROM section 
        INNER JOIN company ON section.company_id = company.id 
        LEFT JOIN division ON division.id = section.division_id 
        WHERE section.record_status='N' ";
        if ($this->session->userdata("user_profile")->id !== '1') {
            $sql .= "AND section.company_id = '" . $this->session->userdata("user_profile")->company_id . "' ";
        }
        $sql .= "ORDER BY division.sort, section.sort 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 section WHERE record_status='N' AND id = '" . $id . "'";
        $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')
        );
        $section_name = $this->input->post('section_name');
        $this->db->where('section_name', $section_name);
        $this->db->update('section', $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'),
            'company_id' => $this->input->post('company_id'),
            'division_id' => $this->input->post('division_id'),
            'section_name' => $this->input->post('section_name'),
            'section_description' => $this->input->post('section_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('section', $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();

        $id = $this->input->post('id');
        $data = array(
            'company_id' => $this->input->post('company_id'),
            'division_id' => $this->input->post('division_id'),
            'section_name' => $this->input->post('section_name'),
            'section_description' => $this->input->post('section_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('section', $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('section')) {
            $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('section', $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("section", ($this->session->userdata("user_profile")->id !== '1' ? "AND company_id ='" . $this->session->userdata("user_profile")->company_id . "'" : "")));
    }
}
