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

class Sign_In extends CI_Controller {

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

    /**
     * @Function            : index 
     * @Used IN             : self
     * @Description         : used to load sign in page
     * @Developed By        : Unknown
     * @Start DateTime      : Unknown
     * @Update By           : Tania Akter
     * @Update Date         : 31-05-2016
     * @Parameter           : none
     * @Return              : none
     * @Status              : Available        
     * */
    function index() {
        $data = $this->welcome_model->generate_menu();  //view mega menu
        $person_id = $this->session->userdata('person_id');
        $data['quiz_start_url'] = $this->session->userdata('quiz_start_url');
        if ($person_id) {
            redirect();
        } else {
            $data['main_content'] = $this->load->view('front_end/sign_in', $data, TRUE);
            $this->load->view('front_end/master', $data);
        }
    }

    /**
     * @Function            : check_sign_in_login 
     * @Used IN             : front_end/sign-in.php
     * @Description         : used to check for sign in
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 18-04-2016 02:00 PM  
     * @Update By           : Tania Akter
     * @Update Date         : 31-05-2016     
     * @Parameter           : NULL
     * @View                : None
     * @Redirect            : front_end/sign-in.php, 
     * @Return              : NULL    
     * @Status              : Available       
     * */
    function check_sign_in() {
        $user_email = $this->input->post('person_sign_in_email', true);
        $user_password = md5($this->input->post('person_sign_in_password', true));
        $person_info = $this->person_model->get_person_information_for_login($user_email, $user_password);
        //echo '<pre>';
        //print_r($person_info);
       // exit();
        if ($person_info) {
            $this->check_sign_in_by_person_info($person_info);
        } else {
            $email_status = $this->person_model->check_person_email_existance($user_email);
            if ($email_status) {
                $this->invalid_password_submitted_by_user($email_status);
            } else {
                $sdata['exception'] = 'Please sign up to login!';
                $this->session->set_userdata($sdata);
                redirect('sign-in');
            }
        }
    }

    /**
     * @Function            : check_sign_in_by_person_info 
     * @Used IN             : function[check_sign_in] controller[sign_in]
     * @Description         : used to check sign in person by person info
     * @Update By           : Tania Akter
     * @Update Date         : 31-05-2016     
     * @Parameter           : NULL
     * @View                : None
     * @Redirect            : none
     * @Return              : NULL    
     * @Status              : Available       
     * */
    function check_sign_in_by_person_info($person_info) {
        if ($person_info->person_role == 1 || $person_info->person_role == 6 || $person_info->person_role == 2 || $person_info->person_role == 8) {
            $this->sign_in_by_backend_user();   // if user are super admin, admin or account office, quiz editor
        }
        if ($person_info->person_status == 0) { // if person is inactive
            $this->sign_in_by_inactive_person();
        }
        if ($person_info->person_status == 4) { // if organization teacher inactive by organization
            $this->sign_in_by_inactive_organization_teacher();
        }
        if ($person_info->person_status == 2 || $person_info->person_status == 3) { // if user are admin_inactive or archive
            $this->sign_in_by_archived_and_block_person();
        }
        if ($person_info->person_status == 1) { // if person is active
            
            $this->sign_in_by_active_person($person_info);
        }
    }

    /**
     * @Function            : sign_in_by_backend_user 
     * @Used IN             : function[check_sign_in_by_person_info] controller[sign_in]
     * @Description         : used to check if backend user want to sign in
     * @Update By           : Tania Akter
     * @Update Date         : 1-06-2016     
     * @Parameter           : NULL
     * @View                : None
     * @Redirect            : sign-in
     * @Return              : NULL    
     * @Status              : Available       
     * */
    function sign_in_by_backend_user() {
        $sdata = array();
        $sdata['exception'] = '<span style=color:red> Please sign up to login</span>';
        $this->session->set_userdata($sdata);
        redirect('sign-in');
    }

    /**
     * @Function            : sign_in_by_inactive_person 
     * @Used IN             : function[check_sign_in_by_person_info] controller[sign_in]
     * @Description         : used to check if inactive person want to sign in
     * @Update By           : Tania Akter
     * @Update Date         : 1-06-2016     
     * @Parameter           : NULL
     * @View                : None
     * @Redirect            : sign-in
     * @Return              : NULL    
     * @Status              : Available       
     * */
    function sign_in_by_inactive_person() {
        $sdata = array();
        $sdata['exception'] = '<span style=color:red> To Activate Account please check your email </span>';
        $this->session->set_userdata($sdata);
        redirect('sign-in');
    }

