<?php

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

class Main extends CI_Controller
{

    function __construct()
    {
        /* Call the Model constructor */
        parent::__construct();
        /* Get System Variable */
        $this->data['var'] = $this->app->get_var_sys();

        if (empty($this->session->userdata("user_profile")->id)) {
            redirect('authen', 'refresh');
            exit();
        }
    }

    /* กลับไปหน้าหลักของผู้ใช้งาน */
    public function index()
    {
        $this->data['navbar'] = 'layout/navbar';
        $this->data['sidebar'] = 'layout/sidebar';
        $this->data['footer'] = 'layout/footer';
        $this->data['page'] = 'layout/dashboard';
        $this->load->view("layout/main", $this->data);
    }

    /* ดูข้อมูลกิจกรรมของผู้ใช้งานปัจจุบัน */
    public function activity_log()
    {

        $this->data['navbar'] = 'layout/navbar';
        $this->data['sidebar'] = 'layout/sidebar';
        $this->data['footer'] = 'layout/footer';
        $this->data['page'] = 'activity_log';
        $this->load->view("layout/main", $this->data);
    }
    public function activity_log_data()
    {
        header('Access-Control-Allow-Origin: *');
        ini_set('max_execution_time', 300);
        $sql = "SELECT * FROM sys_log ";
        $sql .= "WHERE user_name = '" . $this->session->userdata("user_profile")->user_name . "' ";
        $sql .= "AND company_id = '" . $this->session->userdata("user_profile")->company_id . "'";
        $sql .= "ORDER BY datetime DESC";
        $data['data'] = $this->db->query($sql)->result();
        echo json_encode($data);
    }

    /* ดูข้อมูลโปรไฟล์ของผู้ใช้งาน */
    public function profile()
    {
        $this->data['navbar'] = 'layout/navbar';
        $this->data['sidebar'] = 'layout/sidebar';
        $this->data['footer'] = 'layout/footer';
        $this->data['page'] = 'profile';
        $this->load->view("layout/main", $this->data);
    }

    public function profile_edit()
    {

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

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

        /* ดึงรูปแล้วเข้ารหัสแบบ Base64 */
        $file_tmp = $_FILES['user_pic']['tmp_name'];
        $type = mime_content_type($_FILES['user_pic']['tmp_name']);
        $pic = file_get_contents($file_tmp);
        $base64_pic = 'data:' . $type . ';base64,' . base64_encode($pic);

        if (!empty($file_tmp)) {
            $data['user_pic'] = $base64_pic;
        }

        $this->db->where('id', $this->session->userdata("user_profile")->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']);
            /* 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 {
            /* อัพเดททันที แต่จะมีผลทำให้ต้องกลับไปหน้า login ทันที
            $sql = "SELECT sys_user.* "
                . ", 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 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 "
                . "WHERE sys_user.user_name = '" . $this->session->userdata("user_profile")->id . "' "
                . "AND sys_user.record_status = 'N' ";
            $query = $this->db->query($sql);
            $data['user_profile'] = $query->row();
            $this->session->set_userdata($data);
            */

            $this->session->set_flashdata('type', 'success');
            $this->session->set_flashdata('msg', 'Completed<br>Please logout to update session.');
            $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());
    }

    public function change_password()
    {

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

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

        $this->db->where('id', $this->session->userdata("user_profile")->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']);
            /* 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<br>Please logout to update session.');
            $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 -->
      <!-- ============================================================== --> */


    /* เข้ารหัส ID */
    function encrypt_id()
    {
        echo $this->app->encrypt_segment($this->uri->segment(3));
    }

    /* ถอดรหัส ID */
    function decrypt_id()
    {
        echo $this->app->decrypt_segment($this->uri->segment(3));
    }
}
