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

class Auth extends MX_Controller
{

    public function __construct()
    {
        parent::__construct();

        $this->db->query('SET SESSION sql_mode = ""');

        $this->load->model(array(
            'auth_model'
        ));

        $this->load->helper('captcha');
    }

    public function index()
    {
        if ($this->session->userdata('isLogIn') && $this->session->userdata('two_factors') == '1') {
            if ($this->session->userdata('login_status') != '1'){
                redirect('dashboard/home/setNewPassword');
            }else{
                redirect('dashboard/home');
            }

        }
        $data['title'] = display('login');

        $validation_code = $this->input->post('validation_code', true);

        if ($validation_code) {
            $validData = array(
                'session_id' => session_id(),
                'two_factors' => $validation_code,
            );
            $validateuser = $this->auth_model->check_auth_twofactor($validData);

            if ($validateuser->num_rows() > 0) {
                $sData = array(
                    'isLogIn' => true,
                    'two_factors' => '1',
                );
                $this->session->set_userdata($sData);

                if ($this->session->userdata('login_status') != '1'){
                    redirect('dashboard/home/setNewPassword');
                }else{
                    $this->session->set_flashdata('message', display('welcome_back') . ' ' . $this->session->userdata('fullname'));
                    redirect('dashboard/home');
                }
            } else {
                $this->session->set_flashdata('exception', 'Invalid code');
                redirect('login?validation=true&ngbdgfennsd=' . session_id());
            }
        }

        #-------------------------------------#
        $this->form_validation->set_rules('email', display('email'), 'required|valid_email|max_length[100]|trim');
        $this->form_validation->set_rules('password', display('password'), 'required|max_length[32]|md5|trim');
        $this->form_validation->set_rules(
            'captcha', display('captcha'),
            array(
                'matches[captcha]',
                function ($captcha) {
                    $oldCaptcha = $this->session->userdata('captcha');
                    if ($captcha == $oldCaptcha) {
                        return true;
                    }
                }
            )
        );

        #-------------------------------------#
        $data['user'] = (object)$userData = array(
            'email' => $this->input->post('email', true),
            'password' => $this->input->post('password', true),
        );

        #-------------------------------------#
        if ($this->form_validation->run()) {

            $this->session->unset_userdata('captcha');

            $user = $this->auth_model->checkUser($userData);

            if ($user->num_rows() > 0) {

                $checkPermission = $this->auth_model->userPermission2($user->row()->id);
                if ($checkPermission != NULL) {
                    $permission = array();
                    $permission1 = array();
                    if (!empty($checkPermission)) {
                        foreach ($checkPermission as $value) {
                            $permission[$value->module] = array(
                                'create' => $value->create,
                                'read' => $value->read,
                                'update' => $value->update,
                                'delete' => $value->delete
                            );

                            $permission1[$value->menu_title] = array(
                                'create' => $value->create,
                                'read' => $value->read,
                                'update' => $value->update,
                                'delete' => $value->delete
                            );
                        }
                    }
                }

                if ($user->row()->is_admin == 2) {
                    $row = $this->db->select('client_id,client_email')->where('client_email', $user->row()->email)->get('setup_client_tbl')->row();
                }
                $employee_info = $this->db->select('employee_id,first_name,last_name,is_super_visor')->from('employee_history')->where('email', $user->row()->email)->get()->row();
                $sData = array(
                    'isAdmin' => (($user->row()->is_admin == 1) ? true : false),
                    'user_type' => $user->row()->is_admin,
                    'id' => $user->row()->id,
                    'client_id' => @$row->client_id,
                    'fullname' => $user->row()->fullname,
                    'user_level' => $user->row()->user_level,
                    'email' => $user->row()->email,
                    'image' => $user->row()->image,
                    'last_login' => $user->row()->last_login,
                    'last_logout' => $user->row()->last_logout,
                    'ip_address' => $user->row()->ip_address,
                    'employee_id' => $employee_info->employee_id,
                    'first_name' => $employee_info->first_name,
                    'last_name' => $employee_info->last_name,
                    'supervisor' => $employee_info->is_super_visor,
                    'permission' => json_encode(@$permission),
                    'label_permission' => json_encode(@$permission1),
                    'login_status' => $user->row()->login_status,
                );


                //store date to session
                $this->session->set_userdata($sData);
                //update database status
                $this->auth_model->last_login();

                // Two factor Authentication
                if ($this->session->userdata('two_factors') != '1') {
                    $six_digit_random_number = random_int(100000, 999999);

                    $this->sendEmail($six_digit_random_number, $user->row()->email);

                    $facData = array(
                        'session_id' => session_id(),
                        'two_factor_token' => $six_digit_random_number,
                    );

                    $set_two_factor = $this->auth_model->set_two_factor($facData);
                    if ($set_two_factor) {
                        redirect('login?validation=true&ngbdgfennsd=' . session_id());
                    }
                }

                if ($this->session->userdata('login_status') != '1'){
                    redirect('dashboard/home/setNewPassword');
                }else{
                    $this->session->set_flashdata('message', display('welcome_back') . ' ' . $user->row()->fullname);
                    redirect('dashboard/home');
                }


            } else {
                $this->session->set_flashdata('exception', display('incorrect_email_or_password'));
                redirect('login');
            }

        } else {

            $captcha = create_captcha(array(
                'img_path' => './assets/img/captcha/',
                'img_url' => base_url('assets/img/captcha/'),
                'font_path' => './assets/fonts/captcha.ttf',
                'img_width' => '300',
                'img_height' => 64,
                'expiration' => 600, //5 min
                'word_length' => 4,
                'font_size' => 26,
                'img_id' => 'Imageid',
                'pool' => '0123456789abcdefghijklmnopqrstuvwxyz',

                // White background and border, black text and red grid
                'colors' => array(
                    'background' => array(255, 255, 255),
                    'border' => array(228, 229, 231),
                    'text' => array(49, 141, 1),
                    'grid' => array(241, 243, 246)
                )
            ));
            $data['captcha_word'] = $captcha['word'];
            $data['captcha_image'] = $captcha['image'];
            $this->session->set_userdata('captcha', $captcha['word']);

            echo Modules::run('template/login', $data);
        }
    }

    public function logout()
    {
        //update database status
        $this->auth_model->last_logout();
        //destroy session
        $this->session->sess_destroy();
        redirect('login');
    }

    /*
 |--------------------------------------------------------
 | Finger print Device information
 |--------------------------------------------------------
 */
    public function deviceData()
    {
        return $this->db->select('*')->from('deviceinfo')->get()->row();
    }

    public function sendEmail($six_digit_random_number, $user_email)
    {
        //---------------------------------------------------------------
        $from_email = FROM_EMAIL;
        $to_email = $user_email;

        //Load email library
        $this->load->library('email');

        $this->email->from($from_email, 'DynaTuners HRM');
        $this->email->to($to_email);
        $this->email->subject('DynaTuners HRM Authentication Code');
        $this->email->message('Your Authentication Code: ' . $six_digit_random_number);

        //Send mail
        if ($this->email->send())
            $this->session->set_flashdata("email_sent", "Email sent successfully.");
        else
            $this->session->set_flashdata("email_sent", "Error in sending Email.");

        ///-------------------------------------------------
    }
}