    /**
     * @Function            : sign_in_by_archived_and_block_person 
     * @Used IN             : function[check_sign_in_by_person_info] controller[sign_in] 
     * @Description         : used to check if block person by admin want to sign in
     * @Update By           : Tania Akter
     * @Update Date         : 1-06-2016     
     * @Parameter           : NULL
     * @View                : None
     * @Redirect            : sign-in
     * @Return              : NULL    
     * @Status              : Available       
     * */
    function sign_in_by_archived_and_block_person() {
        $sdata = array();
        $sdata['exception'] = '<span style=color:red> Please contact support</span>';
        $this->session->set_userdata($sdata);
        redirect('sign-in');
    }

    /**
     * @Function            : sign_in_by_inactive_organization_teacher 
     * @Used IN             : function[check_sign_in_by_person_info] controller[sign_in] 
     * @Description         : used to check if inactive organization teacher want to sign in
     * @Update By           : Tania Akter
     * @Update Date         : 1-06-2016     
     * @Parameter           : none
     * @View                : None
     * @Redirect            : sign-in
     * @Return              : NULL    
     * @Status              : Available       
     * */
    function sign_in_by_inactive_organization_teacher() {
        $sdata = array();
        $sdata['exception'] = '<span style=color:red> Please contact your organization to login </span>';
        $this->session->set_userdata($sdata);
        redirect('sign-in');
    }

    /**
     * @Function            : sign_in_by_active_person 
     * @Used IN             : function[check_sign_in_by_person_info] controller[sign_in]
     * @Description         : This function is used to check if active person want to sign in
     * @Update By           : Tania Akter
     * @Update Date         : 1-06-2016     
     * @Parameter           : $person_info (person info )
     * @View                : None
     * @Redirect            : $url
     * @Return              : NULL    
     * @Status              : Available       
     * */
    function sign_in_by_active_person($person_info) {
        $person_time_zone = $this->input->post('person_time_zone', true);
        $this->application_model->update_person_time_zone($person_info->person_id, $person_time_zone); // save person time in to database        
        $sdata['person_pc_info_id'] = $this->application_model->save_login_person_pc_information($person_info);
        $this->set_data_into_session($person_info, $sdata); // set date in to session
        
       

        $directory = 'content-library/' . $person_info->url . '/';      // Make directory for uploaded tinymce file
        if (!is_dir($directory)) {
            mkdir($directory, 0777, TRUE);
        }

        $quiz_start_url = $this->session->userdata('quiz_start_url');
        if($quiz_start_url) {
            redirect("$quiz_start_url");
        } else {
            // echo 'in active block';
            //exit();
            redirect();
        }
    }

    /**
     * @Function            : invalid_password_submitted_by_user 
     * @Used IN             : function[check_sign_in] controller[sign_in]
     * @Description         : This function is used to check when submitted email address is valid and password is invalid
     * @Update By           : Tania Akter
     * @Update Date         : 1-06-2016     
     * @Parameter           : $email_status (person info by email)
     * @View                : None
     * @Redirect            : forgot-password, sign-in 
     * @Return              : NULL    
     * @Status              : Available       
     * */
    function invalid_password_submitted_by_user($email_status) {
        $this->application_model->update_invalid_authetication($email_status->person_id, 2);
        $result = $this->application_model->select_invalid_authetication($email_status->person_id);
        if ($result->total_invalid_access == 3) {
            $this->application_model->delete_invalid_authentication($result->invalid_authentication_id);
            redirect('forgot-password');
        } else {
            $sdata['exception'] = 'Please enter your correct password';
            $this->session->set_userdata($sdata);
            redirect('sign-in');
        }
    }

