<?php

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

class Authentication extends App_Controller
{
    public function __construct()
    {
        parent::__construct();

        if ($this->app->is_db_upgrade_required()) {
            redirect(admin_url());
        }

        load_admin_language();
        $this->load->model('Authentication_model');
        $this->load->model('Cron_model');
        $this->load->library('form_validation');
        $this->load->model('Token_model');

        $this->form_validation->set_message('required', _l('form_validation_required'));
        $this->form_validation->set_message('valid_email', _l('form_validation_valid_email'));
        $this->form_validation->set_message('matches', _l('form_validation_matches'));

        hooks()->do_action('admin_auth_init');
    }

   public function index($lead_id = '', $role_type = '')
    {
        if (is_staff_logged_in()) {
            if(!empty($lead_id)){
                redirect(admin_url('cases/index/' . $lead_id));
            }
        }

        // Allowed role-based login paths
        $valid_roles = ['broker', 'ldteam', 'adminbroker', 'clerk', 'officer', 'hr'];

        if (in_array($role_type, $valid_roles)) {
            redirect("admin/authentication/{$role_type}");
        }

        // Default fallback to standard admin login
        $this->admin();
    }

    // email template show for testing
    public function template()
    {
        $this->load->view('admin/leads/Email_template/Rff_to_broker');
    }

    // Dropbox Auth work
    public function tokengenereate()
    {
        $this->Cron_model->dropbox_connect();
    }
    public function send_post_request($url, $data)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $response = curl_exec($ch);

        // Check for cURL errors
        if (curl_errno($ch)) {
            echo 'cURL error: ' . curl_error($ch);
        }

        curl_close($ch);

