<?php

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

class Branch 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("branch", ($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/branch';
        $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 branch.*, company.company_name FROM branch 
        INNER JOIN company ON branch.company_id = company.id 
        WHERE branch.record_status='N' ";
        if ($this->session->userdata("user_profile")->id !== '1') {
            $sql .= "AND branch.company_id = '" . $this->session->userdata("user_profile")->company_id . "' ";
        }
        $sql .= "ORDER BY 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 branch 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')
        );
        $id = $this->input->post('id');
        $this->db->where('id', $id);
        $this->db->update('branch', $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'),
            'branch_name' => $this->input->post('branch_name'),
            'branch_description' => $this->input->post('branch_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('branch', $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'),
            'branch_name' => $this->input->post('branch_name'),
            'branch_description' => $this->input->post('branch_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('branch', $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('branch')) {
            $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('branch', $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("branch", ($this->session->userdata("user_profile")->id !== '1' ? "AND company_id ='" . $this->session->userdata("user_profile")->company_id . "'" : "")));
    }
}