    /**
     * @Function            : set_data_into_session
     * @Used IN             : function[sign_in_by_active_person] controller[sign_in]
     * @Description         : used to set active person infoformation into session
     * @Update By           : Tania Akter
     * @Update Date         : 31-05-2016
     * @Updated By          : Md Mashqur Ul Alam [19-03-17]    
     * @Parameter           : NULL
     * @View                : None
     * @Redirect            : none
     * @Return              : NULL    
     * @Status              : Available       
     * */
    function set_data_into_session($person_info, $data) {
        $sdata['login_start_time'] = time();
        //$sdata['time_offset'] = $data['time_offset'];
        $sdata['person_pc_info_id'] = $data['person_pc_info_id'];
        $sdata['person_id'] = $person_info->person_id;
        $sdata['person_url'] = $person_info->url;
        $sdata['person_role'] = $person_info->person_role;
        $sdata['person_status'] = $person_info->person_status;        
        $sdata['resource_person_type'] = $this->person_model->get_resource_person_type($person_info->person_id);        
      
        // anytime this session code will be deleted
        $sdata['user_id'] = $person_info->person_id;
        $sdata['user_email'] = $person_info->person_email;
        $sdata['profile_id'] = $person_info->url;
        $sdata['user_role'] = $person_info->person_role;
        $sdata['person_first_name'] = $person_info->person_first_name;
        $sdata['person_last_name'] = $person_info->person_last_name;
        // anytime this session code will be deleted
        $this->session->set_userdata($sdata);
        $_SESSION['upload_dir'] = '/source/' . $person_info->url . '/';
        $_SESSION['current_path'] = '../source/' . $person_info->url . '/';
    }

    /** ----------------------------------- forgot password start ----------------------------------------* */

    /**
     * @Function            : email_varify_for_password [moved from registration @controller]
     * @Used IN             : front_end/sign_in     line--61
     *                        front_end/forgot_password     line----23
     * @Description         : used to forgot password varify
     * Developed By         : Unknown
     * @Developed date      : Unknown
     * @Update By           : Tania Akter
     * @Update Date         : 02-06-2016     
     * @Parameter           : none
     * @View                : none
     * @Redirect            : none
     * @Return              : none   
     * @Status              : Available       
     * */
    function email_varify_for_password() {
        if($this->session->person_id){
            redirect();
        }
        $data = $this->welcome_model->generate_menu();     //view mega menu   
        $this->email_varify_for_password_form_validation();
        if ($this->form_validation->run() == FALSE) {
            //$data['captcha'] = $this->sign_up_model->generate_captcha();
            $data['main_content'] = $this->load->view('front_end/forgot_password', $data, TRUE);
            $this->load->view('front_end/master', $data);
        } else {
            $person_email = $this->input->post('person_email', TRUE);
            $result = $this->sign_up_model->check_user_email_info($person_email);
            $this->sign_up_model->password_recovery_request_status($result->person_id);
            $this->send_email_to_user_for_forgot_password($result);
        }
    }

    /**
     * @Function            : email_varify_for_password_form_validation 
     * @Used IN             : function[email_varify_for_password] controller[sign_in]
     * @Description         : used to forgot password form validation
     * Developed By         : Tania Akter
     * @Developed date      : 02-06-2016     
     * @Parameter           : none
     * @View                : none
     * @Redirect            : none
     * @Return              : none    
     * @Status              : Available       
     * */
    function email_varify_for_password_form_validation() {
        $this->form_validation->set_rules('person_email', 'Email', 'required|trim|callback_check_email_from_forget_password');
        //$this->form_validation->set_rules('captcha', 'captcha', 'required|trim|strip_tags|callback_check_captcha_from_forget_password');
    }

    /**
     * @Function            : check_email_from_forget_password 
     * @Used IN             : function[email_varify_for_password_form_validation] controller[sign_in]
     * @Description         : used to check email for forgot password
     * Developed By         : Unknown
     * @Developed date      : Unknown   
     * @Parameter           : $person_email
     * @View                : none
     * @Redirect            : none
     * @Return              : true, false (show validation message)  
     * @Status              : Available       
     * */
    function check_email_from_forget_password($person_email) {
        $result = $this->sign_up_model->check_user_email_info($person_email);      //02-06-2016
        if ($result) {
            return TRUE;    //no need to show error(validation) message
        } else {
            $this->form_validation->set_message('check_email_from_forget_password', '<span style=color:red>You are Not Registered User!!! Please Sign Up</span>');
            return FALSE; //show error(validation) message
        }
    }

    
    /**
     * @Function            : send_email_to_user_for_forgot_password 
     * @Used IN             : function[email_varify_for_password] controller[sign_in]
     * @Description         : used to send email for password reset
     * Developed By         : Tania Akter
     * @Developed date      : 02-06-2016  
     * @Parameter           : $result (array contain person info)
     * @View                : mailscripts/email_to_user_password
     * @Redirect            : sign-in
     * @Return              : none  
     * @Status              : Available       
     * */
    function send_email_to_user_for_forgot_password($result) {
        $mdata = array();
        $mdata['person_id'] = $result->person_id;
        $mdata['person_name'] = $result->person_first_name;
        $mdata['person_password'] = $result->person_password;
        $mdata['from_address'] = 'no-replay@talhatraining.com';
        $mdata['company_name'] = 'Talha Training';
        $mdata['admin_name'] = 'Talha Training';
        $mdata['to_address'] = $this->input->post('person_email', true);
        $mdata['subject'] = 'Recover Password';
        $id = $this->encryption->encrypt($result->person_id);
        $p_id = str_replace("/", "%F2", $id);
        $mdata['site_link'] = base_url() . 'recover-password/' . $p_id;
        $this->mailer_model->send_email($mdata, 'email_to_user_password');
        $sdata['message'] = 'Reset password link sent to your mail';
        $this->session->set_userdata($sdata);
        redirect('sign-in');
    }

