<?php

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

class Authen extends CI_Controller
{

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

    public function index()
    {
        if (!empty($this->session->userdata("user_profile")->id)) {
            redirect(base_url());
            exit();
        } else {
            $this->load->view("login", $this->data);
        }
    }

    public function login()
    {

        /* Clear Session */
        $this->session->unset_userdata(array('user_profile', 'user_permission', 'token'));

        $username = trim($this->input->post('user_name'));
        $passwd = trim($this->input->post('user_password'));

        /* Pass user_name to form login */
        $this->session->set_flashdata('user_name', $username);

        $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.user_name = '" . $username . "' "
            . "AND sys_user.record_status = 'N' ";
        $query = $this->db->query($sql);
        if ($query) {
            $nrows = $query->num_rows();
            if ($nrows > 0) {
                $user_profile = $query->row();
                if ($user_profile->is_active == 1) {
                    $query_passwd = $this->db->query("SELECT * FROM sys_user WHERE id ='" . $user_profile->id . "' AND user_password = '" . md5($passwd) . "' AND record_status='N' ");
                    $nrows_passwd = $query_passwd->num_rows();

                    $data['user_profile'] = $user_profile;
                    /* Set token For Session */
                    /* ตั้งค่าโทเค็นสำหรับเซสชันผู้ใช้ปัจจุบัน */
                    $data['token'] = strtotime(date("Y-m-d H:i:s"));

                    if ($nrows_passwd > 0) {
                        $this->session->set_userdata($data);
                        $this->app->write_log('Authen => Logged');
                    } else {
                        $this->session->set_flashdata('type', 'warning');
                        $this->session->set_flashdata('msg', ' <u>' . $username . '</u> and password not correct.');
                        $this->app->write_log('error-authen-password=> ' . $this->session->flashdata('msg'));
                    }
                } else {
                    $this->session->set_flashdata('type', 'warning');
                    $this->session->set_flashdata('msg', '<u>' . $username . '</u> has disabled.');
                    $this->app->write_log('error-authen-disabled=> ' . $this->session->flashdata('msg'));
                }
            } else {
                $this->session->set_flashdata('type', 'error');
                $this->session->set_flashdata('msg', '<u>' . $username . '</u> not found.');
                $this->app->write_log('error-authen-username=> ' . $this->session->flashdata('msg'));
            }
        } else {
            $this->session->set_flashdata('type', 'error');
            $this->session->set_flashdata('msg', 'Synax error.');
            $this->app->write_log('error-authen-command-error=> ' . $this->session->flashdata('msg'));
        }
        if (!empty($this->session->userdata("user_profile")->id)) {
            redirect(base_url());
        } else {
            redirect(base_url("authen"));
        }
    }


    public function register()
    {
        $this->load->view("register", $this->data);
    }


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

        $data = array(
            'company_id' => $this->input->post('company_id'),
            'user_fullname' => $this->input->post('user_fullname'),
            'division_id' => $this->input->post('division_id'),
            'section_id' => $this->input->post('section_id'),
            'position_id' => $this->input->post('position_id'),
            'email' => $this->input->post('user_email'),
            'user_name' => $this->input->post('user_name'),
            'hash_password' => md5($this->input->post('user_password')),
            'user_password' => md5($this->input->post('user_password')),
            'is_active' => 0,
            'group_id' => 2,
            'created_by' => '[Module:Register]',
            'created_at' => date('Y-m-d H:i:s'),
            'record_status' => 'N'
        );
        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(base_url());
    }

    public function logout()
    {
        $this->app->write_log('Authen => Logged Out');
        $this->session->unset_userdata(array('user_profile', 'user_permission', 'token'));
        redirect(base_url());
    }

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

    function ajax_user_data()
    {
        /* Check Exist Variable name */
        header('Access-Control-Allow-Origin: *');
        ini_set('max_execution_time', 300);
        $user_name = $this->input->post('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";
        }
    }
}
