<?php

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

class User 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_user");
        }
    }

    public function index()
    {
        $this->data['navbar'] = 'layout/navbar';
        $this->data['sidebar'] = 'layout/sidebar';
        $this->data['footer'] = 'layout/footer';
        $this->data['page'] = 'sys/user';
        $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 sys_user.* "
            . ", title.title_name "
            . ", branch.branch_name "
            . ", manage.manage_name "
            . ", 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 title ON sys_user.title_id = title.id "
            . "LEFT JOIN branch ON sys_user.branch_id = branch.id "
            . "LEFT JOIN manage ON sys_user.manage_id = manage.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.record_status = 'N' ";
        //echo $sql;
        $data['data'] = $this->db->query($sql)->result();
        /* Init $items NULL */
        $items['data'] = array();
        foreach ($data['data'] as $key => $item) {
            $items['data'][$key]['id'] = $item->id;
            $items['data'][$key]['user_pic'] = '<img class="profile-pic-list" data-pic="' . $item->id . '" src="' . $this->app->user_pic($item->id) . '"style="width: 48px; height: 48px;">';
            $items['data'][$key]['company_id'] = $item->company_id;
            $items['data'][$key]['user_name'] = $item->user_name;
            $items['data'][$key]['hash_password'] = $item->hash_password;
            $items['data'][$key]['user_password'] = $item->user_password;
            $items['data'][$key]['title_id'] = $item->title_id;
            $items['data'][$key]['level'] = $item->level;
            $items['data'][$key]['user_fullname'] = $item->user_fullname;
            $items['data'][$key]['section_id'] = $item->section_id;
            $items['data'][$key]['division_id'] = $item->division_id;
            $items['data'][$key]['position_id'] = $item->position_id;
            $items['data'][$key]['email'] = $item->email;
            $items['data'][$key]['email_1'] = $item->email_1;
            $items['data'][$key]['email_2'] = $item->email_2;
            $items['data'][$key]['email_3'] = $item->email_3;
            $items['data'][$key]['group_id'] = $item->group_id;
            $items['data'][$key]['is_active'] = $item->is_active;
            $items['data'][$key]['title_name'] = $item->title_name;
            $items['data'][$key]['branch_name'] = $item->branch_name;
            $items['data'][$key]['manage_name'] = $item->manage_name;
            $items['data'][$key]['company_name'] = $item->company_name;
            $items['data'][$key]['division_name'] = $item->division_name;
            $items['data'][$key]['section_name'] = (empty($item->section_name) ? '-' : $item->section_name);
            $items['data'][$key]['position_name'] = $item->position_name;
            $items['data'][$key]['group_name'] = $item->group_name;
            $items['data'][$key]['created_by'] = $item->created_by;
        }

        $items['sql'] = $sql;
        echo json_encode($items);
    }

    /* 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 sys_user WHERE record_status='N' AND id = '" . $id . "'";
        $data = $this->db->query($sql)->row();
        $data->user_pic =  $this->app->user_pic($data->id);

        echo json_encode($data);
    }


    /* Add Data */

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

        $data = array(
            'company_id' => $this->input->post('company_id'),
            'user_name' => $this->input->post('user_name'),
            'user_fullname' => $this->input->post('user_fullname'),
            'title_id' => $this->input->post('title_id'),
            'branch_id' => $this->input->post('branch_id'),
            'manage_id' => $this->input->post('manage_id'),
            'section_id' => $this->input->post('section_id'),
            'division_id' => $this->input->post('division_id'),
            'position_id' => $this->input->post('position_id'),
            'work_date' => $this->input->post('work_date'),
            'leave_qty' => $this->input->post('leave_qty'),
            'email' => $this->input->post('email'),
            'group_id' => $this->input->post('group_id'),
            'created_by' => $this->session->userdata("user_profile")->user_name,
            'created_at' => date('Y-m-d H:i:s'),
            'record_status' => 'N'
        );

        /* ดึงรูปแล้วเข้ารหัสแบบ 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;
        }
        if (!empty(trim($this->input->post('user_password')))) {
            $user_password = trim($this->input->post('user_password'));
            $data['user_password'] = md5($user_password);
        }


        if (!$this->db->insert('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());
    }

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

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

        /* ดึงรูปแล้วเข้ารหัสแบบ 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;
        }
        if (!empty(trim($this->input->post('user_password')))) {
            $user_password = trim($this->input->post('user_password'));
            $data['user_password'] = md5($user_password);
        }

        $this->db->where('id', $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');
            $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('sys_user')) {
            $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('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->db->trans_commit();
        }
        redirect($this->agent->referrer());
    }


    public function resetPassword()
    {
        $id = urldecode($this->uri->segment(4));
        $sql = "SELECT hash_password FROM sys_user WHERE id ='" . trim($id) . "'";
        $hash_password = $this->db->query($sql)->row()->hash_password;

        $data = array(
            'user_password' => $hash_password,
            'updated_by' => $this->session->userdata("user_profile")->username,
            'updated_at' => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $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()));
        }
        redirect($this->agent->referrer());
    }

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

    /* get updated row */
    public function timestamp()
    {
        echo json_encode($this->app->last_updated_table("sys_user"));
    }

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