    /**
     * @Function            : check_email_forgot_password 
     * @Used IN             : front_end/forgot_password     line-33
     * @Description         : used to check user email exist in db
     * Developed By         : Tania Akter
     * @Developed date      : 05-06-2016  
     * @Parameter           : none
     * @View                : none
     * @Redirect            : none
     * @Return              : none  
     * @Status              : Available       
     * */
    function check_email_forgot_password() {
        $forgot_password_email = $this->input->post('forgot_password_email', TRUE);
        $result = $this->sign_up_model->check_user_email_info($forgot_password_email);
        if ($result) {
            echo 1;     //if user given email address found in db it echo 1
        } else {
            echo 2;     //if user given email address not found in db it echo 2
        }
    }

    /**
     * @Function            : password_recover_form 
     * @Used IN             : function[send_email_to_user_for_forgot_password] controller[sign_in]
     * @Description         : used to set person_id on session and redirect password reset email to recover password form
     * Developed By         : Unknown
     * @Developed date      : Unknown   
     * @Parameter           : $p_id(person id sent from reset password mail)
     * @View                : none
     * @Redirect            : reset-password
     * @Return              : none   
     * @Status              : Available       
     * */
    function password_recover_form($p_id) {
        $sdata['p_id'] = $p_id;
        $this->session->set_userdata($sdata);
        redirect('reset-password');
    }

    /**
     * @Function            : reset_password 
     * @Used IN             : function[password_recover_form] controller[sign_in]
     *                        front_end/recover_password
     * @Description         : to recover passwords
     * Developed By         : Unknown
     * @Developed date      : Unknown 
     * @Update              : Tania Akter
     * @Updated date        : 05-06-2016 
     * @Parameter           : none
     * @View                : front_end/recover_password , 
     * @Redirect            : none
     * @Return              : none  
     * @Status              : Available       
     * */
    function reset_password() {
        if($this->session->userdata('person_id')){
            redirect();
        }else{
            $data = $this->welcome_model->generate_menu();      //used for view mega menu
            $person_password = md5($this->input->post('person_password', TRUE));
            // $confirm_password = md5($this->input->post('confirm_password', TRUE));
            $person_id = $this->person_id_decode();         //used to decode person id
            $data['person_id'] = $person_id;
            $data['person_info'] = $this->sign_up_model->select_recovery_status($person_id);    //used to select send request for password recovery by person_id //send_request=1;request_accepted=0
            if (!$data['person_info']) {
                $this->recovry_password_request_status_not_found();
            }
            $this->recover_password_form_validation();      //used to validate password recovery form

            if ($this->form_validation->run() == FALSE) {
                $data['main_content'] = $this->load->view('front_end/recover_password', $data, TRUE);
                $this->load->view('front_end/master', $data);
            } else {
                $this->recover_password_matched($data['person_info']->person_id, $person_password);
            }
        }
    }

    /**
     * @Function            : person_id_decode 
     * @Used IN             : function[reset_password] controller[sign_in]
     * @Description         : used to decode person_id
     * Developed By         : Unknown
     * @Developed date      : Unknown   
     * @Update              : Tania Akter
     * @ Update Date        : 05-06-2016
     * @Parameter           : none
     * @View                : none
     * @Redirect            : none
     * @Return              : person_id 
     * @Status              : Available       
     * */
    function person_id_decode() {
        $p_id = $this->session->userdata('p_id');
        $pe_id = str_replace("%F2", "/", $p_id);
        return $this->encryption->decrypt($pe_id);
    }

    /**
     * @Function            : recovry_password_request_status_not_found 
     * @Used IN             : function[reset_password] controller[sign_in]
     * @Description         : used to show validation message when recovery password request not found
     * Developed By         : Unknown
     * @Developed date      : Unknown   
     * @Update              : Tania Akter
     * @ Update Date        : 05-06-2016
     * @Parameter           : none
     * @View                : none
     * @Redirect            : forgot-password
     * @Return              : none  
     * @Status              : Available       
     * */
    function recovry_password_request_status_not_found() {
        $sdata['message'] = '<span style=color:red> Your code has expired. For security reasons there’s a time limit for temporary codes and the one we’ve sent you has now expired. Please enter your email address and we’ll send you a new code.</span>';
        $this->session->set_userdata($sdata);
        redirect('forgot-password');
    }

