<?php

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

/* * ***************Auth.php**********************************
 * @product name    : Hospital Management System
 * @type            : Class
 * @class name      : Auth
 * @description     : This class used to handle user authentication functionality 
 *                    of the application.  
 * @author          : South Bangla IT Zone Team 	
 * @url             : http://hms.sbitzone.com    
 * @support         : rabibd.it@gmail.com	
 * @copyright       : South Bangla IT Zone Team	 	
 * ********************************************************** */

class Auth extends CI_Controller
{

    public $data = array();
    public $global_setting = array();
    private $exp_time = 60 * 30; //30 minutes

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Auth_Model', 'auth', true);
        $this->global_setting = $this->db->get_where('global_setting', array('status' => 1))->row();

        if ($this->global_setting) {
            date_default_timezone_set($this->global_setting->time_zone);
        }
    }

    public function language($language = "")
    {
        $this->session->set_userdata('site_lang', $language);
        $url = $_SERVER['HTTP_REFERER'];
        redirect($url);
    }

    /*     * **************Function login**********************************
     * @type            : Function
     * @function name   : login
     * @description     : Authenticatte when uset try lo login. 
     *                    if autheticated redirected to logged in user dashboard.
     *                    Also set some session date for logged in user.   
     * @param           : null 
     * @return          : null 
     * ********************************************************** */

    public function login()
    {

        if ($_POST) {
            if (get_cookie('remember_me')) {
                $username = get_cookie('username');
                $password = get_cookie('password');

                if (!$this->input->post('remember_me')) {
                    delete_cookie("remember_me");
                    delete_cookie("username");
                    delete_cookie("password");
                }

                $data['username'] = $username;
                $data['password'] = md5($password);

                $login = $this->auth->get_single('users', $data);

                if (!empty($login)) {
                    // check user active status
                    if (!$login->status) {
                        $this->session->set_flashdata('error', $this->lang->line('user_active_status'));
                        redirect('admin');
                    }

                    // check is setting role permission by admin
                    $privileges = $this->auth->get_list('privileges', array('role_id' => $login->role_id));
                    if (empty($privileges)) {
                        $this->session->set_flashdata('error', $this->lang->line('privilege_not_setting'));
                        redirect('admin');
                    }

                    // User table data
                    $this->session->set_userdata('id', $login->id);
                    $this->session->set_userdata('role_id', $login->role_id);
                    $this->session->set_userdata('username', $login->username);
                    $this->session->set_userdata('toggle_btn', $login->toggle_btn);
                    $this->session->set_userdata('top_nav', $login->top_nav);
                    $this->session->set_userdata('sidebar_nav', $login->sidebar_nav);


                    if ($login->role_id == SUPER_ADMIN) {
                        $profile = $this->auth->get_single('employees', array('user_id' => $login->id));
                    } else {
                        $profile = $this->auth->get_single('employees', array('user_id' => $login->id));
                    }

                    if (isset($profile->name)) {
                        $this->session->set_userdata('name', $profile->name);
                    }
                    if (isset($profile->phone)) {
                        $this->session->set_userdata('phone', $profile->phone);
                    }
                    if (isset($profile->email)) {
                        $this->session->set_userdata('email', $profile->email);
                    }
                    if (isset($profile->photo)) {
                        $this->session->set_userdata('photo', $profile->photo);
                    }
                    if (isset($profile->user_id)) {
                        $this->session->set_userdata('user_id', $profile->user_id);
                    }
                    if (isset($profile->created_at)) {
                        $this->session->set_userdata('created_at', $profile->created_at);
                    }

                    $this->auth->update('users', array('last_logged_in' => date('Y-m-d H:i:s')), array('id' => logged_in_user_id()));
                    success($this->lang->line('login_success'));
                    create_log('Has been logged in');
                    redirect('dashboard');
                } else {
                    $this->session->set_flashdata('error', $this->lang->line('invalid_login'));
                    redirect('admin');
                }
            } else {
                $remember_me = $this->input->post('remember_me');
                $username = $this->input->post('username');
                $password = $this->input->post('password');

                $data['username'] = $username;
                $data['password'] = md5($password);

                if ($remember_me) {
                    set_cookie("username", $username, $this->exp_time);
                    set_cookie("password", $password, $this->exp_time);
                    set_cookie("remember_me", $remember_me, $this->exp_time);
                } else {
                    delete_cookie("username");
                    delete_cookie("password");
                    delete_cookie("remember_me");
                }

                $login = $this->auth->get_single('users', $data);

                if (!empty($login)) {

                    // check user active status
                    if (!$login->status) {
                        $this->session->set_flashdata('error', $this->lang->line('user_active_status'));
                        redirect('admin');
                    }

                    // check is setting role permission by admin
                    $privileges = $this->auth->get_list('privileges', array('role_id' => $login->role_id));
                    if (empty($privileges)) {
                        $this->session->set_flashdata('error', $this->lang->line('privilege_not_setting'));
                        redirect('admin');
                    }

                    // User table data
                    $this->session->set_userdata('id', $login->id);
                    $this->session->set_userdata('role_id', $login->role_id);
                    $this->session->set_userdata('username', $login->username);
                    $this->session->set_userdata('toggle_btn', $login->toggle_btn);
                    $this->session->set_userdata('top_nav', $login->top_nav);
                    $this->session->set_userdata('sidebar_nav', $login->sidebar_nav);


                    if ($login->role_id == SUPER_ADMIN) {
                        $profile = $this->auth->get_single('employees', array('user_id' => $login->id));
                    } else {
                        $profile = $this->auth->get_single('employees', array('user_id' => $login->id));
                    }

                    if (isset($profile->name)) {
                        $this->session->set_userdata('name', $profile->name);
                    }
                    if (isset($profile->phone)) {
                        $this->session->set_userdata('phone', $profile->phone);
                    }
                    if (isset($profile->email)) {
                        $this->session->set_userdata('email', $profile->email);
                    }
                    if (isset($profile->photo)) {
                        $this->session->set_userdata('photo', $profile->photo);
                    }
                    if (isset($profile->gender)) {
                        $this->session->set_userdata('gender', $profile->gender);
                    }
                    if (isset($profile->user_id)) {
                        $this->session->set_userdata('user_id', $profile->user_id);
                    }
                    if (isset($profile->created_at)) {
                        $this->session->set_userdata('created_at', $profile->created_at);
                    }

                    $this->auth->update('users', array('last_logged_in' => date('Y-m-d H:i:s')), array('id' => logged_in_user_id()));
                    success($this->lang->line('login_success'));
                    create_log('Has been logged in');
                    redirect('dashboard');
                } else {
                    $this->session->set_flashdata('error', $this->lang->line('invalid_login'));
                    redirect('admin');
                }
            }
        }
    }

    /*     * ***************Function logout**********************************
     * @type            : Function
     * @function name   : logout
     * @description     : Log Out the logged in user and redirected to Login page  
     * @param           : null 
     * @return          : null 
     * ********************************************************** */

    public function logout($key = null)
    {

        @create_log('Has been logged out');

        $this->session->unset_userdata($key);
        $this->session->unset_userdata('id');
        $this->session->unset_userdata('role_id');
        $this->session->unset_userdata('email');
        $this->session->unset_userdata('username');

        $this->session->unset_userdata('name');
        $this->session->unset_userdata('phone');
        $this->session->unset_userdata('photo');
        $this->session->unset_userdata('user_id');
        $this->session->sess_destroy();
        redirect('admin', 'refresh');
        exit;
    }

    /*     * ***************Function forgot**********************************
     * @type            : Function
     * @function name   : forgot
     * @description     : Load recover forgot password view file  
     * @param           : null 
     * @return          : null 
     * ********************************************************** */

    public function forgot()
    {

        $this->load->helper('form');
        $data = array();
        $this->load->view('forgot', $data);
    }

    /*     * ***************Function forgotpass**********************************
     * @type            : Function
     * @function name   : forgotpass
     * @description     : this function is used to send recover forgot password  email 
     * @param           : null 
     * @return          : null 
     * ********************************************************** */

    /*     * ***************Function forgotpass**********************************
     * @type            : Function
     * @function name   : forgotpass
     * @description     : this function is used to send recover forgot password  email 
     * @param           : null 
     * @return          : null 
     * ********************************************************** */

    public function forgotpass()
    {

        if ($_POST) {

            $data['username'] = $this->input->post('username');
            $data['status'] = 1;
            $login = $this->auth->get_single('users', $data);
            if (!empty($login)) {
                if ($this->_send_email($login)) {
                    $this->_send_sms($login);
                    $this->session->set_flashdata('success', $this->lang->line('email_send_success'));
                } else {
                    $this->session->set_flashdata('success', $this->lang->line('unexpected_error'));
                }
            } else {
                $this->session->set_flashdata('error', $this->lang->line('wrong_username'));
            }
        }
        redirect('forgot');
        exit;
    }

    /*     * ***************Function _send_email**********************************
     * @type            : Function
     * @function name   : _send_email
     * @description     : this function used to send recover forgot password email 
     * @param           : $data array(); 
     * @return          : null 
     * ********************************************************** */

    private function _send_email($data)
    {

        $profile = get_user_by_role($data->role_id, $data->id);

        if ($profile->email) {

            $from_email = FROM_EMAIL;
            $from_name = FROM_NAME;

            $email_setting = $this->auth->get_single('email_settings', array('status' => 1));

            if (!empty($email_setting)) {
                $from_email = $email_setting->from_address;
                $from_name = $email_setting->from_name;
            }

            if (!empty($email_setting) && $email_setting->mail_protocol == 'smtp') {
                $config['protocol'] = 'smtp';
                $config['smtp_host'] = $email_setting->smtp_host;
                $config['smtp_port'] = $email_setting->smtp_port;
                $config['smtp_timeout'] = $email_setting->smtp_timeout ? $email_setting->smtp_timeout : 5;
                $config['smtp_user'] = $email_setting->smtp_user;
                $config['smtp_pass'] = $email_setting->smtp_pass;
                $config['smtp_crypto'] = $email_setting->smtp_crypto ? $email_setting->smtp_crypto : 'tls';
                $config['mailtype'] = isset($email_setting) && $email_setting->mail_type ? $email_setting->mail_type : 'html';
                $config['charset'] = isset($email_setting) && $email_setting->char_set ? $email_setting->char_set : 'iso-8859-1';
                $config['priority'] = isset($email_setting) && $email_setting->priority ? $email_setting->priority : '3';
            } elseif (!empty($email_setting) && $email_setting->mail_protocol != 'smtp') {
                $config['protocol'] = $email_setting->mail_protocol;
                $config['mailpath'] = '/usr/sbin/' . $email_setting->mail_protocol;
                $config['mailtype'] = isset($email_setting) && $email_setting->mail_type ? $email_setting->mail_type : 'html';
                $config['charset'] = isset($email_setting) && $email_setting->char_set ? $email_setting->char_set : 'iso-8859-1';
                $config['priority'] = isset($email_setting) && $email_setting->priority ? $email_setting->priority : '3';
            } else { // default
                $config['protocol'] = 'sendmail';
                $config['mailpath'] = '/usr/sbin/sendmail';
            }


            $config['wordwrap'] = TRUE;
            $config['newline'] = "\r\n";


            $this->load->library('email');
            $this->email->initialize($config);


            $this->email->from($from_email, $from_name);
            $this->email->to($profile->email);
            $subject = 'Password reset Email from : ' . $from_name;
            $this->email->subject($subject);
            $key = uniqid();
            $this->auth->update('users', array('reset_key' => $key), array('id' => $data->id));

            $message = 'You have requested to reset your ' . $from_name . ' web Application login password.<br/>';
            $message .= 'To reset you password plese click following url<br/><br/>';
            $message .= site_url('auth/reset/' . $key);
            $message .= '<br/><br/>';
            $message .= 'If you did not request to reset your password, Plesae ignore this email.<br/><br/>';
            $message .= 'Thank you<br/>';
            $message .= $from_name;

            $this->email->message($message);

            if (!empty($email_setting) && $email_setting->mail_protocol == 'smtp') {
                $this->email->send();
            } else {
                $headers = "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                $headers .= "From:  $from_name < $from_email >\r\n";
                $headers .= "Reply-To:  $from_name < $from_email >\r\n";
                mail($profile->email, $subject, $message, $headers);
            }

            return TRUE;
        } else {
            return FALSE;
        }
    }

    /*     * ***************Function reset**********************************
     * @type            : Function
     * @function name   : reset
     * @description     : this function used to load password reset view file 
     * @param           : $key string parameter; 
     * @return          : null 
     * ********************************************************** */

    public function reset($key)
    {

        $data = array();
        $this->load->helper('form');
        $user = $this->auth->get_single('users', array('reset_key' => $key));

        if (!empty($user)) {
            $data['user'] = $user;
            $data['key'] = $key;
            $this->load->view('reset', $data);
        } else {
            $this->session->set_flashdata('error', $this->lang->line('unexpected_error'));
            redirect('admin');
        }
    }

    /*     * ***************Function resetpass**********************************
     * @type            : Function
     * @function name   : resetpass
     * @description     : this function used to reset user passwrd 
     *                    after sucessfull reset password it's redirected
     *                    user to log in page            
     * @param           : null; 
     * @return          : null 
     * ********************************************************** */

    public function resetpass()
    {

        if ($_POST) {

            $this->load->library('form_validation');
            $this->form_validation->set_error_delimiters('<div class="error-message" style="color: red;">', '</div>');
            $this->form_validation->set_rules('password', $this->lang->line('password'), 'trim|required|min_length[5]|max_length[12]');
            $this->form_validation->set_rules('conf_password', $this->lang->line('conf_password'), 'trim|required|matches[password]');

            if ($this->form_validation->run() === TRUE) {
                $data['password'] = md5($this->input->post('password'));
                $data['temp_password'] = base64_encode($this->input->post('password'));
                $data['reset_key'] = NULL;
                $data['modified_at'] = date('Y-m-d H:i:s');
                $this->auth->update('users', $data, array('id' => $this->input->post('id')));
                $this->session->set_flashdata('success', $this->lang->line('update_success'));

                delete_cookie("remember_me");
                delete_cookie("username");
                delete_cookie("password");

                redirect('admin', 'refresh');
            } else {
                $this->session->set_flashdata('error', $this->lang->line('password_reset_error'));
                redirect('auth/reset/' . $this->input->post('key'));
            }
        }

        redirect();
        exit;
    }


    /*     * ***************Function _send_sms**********************************
     * @type            : Function
     * @function name   : _send_sms
     * @description     : this function used to send reset username and passwrd by user mobile         
     * @param           : null; 
     * @return          : null 
     * ********************************************************** */

    private function _send_sms($data)
    {

        $profile = get_user_by_role($data->role_id, $data->id);

        if ($profile->phone) {
            $notification = $this->db->get_where('notifications', array('status' => 1, 'type' => 'reset_pass'))->row();
            $body = $this->db->get_where('sms_templates', array('type' => $notification->id))->row();
            if ($notification->is_sms) {

                $this->load->library('mimsms');

                $phone   = $profile->phone;
                // $name   = $profile->name;
                // $username   = $data->username;
                // $password   = base64_decode($data->temp_password);
                // $message = 'Hello, ' . $name;
                // $message .= ', your login details for Url:' . site_url('admin');
                // $message .= ', Username: ' . $username;
                // $message .= ', Password: ' . $password;
                // $message .= "\n\n";
                // $message .= 'Thanks';
                // $message .= "\n";
                // $message .= $setting->brand_name;
                // if ($phone) {
                //     return $this->mimsms->sendMimSms($phone, $message);
                // }

                $message = get_formatted_body($body->template, $data->role_id, $data->id);
                if ($phone) {
                    return $this->mimsms->sendMimSms($phone, $message);
                }
            }
        }
    }
}
