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

class Auth extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->model('Auth_model', 'auth');
        $this->load->model('Admin_model', 'admin');
    }

    private function _has_login()
    {
        if ($this->session->has_userdata('login_session')) {
            redirect('dashboard');
        }
    }

    public function index()
    {
        $this->_has_login();

        $this->form_validation->set_rules('username', 'Username', 'required|trim');
        $this->form_validation->set_rules('password', 'Password', 'required|trim');

        if ($this->form_validation->run() == false) {
            $data['title'] = 'Login Panel';
            $this->template->load('templates/auth', 'auth/login', $data);
        } else {
            $input = $this->input->post(null, true);


            $user_db = $this->auth->userdata($input['username']);

            if ($user_db['role'] != 'admin') {
                set_pesan('Acceso denegado', false);
                redirect('login');
            }

        
            $check_username = $this->auth->check_username($input['username']);

            if ($check_username > 0) {
                
                $password = $this->auth->get_password($input['username']);
                
                if (password_verify($input['password'], $password)) {

                    $user_db = $this->auth->userdata($input['username']);

                    if ($user_db['is_active'] != 1) {
                        set_pesan('Su cuenta de usuario esta bloqueada, por favor contacte al administrador.', false);
                        redirect('login');
                    } else {

                        $get_entidad = $this->auth->get_entidad( $user_db['id_entidad'] );


                        // SET SESSTION ENVIRONMET
                        $userdata = [
                            'user'          => $user_db['id_user'],
                            'user_name'     => $user_db['username'],
                            'role'          => $user_db['role'],
                            'timestamp'     => time(),
                            'id_entidad'    => $user_db['id_entidad'],
                            'entidad'       => $get_entidad
                        ];

                        $this->session->set_userdata('login_session', $userdata);

                        //$last_login = $this->admin->getLastLoginInfo($input['username']);
                        //log_message('error', $last_login );

                        //SAVE LAST LOGIN LOG                        
                        $input_last_login = [
                            'userId'            => $user_db['username'],
                            'sessionData'       => json_encode($userdata),
                            'machineIp'         => $_SERVER['REMOTE_ADDR'],
                            'userAgent'         => getBrowserAgent(),
                            'agentString'       => $this->agent->agent_string(),
                            'platform'          => $this->agent->platform(),
                            'createdDtm'        => date('Y-m-d H:i:s'),
                            'usertType'         => $user_db['role']
                        ];
                        
                        $this->admin->insert('tbl_last_login', $input_last_login);

                        redirect('dashboard');
                    }
                } else {
                    set_pesan('Usuario o contraseña incorrectos', false);
                    redirect('auth');
                }
            } else {
                set_pesan('Usuario o contraseña incorrectos', false);
                redirect('auth');
            }
        }
    }

    public function logout()
    {
        $this->session->unset_userdata('login_session');

        //set_pesan('Logged Out Successfully!');
        redirect('auth');
    }

    public function register()
    {
        $this->form_validation->set_rules('username', 'Username', 'required|trim|is_unique[tbl_user.username]|alpha_numeric');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[3]|trim');
        $this->form_validation->set_rules('password2', 'Repetir Password', 'matches[password]|trim');
        $this->form_validation->set_rules('name', 'Nombre', 'required|trim');
        $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[tbl_user.email]');
        $this->form_validation->set_rules('no_telp', 'Teléfono', 'required|trim');

        if ($this->form_validation->run() == false) {
            $data['title'] = 'Create Account';
            $this->template->load('templates/auth', 'auth/register', $data);
        } else {
            $input = $this->input->post(null, true);
            unset($input['password2']);
            $input['password']      = password_hash($input['password'], PASSWORD_DEFAULT);
            $input['role']          = 'abogado';
            $input['foto']          = 'user.png';
            $input['is_active']     = 0;
            $input['created_at']    = time();

            $query = $this->admin->insert('tbl_user', $input);
            if ($query) {
                set_pesan('Please contact admin to activate your account');
                redirect('login');
            } else {
                set_pesan('Something went wrong', false);
                redirect('register');
            }
        }
    }
}