    /**
     * @Function            : recover_password_form_validation 
     * @Used IN             : function[reset_password] controller[sign_in]
     * @Description         : used to recover password form validation 
     * Developed By         : Unknown
     * @Developed date      : Unknown   
     * @Update              : Tania Akter
     * @ Update Date        : 05-06-2016
     * @Parameter           : none
     * @View                : none
     * @Redirect            : none
     * @Return              : none   
     * @Status              : Available       
     * */
    function recover_password_form_validation() {
        $this->form_validation->set_rules('person_password', 'Password', 'required|min_length[6]|callback_password_check');
        $this->form_validation->set_rules('confirm_password', 'Confirm password', 'required|min_length[6]|callback_password_check');
    }

    /**
     * @Function            : password_check 
     * @Used IN             : function[recover_password_form_validation] controller[sign_in]
     * @Description         : used to check password
     * Developed By         : Unknown
     * @Developed date      : Unknown   
     * @Update              : Tania Akter
     * @ Update Date        : 05-06-2016
     * @Parameter           : $str (password type by user)
     * @View                : none
     * @Redirect            : none
     * @Return              : true, false(validation message)  
     * @Status              : Available       
     * */
    function password_check($str) {
        $person_password = $this->input->post('person_password', TRUE);
        $confirm_password = $this->input->post('confirm_password', TRUE);
        if (strlen($str) < 6) {
            $this->form_validation->set_message('password_check', 'Minimum six Charecter');
            return FALSE;
        } else if (preg_match('#[0-9]#', $str) && preg_match('#[a-z]#', $str)) {
            if ($person_password == $confirm_password) {
                return TRUE;
            } else {
                $this->form_validation->set_message('password_check', 'Password Not Matched with Confirm Password !!!');
                return FALSE;
            }
        } else {
            $this->form_validation->set_message('password_check', 'password Must be contain minimum one Capital one small letter and one special charecter (minimum length 6)');
            return FALSE;
        }
    }

    /**
     * @Function            : recover_password_matched 
     * @Used IN             : function[reset_password] controller[sign_in]
     * @Description         : used to send recover password suceefull mail
     * Developed By         : Unknown
     * @Developed date      : Unknown   
     * @Update              : Tania Akter
     * @ Update Date        : 05-06-2016
     * @Parameter           : $person_id, $person_password
     * @View                : none
     * @Redirect            : none
     * @Return              : none   
     * @Status              : Available       
     * */
    function recover_password_matched($person_id, $person_password) {
        $this->sign_up_model->recover_person_password($person_id, $person_password);
        $sdata = array();
        $sdata['message'] = 'Password Recovery Successfull. Now you can Sign in';
        $this->session->set_userdata($sdata);
        $data['person_info'] = $this->profile_model->person_info_by_id($person_id);
        $this->send_recover_password_successfull_mail($data);
    }

    /**
     * @Function            : send_recover_password_successfull_mail 
     * @Used IN             : function[recover_password_matched] controller[sign_in]
     * @Description         : used to send password recover successfull mail
     * Developed By         : Unknown
     * @Developed date      : Unknown   
     * @Update              : Tania Akter
     * @ Update Date        : 05-06-2016
     * @Parameter           : $data(array contain person info), $person_id
     * @View                : mailscripts/reseted_password_mail
     * @Redirect            : sign-in
     * @Return              : none   
     * @Status              : Available       
     * */
    function send_recover_password_successfull_mail($data) {
        $mdata = array();
        $mdata['person_id'] = $data['person_info']->person_id;
        $mdata['person_name'] = $data['person_info']->person_first_name . ' ' . $data['person_info']->person_last_name;
        $mdata['from_address'] = 'no-replay@talhatraining.com';
        $mdata['company_name'] = 'Talha Training';
        $mdata['admin_name'] = 'Talha Training';
        $mdata['to_address'] = $data['person_info']->person_email;
        $mdata['subject'] = 'Reset password mail';
        $mdata['site_link'] = base_url() . 'sign-in/';
        $this->mailer_model->send_email($mdata, 'reseted_password_mail');
        redirect('sign-in');
    }

}