        return json_decode($response, true);
    }

    public function refresh_dropbox_token()
    {
        // Obtain app-specific credentials from the Dropbox App Console
        if (base_url() == 'https://dev.platform.legaldirect.ca/') {
            define('DROPBOX_CLIENT_ID', 'atcksepiq6w9wzo');
            define('DROPBOX_CLIENT_SECRET', 'tye7w7g8khh68ri');
        }else{
            define('DROPBOX_CLIENT_ID', 'deh0r98qh2zi04k');
            define('DROPBOX_CLIENT_SECRET', 'ai3t7vc77cvt4vd');
        }

        // Get the refresh token from the database
        $data = $this->Token_model->getToken();
        $refreshToken = array_column($data, 'refresh_token');
        $refreshToken = implode(',', $refreshToken);

        // Check if a refresh token is available
        if (!empty ($refreshToken)) {
            // Construct the URL for the token refresh
            $tokenRefreshURL = 'https://api.dropbox.com/oauth2/token';

            // Prepare the parameters for the refresh token request
            $params = array(
                'grant_type' => 'refresh_token',
                'refresh_token' => $refreshToken,
                'client_id' => DROPBOX_CLIENT_ID,
                'client_secret' => DROPBOX_CLIENT_SECRET,
            );

            // Send a POST request to refresh the token
            $response = $this->send_post_request($tokenRefreshURL, $params);
            // Handle the response
            if (isset ($response['access_token'])) {
                $newAccessToken = $response['access_token'];
                $expires_in = $response['expires_in'];
                // Update the database with the new access token
                $data = array(
                    'token' => $newAccessToken,
                    'expire_time' => $expires_in,
                    'created_at' => date('Y-m-d H:i:s'),
                );

                $this->db->where('token', $refreshToken);
                $this->db->update(db_prefix() . 'token', $data);

                echo 'Token refreshed successfully.';
            } else {
                // Check if the error is due to a malformed refresh token
                if (isset ($response['error']) && $response['error'] === 'invalid_grant') {
                    echo 'Refresh token is invalid or malformed. You may need to reauthorize the user.';
                } else {
                    echo 'Failed to refresh the token. ' . json_encode($response);
                }
            }
        } else {
            echo 'No refresh token available.';
        }
    }
    function refreshAccessToken()
    {
        if (base_url() == 'https://dev.platform.legaldirect.ca/') {
            $clientId = 'atcksepiq6w9wzo'; 
            $clientSecret = 'tye7w7g8khh68ri'; 
        }else{
            $clientId = 'deh0r98qh2zi04k'; 
            $clientSecret = 'ai3t7vc77cvt4vd'; 
        }
        // Get the refresh token from the database
        $data = $this->Token_model->getToken();
        $refreshToken = array_column($data, 'token');
        $refreshToken = implode(',', $refreshToken);
        if (empty ($data)) {
            // Handle the case where there is no refresh token available
            return ['error' => 'No refresh token available'];
        }

        $tokenRefreshURL = 'https://api.dropbox.com/oauth2/token';

        $params = [
            'grant_type' => 'refresh_token',
            'refresh_token' => $refreshToken,
            'client_id' => $clientId,
            'client_secret' => $clientSecret,
        ];

        $ch = curl_init($tokenRefreshURL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

        $response = curl_exec($ch);
        print_r($response);
        if ($response === false) {
            // Handle cURL error
            return ['error' => 'cURL error: ' . curl_error($ch)];
        }

        curl_close($ch);

        return json_decode($response, true);
    }



    public function checktoken()
    {
        $urlToRedirect = 'https://platform.legaldirect.ca/admin/authentication/tokengenereate';
        // Use cURL to make an HTTP request
        $ch = curl_init($urlToRedirect);
        $exc = curl_exec($ch);
        curl_close($ch);
        echo $exc;
    }


    // public function dropbox(){
    //     $this->load->view('dropbox_token');
    // }
    public function admin()
    {
        if (is_staff_logged_in()) {
            redirect(admin_url());
        }

        $this->form_validation->set_rules('password', _l('admin_auth_login_password'), 'required');
        $this->form_validation->set_rules('email', _l('admin_auth_login_email'), 'trim|required|valid_email');
        if (show_recaptcha()) {
            $this->form_validation->set_rules('g-recaptcha-response', 'Captcha', 'callback_recaptcha');
        }
        if ($this->input->post()) {
            if ($this->form_validation->run() !== false) {
                $email = $this->input->post('email');
                $password = $this->input->post('password', false);
                $remember = $this->input->post('remember');
                // check for ldteam is login or not
                $this->db->where('email', $email);
                $this->db->where('role', '4');
                $get_role = $this->db->get(db_prefix() . 'staff')->row();
                if (empty ($get_role)) {
                    set_alert('danger', 'Admin is not exist in our record.');
                    redirect(admin_url('authentication'));
                }
                $data = $this->Authentication_model->login($email, $password, $remember, true);

                if (is_array($data) && isset ($data['memberinactive'])) {
                    set_alert('danger', _l('admin_auth_inactive_account'));
                    redirect(admin_url('authentication'));
                } elseif (is_array($data) && isset ($data['two_factor_auth'])) {
                    $this->session->set_userdata('_two_factor_auth_established', true);
                    if ($data['user']->two_factor_auth_enabled == 1) {
                        $this->Authentication_model->set_two_factor_auth_code($data['user']->staffid);
                        $sent = send_mail_template('staff_two_factor_auth_key', $data['user']);

                        if (!$sent) {
                            set_alert('danger', _l('two_factor_auth_failed_to_send_code'));
                            redirect(admin_url('authentication'));
                        } else {
                            $this->session->set_userdata('_two_factor_auth_staff_email', $email);
                            set_alert('success', _l('two_factor_auth_code_sent_successfully', $email));
                            redirect(admin_url('authentication/two_factor'));
                        }
                    } else {
                        set_alert('success', _l('enter_two_factor_auth_code_from_mobile'));
                        redirect(admin_url('authentication/two_factor/app'));
                    }
                } elseif ($data == false) {
                    set_alert('danger', _l('admin_auth_invalid_email_or_password'));
                    redirect(admin_url('authentication'));
                }

                $this->load->model('announcements_model');
                $this->announcements_model->set_announcements_as_read_except_last_one(get_staff_user_id(), true);

                // is logged in
                maybe_redirect_to_previous_url();

                hooks()->do_action('after_staff_login');
                redirect(admin_url());
            }
        }

        $data['title'] = _l('admin_auth_login_heading');
        $data['role_title'] = 'Admin ';
        $data['message'] = '<p style="color:red;font-size:medium;line-height: normal;">
            This page is intended for development purposes only. 
            To access the live login page, please 
            <a href="' . 'https://platform.legaldirect.ca/admin/authentication' . '">click here</a>.
        </p>';
        $data['company_title'] = $this->Authentication_model->CopyrightText();
        $this->load->view('authentication/login_admin', $data);
    }
    public function broker()
    {
        if (is_staff_logged_in()) {
            redirect(admin_url());
        }

        $this->form_validation->set_rules('password', _l('admin_auth_login_password'), 'required');
        $this->form_validation->set_rules('email', _l('admin_auth_login_email'), 'trim|required|valid_email');
        if (show_recaptcha()) {
            $this->form_validation->set_rules('g-recaptcha-response', 'Captcha', 'callback_recaptcha');
        }
        if ($this->input->post()) {
            if ($this->form_validation->run() !== false) {
                $email = $this->input->post('email');
                $password = $this->input->post('password', false);
                $remember = $this->input->post('remember');
                // check for ldteam is login or not
                $this->db->where('email', $email);
                $this->db->where('role', '2');
                $get_role = $this->db->get(db_prefix() . 'staff')->row();
                if (empty ($get_role)) {
                    set_alert('danger', 'Broker is not exist in our record.');
                    redirect(admin_url('authentication/broker'));
                }
                $data = $this->Authentication_model->login($email, $password, $remember, true);

                if (is_array($data) && isset ($data['memberinactive'])) {
                    set_alert('danger', _l('admin_auth_inactive_account'));
                    redirect(admin_url('authentication/broker'));
                } elseif (is_array($data) && isset ($data['two_factor_auth'])) {
                    $this->session->set_userdata('_two_factor_auth_established', true);
                    if ($data['user']->two_factor_auth_enabled == 1) {
                        $this->Authentication_model->set_two_factor_auth_code($data['user']->staffid);
                        $sent = send_mail_template('staff_two_factor_auth_key', $data['user']);

                        if (!$sent) {
                            set_alert('danger', _l('two_factor_auth_failed_to_send_code'));
                            redirect(admin_url('authentication'));
                        } else {
                            $this->session->set_userdata('_two_factor_auth_staff_email', $email);
                            set_alert('success', _l('two_factor_auth_code_sent_successfully', $email));
                            redirect(admin_url('authentication/two_factor'));
                        }
                    } else {
                        set_alert('success', _l('enter_two_factor_auth_code_from_mobile'));
                        redirect(admin_url('authentication/two_factor/app'));
                    }
                } elseif ($data == false) {
                    set_alert('danger', _l('admin_auth_invalid_email_or_password'));
                    redirect(admin_url('authentication/broker'));
                }

                $this->load->model('announcements_model');
                $this->announcements_model->set_announcements_as_read_except_last_one(get_staff_user_id(), true);

                // is logged in
                maybe_redirect_to_previous_url();

                hooks()->do_action('after_staff_login');
                redirect(admin_url());
            }
        }

        $data['title'] = _l('admin_auth_login_heading');
        $data['role_title'] = 'Broker ';
        $data['message'] = '<p style="color:red;font-size:medium;line-height: normal;">
            This page is intended for development purposes only. 
            To access the live login page, please 
            <a href="' . 'https://platform.legaldirect.ca/admin/authentication/broker' . '">click here</a>.
        </p>';
        $data['company_title'] = $this->Authentication_model->CopyrightText();
        $this->load->view('authentication/login_admin', $data);
    }
    public function ldteam()
    {
        if (is_staff_logged_in()) {
            redirect(admin_url());
        }

        $this->form_validation->set_rules('password', _l('admin_auth_login_password'), 'required');
        $this->form_validation->set_rules('email', _l('admin_auth_login_email'), 'trim|required|valid_email');
        if (show_recaptcha()) {
            $this->form_validation->set_rules('g-recaptcha-response', 'Captcha', 'callback_recaptcha');
        }
        if ($this->input->post()) {
            if ($this->form_validation->run() !== false) {
                $email = $this->input->post('email');
                $password = $this->input->post('password', false);
                $remember = $this->input->post('remember');
                // check for ldteam is login or not
                $this->db->where('email', $email);
                $this->db->where('role', '1');
                $get_role = $this->db->get(db_prefix() . 'staff')->row();
                if (empty ($get_role)) {
                    set_alert('danger', 'LD-Team is not exist in our record.');
                    redirect(admin_url('authentication/ldteam'));
                }
                $data = $this->Authentication_model->login($email, $password, $remember, true);

                if (is_array($data) && isset ($data['memberinactive'])) {
                    set_alert('danger', _l('admin_auth_inactive_account'));
                    redirect(admin_url('authentication/ldteam'));
                } elseif (is_array($data) && isset ($data['two_factor_auth'])) {
                    $this->session->set_userdata('_two_factor_auth_established', true);
                    if ($data['user']->two_factor_auth_enabled == 1) {
                        $this->Authentication_model->set_two_factor_auth_code($data['user']->staffid);
                        $sent = send_mail_template('staff_two_factor_auth_key', $data['user']);

                        if (!$sent) {
                            set_alert('danger', _l('two_factor_auth_failed_to_send_code'));
                            redirect(admin_url('authentication'));
                        } else {
                            $this->session->set_userdata('_two_factor_auth_staff_email', $email);
                            set_alert('success', _l('two_factor_auth_code_sent_successfully', $email));
                            redirect(admin_url('authentication/two_factor'));
                        }
                    } else {
                        set_alert('success', _l('enter_two_factor_auth_code_from_mobile'));
                        redirect(admin_url('authentication/two_factor/app'));
                    }
                } elseif ($data == false) {
                    set_alert('danger', _l('admin_auth_invalid_email_or_password'));
                    redirect(admin_url('authentication/ldteam'));
                }

                $this->load->model('announcements_model');
                $this->announcements_model->set_announcements_as_read_except_last_one(get_staff_user_id(), true);

                // is logged in
                maybe_redirect_to_previous_url();

                hooks()->do_action('after_staff_login');
                redirect(admin_url());
            }
        }

        $data['title'] = _l('admin_auth_login_heading');
        $data['role_title'] = 'LD-Team ';
        $data['message'] = '<p style="color:red;font-size:medium;line-height: normal;">
            This page is intended for development purposes only. 
            To access the live login page, please 
            <a href="' . 'https://platform.legaldirect.ca/admin/authentication/ldteam' . '">click here</a>.
        </p>';
        $data['company_title'] = $this->Authentication_model->CopyrightText();
        $this->load->view('authentication/login_admin', $data);
    }
    public function adminbroker()
    {
        if (is_staff_logged_in()) {
            redirect(admin_url());
        }

        $this->form_validation->set_rules('password', _l('admin_auth_login_password'), 'required');
        $this->form_validation->set_rules('email', _l('admin_auth_login_email'), 'trim|required|valid_email');
        if (show_recaptcha()) {
            $this->form_validation->set_rules('g-recaptcha-response', 'Captcha', 'callback_recaptcha');
        }
        if ($this->input->post()) {
            if ($this->form_validation->run() !== false) {
                $email = $this->input->post('email');
                $password = $this->input->post('password', false);
                $remember = $this->input->post('remember');
                // check for ldteam is login or not
                $this->db->where('email', $email);
                $this->db->where('role', '6');
                $get_role = $this->db->get(db_prefix() . 'staff')->row();
                if (empty ($get_role)) {
                    set_alert('danger', 'Admin-Broker is not exist in our record.');
                    redirect(admin_url('authentication/adminbroker'));
                }
                $data = $this->Authentication_model->login($email, $password, $remember, true);

                if (is_array($data) && isset ($data['memberinactive'])) {
                    set_alert('danger', _l('admin_auth_inactive_account'));
                    redirect(admin_url('authentication/adminbroker'));
                } elseif (is_array($data) && isset ($data['two_factor_auth'])) {
                    $this->session->set_userdata('_two_factor_auth_established', true);
                    if ($data['user']->two_factor_auth_enabled == 1) {
                        $this->Authentication_model->set_two_factor_auth_code($data['user']->staffid);
                        $sent = send_mail_template('staff_two_factor_auth_key', $data['user']);

                        if (!$sent) {
                            set_alert('danger', _l('two_factor_auth_failed_to_send_code'));
                            redirect(admin_url('authentication'));
                        } else {
                            $this->session->set_userdata('_two_factor_auth_staff_email', $email);
                            set_alert('success', _l('two_factor_auth_code_sent_successfully', $email));
                            redirect(admin_url('authentication/two_factor'));
                        }
                    } else {
                        set_alert('success', _l('enter_two_factor_auth_code_from_mobile'));
                        redirect(admin_url('authentication/two_factor/app'));
                    }
                } elseif ($data == false) {
                    set_alert('danger', _l('admin_auth_invalid_email_or_password'));
                    redirect(admin_url('authentication/adminbroker'));
                }

                $this->load->model('announcements_model');
                $this->announcements_model->set_announcements_as_read_except_last_one(get_staff_user_id(), true);

                // is logged in
                maybe_redirect_to_previous_url();

                hooks()->do_action('after_staff_login');
                redirect(admin_url());
            }
        }

        $data['title'] = _l('admin_auth_login_heading');
        $data['role_title'] = 'Admin-Broker ';
        $data['message'] = '<p style="color:red;font-size:medium;line-height: normal;">
            This page is intended for development purposes only. 
            To access the live login page, please 
            <a href="' . 'https://platform.legaldirect.ca/admin/authentication/adminbroker' . '">click here</a>.
        </p>';
        $data['company_title'] = $this->Authentication_model->CopyrightText();
        $this->load->view('authentication/login_admin', $data);
    }
    // Clerk
    public function clerk()
    {
        if (is_staff_logged_in()) {
            redirect(admin_url());
        }

        $this->form_validation->set_rules('password', _l('admin_auth_login_password'), 'required');
        $this->form_validation->set_rules('email', _l('admin_auth_login_email'), 'trim|required|valid_email');
        if (show_recaptcha()) {
            $this->form_validation->set_rules('g-recaptcha-response', 'Captcha', 'callback_recaptcha');
        }
        if ($this->input->post()) {
            if ($this->form_validation->run() !== false) {
                $email = $this->input->post('email');
                $password = $this->input->post('password', false);
                $remember = $this->input->post('remember');
                // check for ldteam is login or not
                $this->db->where('email', $email);
                $this->db->where('role', '7');
                $get_role = $this->db->get(db_prefix() . 'staff')->row();
                if (empty ($get_role)) {
                    set_alert('danger', 'Clerk is not exist in our record.');
                    redirect(admin_url('authentication/clerk'));
                }
                $data = $this->Authentication_model->login($email, $password, $remember, true);

                if (is_array($data) && isset ($data['memberinactive'])) {
                    set_alert('danger', _l('admin_auth_inactive_account'));
                    redirect(admin_url('authentication/clerk'));
                } elseif (is_array($data) && isset ($data['two_factor_auth'])) {
                    $this->session->set_userdata('_two_factor_auth_established', true);
                    if ($data['user']->two_factor_auth_enabled == 1) {
                        $this->Authentication_model->set_two_factor_auth_code($data['user']->staffid);
                        $sent = send_mail_template('staff_two_factor_auth_key', $data['user']);

                        if (!$sent) {
                            set_alert('danger', _l('two_factor_auth_failed_to_send_code'));
                            redirect(admin_url('authentication'));
                        } else {
                            $this->session->set_userdata('_two_factor_auth_staff_email', $email);
                            set_alert('success', _l('two_factor_auth_code_sent_successfully', $email));
                            redirect(admin_url('authentication/two_factor'));
                        }
                    } else {
                        set_alert('success', _l('enter_two_factor_auth_code_from_mobile'));
                        redirect(admin_url('authentication/two_factor/app'));
                    }
                } elseif ($data == false) {
                    set_alert('danger', _l('admin_auth_invalid_email_or_password'));
                    redirect(admin_url('authentication/clerk'));
                }

                $this->load->model('announcements_model');
                $this->announcements_model->set_announcements_as_read_except_last_one(get_staff_user_id(), true);

                // is logged in
                maybe_redirect_to_previous_url();

                hooks()->do_action('after_staff_login');
                redirect(admin_url());
            }
        }

        $data['title'] = _l('admin_auth_login_heading');
        $data['role_title'] = 'Clerk ';
        $data['message'] = '<p style="color:red;font-size:medium;line-height: normal;">
            This page is intended for development purposes only. 
            To access the live login page, please 
            <a href="' . 'https://platform.legaldirect.ca/admin/authentication/clerk' . '">click here</a>.
        </p>';
        $data['company_title'] = $this->Authentication_model->CopyrightText();
        $this->load->view('authentication/login_admin', $data);
    }

    // Junior Officer
    public function officer()
    {
        if (is_staff_logged_in()) {
            redirect(admin_url());
        }

        $this->form_validation->set_rules('password', _l('admin_auth_login_password'), 'required');
        $this->form_validation->set_rules('email', _l('admin_auth_login_email'), 'trim|required|valid_email');
        if (show_recaptcha()) {
            $this->form_validation->set_rules('g-recaptcha-response', 'Captcha', 'callback_recaptcha');
        }
        if ($this->input->post()) {
            if ($this->form_validation->run() !== false) {
                $email = $this->input->post('email');
                $password = $this->input->post('password', false);
                $remember = $this->input->post('remember');
                // check for ldteam is login or not
                $this->db->where('email', $email);
                $this->db->where('role', '8');
                $get_role = $this->db->get(db_prefix() . 'staff')->row();
                if (empty ($get_role)) {
                    set_alert('danger', 'Junior-Officer is not exist in our record.');
                    redirect(admin_url('authentication/officer'));
                }
                $data = $this->Authentication_model->login($email, $password, $remember, true);

                if (is_array($data) && isset ($data['memberinactive'])) {
                    set_alert('danger', _l('admin_auth_inactive_account'));
                    redirect(admin_url('authentication/officer'));
                } elseif (is_array($data) && isset ($data['two_factor_auth'])) {
                    $this->session->set_userdata('_two_factor_auth_established', true);
                    if ($data['user']->two_factor_auth_enabled == 1) {
                        $this->Authentication_model->set_two_factor_auth_code($data['user']->staffid);
                        $sent = send_mail_template('staff_two_factor_auth_key', $data['user']);

                        if (!$sent) {
                            set_alert('danger', _l('two_factor_auth_failed_to_send_code'));
                            redirect(admin_url('authentication'));
                        } else {
                            $this->session->set_userdata('_two_factor_auth_staff_email', $email);
                            set_alert('success', _l('two_factor_auth_code_sent_successfully', $email));
                            redirect(admin_url('authentication/two_factor'));
                        }
                    } else {
                        set_alert('success', _l('enter_two_factor_auth_code_from_mobile'));
                        redirect(admin_url('authentication/two_factor/app'));
                    }
                } elseif ($data == false) {
                    set_alert('danger', _l('admin_auth_invalid_email_or_password'));
                    redirect(admin_url('authentication/officer'));
                }

                $this->load->model('announcements_model');
                $this->announcements_model->set_announcements_as_read_except_last_one(get_staff_user_id(), true);

                // is logged in
                maybe_redirect_to_previous_url();

                hooks()->do_action('after_staff_login');
                redirect(admin_url());
            }
        }

        $data['title'] = _l('admin_auth_login_heading');
        $data['role_title'] = 'Junior-Officer ';
        $data['message'] = '<p style="color:red;font-size:medium;line-height: normal;">
            This page is intended for development purposes only. 
            To access the live login page, please 
            <a href="' . 'https://platform.legaldirect.ca/admin/authentication/officer' . '">click here</a>.
        </p>';
        $data['company_title'] = $this->Authentication_model->CopyrightText();
        $this->load->view('authentication/login_admin', $data);
    }
    // HR Manager
    public function hr()
    {
        if (is_staff_logged_in()) {
            redirect(admin_url());
        }

        $this->form_validation->set_rules('password', _l('admin_auth_login_password'), 'required');
        $this->form_validation->set_rules('email', _l('admin_auth_login_email'), 'trim|required|valid_email');
        if (show_recaptcha()) {
            $this->form_validation->set_rules('g-recaptcha-response', 'Captcha', 'callback_recaptcha');
        }
        if ($this->input->post()) {
            if ($this->form_validation->run() !== false) {
                $email = $this->input->post('email');
                $password = $this->input->post('password', false);
                $remember = $this->input->post('remember');
                // check for ldteam is login or not
                $this->db->where('email', $email);
                $this->db->where('role', '9');
                $get_role = $this->db->get(db_prefix() . 'staff')->row();
                if (empty ($get_role)) {
                    set_alert('danger', 'HR Manager is not exist in our record.');
                    redirect(admin_url('authentication/hr'));
                }
                $data = $this->Authentication_model->login($email, $password, $remember, true);

                if (is_array($data) && isset ($data['memberinactive'])) {
                    set_alert('danger', _l('admin_auth_inactive_account'));
                    redirect(admin_url('authentication/hr'));
                } elseif (is_array($data) && isset ($data['two_factor_auth'])) {
                    $this->session->set_userdata('_two_factor_auth_established', true);
                    if ($data['user']->two_factor_auth_enabled == 1) {
                        $this->Authentication_model->set_two_factor_auth_code($data['user']->staffid);
                        $sent = send_mail_template('staff_two_factor_auth_key', $data['user']);

                        if (!$sent) {
                            set_alert('danger', _l('two_factor_auth_failed_to_send_code'));
                            redirect(admin_url('authentication'));
                        } else {
                            $this->session->set_userdata('_two_factor_auth_staff_email', $email);
                            set_alert('success', _l('two_factor_auth_code_sent_successfully', $email));
                            redirect(admin_url('authentication/two_factor'));
                        }
                    } else {
                        set_alert('success', _l('enter_two_factor_auth_code_from_mobile'));
                        redirect(admin_url('authentication/two_factor/app'));
                    }
                } elseif ($data == false) {
                    set_alert('danger', _l('admin_auth_invalid_email_or_password'));
                    redirect(admin_url('authentication/hr'));
                }

                $this->load->model('announcements_model');
                $this->announcements_model->set_announcements_as_read_except_last_one(get_staff_user_id(), true);

                // is logged in
                maybe_redirect_to_previous_url();

                hooks()->do_action('after_staff_login');
                redirect(admin_url());
            }
        }

        $data['title'] = _l('admin_auth_login_heading');
        $data['role_title'] = 'Hr-Manager ';
        $data['message'] = '<p style="color:red;font-size:medium;line-height: normal;">
            This page is intended for development purposes only. 
            To access the live login page, please 
            <a href="' . 'https://platform.legaldirect.ca/admin/authentication/hr' . '">click here</a>.
        </p>';
        $data['company_title'] = $this->Authentication_model->CopyrightText();
        $this->load->view('authentication/login_admin', $data);
    }
    public function two_factor($type = 'email')
    {
        if (!$this->session->has_userdata('_two_factor_auth_established')) {
            show_404();
        }

        $this->form_validation->set_rules('code', _l('two_factor_authentication_code'), 'required');

        if ($this->input->post()) {
            if ($this->form_validation->run() !== false) {
                $code = $this->input->post('code');
                $code = trim($code);
                $email = $this->session->userdata('_two_factor_auth_staff_email');
                if ($this->Authentication_model->is_two_factor_code_valid($code, $email) && $type = 'email') {
                    $this->session->unset_userdata('_two_factor_auth_staff_email');

                    $user = $this->Authentication_model->get_user_by_two_factor_auth_code($code);
                    $this->Authentication_model->clear_two_factor_auth_code($user->staffid);
                    $this->Authentication_model->two_factor_auth_login($user);
                    $this->session->unset_userdata('_two_factor_auth_established');
                    $this->load->model('announcements_model');
                    $this->announcements_model->set_announcements_as_read_except_last_one(get_staff_user_id(), true);

                    maybe_redirect_to_previous_url();

                    hooks()->do_action('after_staff_login');
                    redirect(admin_url());
                } elseif ($this->Authentication_model->is_google_two_factor_code_valid($code) && $type = 'app') {
                    $user = get_staff($this->session->userdata('tfa_staffid'));
                    $this->Authentication_model->two_factor_auth_login($user);
                    $this->session->unset_userdata('_two_factor_auth_established');
                    $this->load->model('announcements_model');
                    $this->announcements_model->set_announcements_as_read_except_last_one(get_staff_user_id(), true);

                    maybe_redirect_to_previous_url();

                    hooks()->do_action('after_staff_login');
                    redirect(admin_url());
                } else {
                    log_activity('Failed Two factor authentication attempt [Staff Name: ' . get_staff_full_name() . ', IP: ' . $this->input->ip_address() . ']');

                    set_alert('danger', _l('two_factor_code_not_valid'));
                    redirect(admin_url('authentication/two_factor/' . $type));
                }
            }
        }

        $this->load->view('authentication/set_two_factor_auth_code');
    }

    public function forgot_password()
    {
        if (is_staff_logged_in()) {
            redirect(admin_url());
        }
        $this->form_validation->set_rules('email', _l('admin_auth_login_email'), 'trim|required|valid_email|callback_email_exists');
        if ($this->input->post()) {
            if ($this->form_validation->run() !== false) {
                $success = $this->Authentication_model->forgot_password($this->input->post('email'), true);
                if (is_array($success) && isset ($success['memberinactive'])) {
                    set_alert('danger', _l('inactive_account'));
                    redirect(admin_url('authentication/forgot_password'));
                } elseif ($success == true) {
                    set_alert('success', _l('check_email_for_resetting_password'));
                    // redirect(admin_url('authentication'));
                    $this->db->where('email', $this->input->post('email'));
                    $staff_data = $this->db->get(db_prefix() . 'staff');
                    $current_role = get_current_staff_role($this, $staff_data->row()->staffid);
                    if($current_role == 1){
                        redirect(admin_url('authentication/ldteam'));
                    }else if($current_role == 2){
                        redirect(admin_url('authentication/broker'));
                    }else if($current_role == 4){
                        redirect(admin_url('authentication'));
                    }else if($current_role == 6){
                        redirect(admin_url('authentication/adminbroker'));
                    }else if($current_role == 7){
                        redirect(admin_url('authentication/clerk'));
                    }else if($current_role == 8){
                        redirect(admin_url('authentication/officer'));
                    }else if($current_role == 9){
                        redirect(admin_url('authentication/hr'));
                    }
                } else {
                    set_alert('danger', _l('error_setting_new_password_key'));
                    redirect(admin_url('authentication/forgot_password'));
                }
            }
        }
        $this->load->view('authentication/forgot_password');
    }

    public function reset_password($staff, $userid, $new_pass_key)
    {
        if (!$this->Authentication_model->can_reset_password($staff, $userid, $new_pass_key)) {
            set_alert('danger', _l('password_reset_key_expired'));
            redirect(admin_url('authentication'));
        }
        $this->form_validation->set_rules('password', _l('admin_auth_reset_password'), 'required');
        $this->form_validation->set_rules('passwordr', _l('admin_auth_reset_password_repeat'), 'required|matches[password]');
        if ($this->input->post()) {
            if ($this->form_validation->run() !== false) {
                hooks()->do_action('before_user_reset_password', [
                    'staff' => $staff,
                    'userid' => $userid,
                ]);
               $current_role = get_current_staff_role($this, $userid);
                $success = $this->Authentication_model->reset_password($staff, $userid, $new_pass_key, $this->input->post('passwordr', false));
                if (is_array($success) && $success['expired'] == true) {
                    set_alert('danger', _l('password_reset_key_expired'));
                } elseif ($success == true) {
                    hooks()->do_action('after_user_reset_password', [
                        'staff' => $staff,
                        'userid' => $userid,
                    ]);
                    set_alert('success', _l('password_reset_message'));
                } else {
                    set_alert('danger', _l('password_reset_message_fail'));
                }
                // redirect(admin_url('authentication'));
                if($current_role == 1){
                    redirect(admin_url('authentication/ldteam'));
                }else if($current_role == 2){
                    redirect(admin_url('authentication/broker'));
                }else if($current_role == 4){
                    redirect(admin_url('authentication'));
                }else if($current_role == 6){
                    redirect(admin_url('authentication/adminbroker'));
                }else if($current_role == 7){
                    redirect(admin_url('authentication/clerk'));
                }else if($current_role == 8){
                    redirect(admin_url('authentication/officer'));
                }else if($current_role == 9){
                    redirect(admin_url('authentication/hr'));
                }
            }
        }
        $this->load->view('authentication/reset_password');
    }

    public function set_password($staff, $userid, $new_pass_key)
    {
        if (!$this->Authentication_model->can_set_password($staff, $userid, $new_pass_key)) {
            set_alert('danger', _l('password_reset_key_expired'));
            if ($staff == 1) {
                redirect(admin_url('authentication'));
            } else {
                redirect(site_url('authentication'));
            }
        }
        $this->form_validation->set_rules('password', _l('admin_auth_set_password'), 'required');
        $this->form_validation->set_rules('passwordr', _l('admin_auth_set_password_repeat'), 'required|matches[password]');
        if ($this->input->post()) {
            if ($this->form_validation->run() !== false) {
                $success = $this->Authentication_model->set_password($staff, $userid, $new_pass_key, $this->input->post('passwordr', false));
                if (is_array($success) && $success['expired'] == true) {
                    set_alert('danger', _l('password_reset_key_expired'));
                } elseif ($success == true) {
                    set_alert('success', _l('password_reset_message'));
                } else {
                    set_alert('danger', _l('password_reset_message_fail'));
                }
                if ($staff == 1) {
                    redirect(admin_url('authentication'));
                } else {
                    redirect(site_url());
                }
            }
        }
        $this->load->view('authentication/set_password');
    }

    public function logout()
    {
        $staff_role = get_current_staff_role($this, get_staff_user_id());
        $this->Authentication_model->logout();
        hooks()->do_action('after_user_logout');
        if($staff_role == 1){
            redirect(admin_url('authentication/ldteam'));
        }else if($staff_role == 2){
            redirect(admin_url('authentication/broker'));
        }else if($staff_role == 4){
            redirect(admin_url('authentication'));
        }else if($staff_role == 6){
            redirect(admin_url('authentication/adminbroker'));
        }else if($staff_role == 7){
            redirect(admin_url('authentication/clerk'));
        }else if($staff_role == 8){
            redirect(admin_url('authentication/officer'));
        }else if($staff_role == 9){
            redirect(admin_url('authentication/hr'));
        }
    }

    public function email_exists($email)
    {
        $total_rows = total_rows(db_prefix() . 'staff', [
            'email' => $email,
        ]);
        if ($total_rows == 0) {
            $this->form_validation->set_message('email_exists', _l('auth_reset_pass_email_not_found'));

            return false;
        }

        return true;
    }

    public function recaptcha($str = '')
    {
        return do_recaptcha_validation($str);
    }

    public function get_qr()
    {
        if (!is_staff_logged_in()) {
            ajax_access_denied();
        }

        $company_name = preg_replace('/:/', '-', get_option('companyname'));

        if ($company_name == '') {
            // Colons is not allowed in the issuer name
            $company_name = rtrim(preg_replace('/^https?:\/\//', '', site_url()), '/') . ' - CRM';
        }

        $data = $this->authentication_model->get_qr($company_name);
        $this->load->view('admin/includes/google_two_factor', $data);
    }
}