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

class Login extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model("site_m");
        $this->load->model("user_m");
        $this->load->model("signin_m");
        $this->load->library("session");
         $this->load->helper('cookie');
        $this->load->library('updatechecker');
        $this->load->helper('language');
        $this->load->helper('date');
        $this->load->helper('form');
        $this->load->model("studentrelation_m");
        $this->load->model("grade_m");
        $this->load->library('form_validation');
        $this->load->library('sms/skooly_init');
        $this->data["siteinfos"] = $this->site_m->get_site();
        $siteInfo = $this->site_m->get_site();
        $this->_backendTheme = strtolower($siteInfo->backend_theme);
        $this->data['backendTheme'] = $this->_backendTheme;
        $this->_backendThemePath = 'assets/inilabs/themes/' . strtolower($siteInfo->backend_theme);
        $this->data['backendThemePath'] = $this->_backendThemePath;
    }
    
    protected function rules()
    {
        $rules = [
            [
                'field' => 'username',
                'label' => "Username",
                'rules' => 'trim|required|max_length[40]|xss_clean'
            ],
            [
                'field' => 'password',
                'label' => "Password",
                'rules' => 'trim|required|max_length[40]|xss_clean'
            ]
        ];

        if ( $this->data["siteinfos"]->captcha_status == 0 ) {
            $rules[] = [
                'field' => 'g-recaptcha-response',
                'label' => "captcha",
                'rules' => 'trim|required'
            ];
        }
        return $rules;
    }
    public function go_back()
    {  
       $this->session->sess_destroy();
       echo json_encode([
            'success' => true,
            'message' => 'User session expired. Please log in again.'
        ]);   
    }
    protected function rules_cpassword() {
		$rules = array(
				array(
					'field' => 'old_password',
					'label' => $this->lang->line('old_password'),
					'rules' => 'trim|required|max_length[40]|min_length[4]|xss_clean|callback_old_password_unique'
				),
				array(
					'field' => 'new_password',
					'label' => $this->lang->line('new_password'),
					'rules' => 'trim|required|max_length[40]|min_length[4]|xss_clean'
				),
				array(
					'field' => 're_password',
					'label' => $this->lang->line('re_password'),
					'rules' => 'trim|required|max_length[40]|min_length[4]|matches[new_password]|xss_clean'
				)
			);
		return $rules;
	}

    public function index() {
        if ( $this->data['siteinfos']->captcha_status == 0 ) {
            $this->load->library('recaptcha');
            $this->data['recaptcha'] = [
                'widget' => $this->recaptcha->getWidget(),
                'script' => $this->recaptcha->getScriptTag(),
            ];
        }

        $this->data['form_validation'] = 'No';
        $this->signin_m->loggedin() == FALSE || redirect(base_url('dashboard/index'));
        if($_POST) {
            $this->_setCookie();
            $rules = $this->rules();
            $this->form_validation->set_rules($rules);
            if ($this->form_validation->run() == FALSE) {
                $this->data['form_validation'] = validation_errors();
                $this->data["subview"]         = "signin/index";
                $this->load->view('_layout_signin', $this->data);
            } else {
                try {
                    $signinManager = $this->_signInManager();
                    if($signinManager['return']) {
                        $this->session->set_userdata('verified_login', 1);
                        redirect(base_url('dashboard/index'));                      
                        
                    } else {
                        $this->data['form_validation'] = $signinManager['message'];
                        $this->data["subview"]         = "signin/index";
                        $this->load->view('_layout_signin', $this->data);
                    }
                } catch(Exception $e){
                        $this->data['form_validation'] = $e->getMessage();
                        $this->data["subview"]         = "signin/index";
                        $this->load->view('_layout_signin', $this->data);
                }

            }
        } else {
            $this->data["subview"]         = "signin/index";
            $this->load->view('_layout_signin', $this->data);
            $this->session->sess_destroy();
        }
	}
	
	private function _setCookie()
    {
        if ( isset($_POST['remember']) ) {
            set_cookie('remember_username', $this->input->post('username'), time() + ( 86400 * 30 ));
            set_cookie('remember_password', $this->input->post('password'), time() + ( 86400 * 30 ));
        } else {
            delete_cookie('remember_username');
            delete_cookie('remember_password');
        }
    }

    public function resend_otp() {
        $user = $this->session->userdata('user');
        
        if (!$user) {
            echo json_encode([
                'success' => false,
                'message' => 'User session expired. Please log in again.'
            ]);
            return;
        }
    
        try {
			$verificationCode = random_int(1000, 9999);
			
            $this->session->set_userdata('otp_code', $verificationCode);
			$this->session->set_userdata('otp_expiration', time() + 60);
			
            SmsService::sendOTP($user, $user->usertypeID, $this->data, $verificationCode);
            $otp_expiration = $this->session->userdata('otp_expiration');
            $current_time = time();
            $remaining_seconds = max(0, $otp_expiration - $current_time);
            echo json_encode([
                'success' => true,
                'otp_expiration'=> $remaining_seconds,
                'message' => 'OTP has been resent successfully.'
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => 'Failed to resend OTP. Please try again.',
                'error' => $e->getMessage()
            ]);
        }
    }    
    
    public function verify(){
        $this->data['form_validation'] = "No";
        if ( $_POST ) {
            $entered_otp = $this->input->post('verification_code');

            if (time() < $this->session->userdata('otp_expiration')) {
                if ($entered_otp == $this->session->userdata('otp_code')) {
                    $this->session->unset_userdata('otp_code');
                    $this->session->unset_userdata('otp_expiration');
                    $this->session->set_userdata('verified_login', 1);

                    $user = $this->session->userdata('user');
                    if($user->usertypeID == 3){
					    $student = $this->studentrelation_m->get_single_student(array('srstudentID' => $user->studentID), TRUE);
					    SmsService::successfulSystemLogin($student, $student->usertypeID, $this->data);
					}else{
					     SmsService::successfulSystemLogin($user, $user->usertypeID, $this->data);
					}
                    
                    redirect(base_url('dashboard/index'));
                }else{
                    $this->data['form_validation'] = "Invalid verification code. Please try again.";
                }

            }else {
                $this->data['form_validation'] = "Your OTP has Expired.";
            }
            
        }
        
        $this->data['otp_expiration'] = $this->session->userdata('otp_expiration');
        
        $this->data["subview"]         = "signin/verify";
        $this->load->view('_layout_signin', $this->data);
        
    }
    
    private function _userChecker( $username, $password )
    {
        $tables   = [
            'student'     => 'student',
            'parents'     => 'parents',
            'teacher'     => 'teacher',
            'user'        => 'user',
            'systemadmin' => 'systemadmin'
        ];
        $userInfo = [ 'info' => [], 'userID' => 0, 'idName' => '' ];
        foreach ( $tables as $table ) {
            $user = $this->user_m->get_user_table($table, $username, $password);
            if ( customCompute($user) ) {
                $id                 = $table . 'ID';
                $userInfo['info']   = $user;
                $userInfo['userID'] = $user->$id;
                $userInfo['idName'] = $table . 'ID';
            }
        }
        return (object) $userInfo;
    }
    
    private function _signInManager()
    {
        $returnArray         = [ 'return' => true, 'message' => 'Success' ];
        $verifyValidUser     = true;
        $setting             = $this->data['siteinfos'];
        $lang                = $setting->language;
        $defaultSchoolYearID = $setting->school_year;
        $username            = $this->input->post('username');
        $password            = $this->input->post('password');
        $user                = $this->_userChecker($username, $password);
        $userID              = customCompute($user) ? $user->userID : 0;
        $user                = customCompute($user) ? $user->info : [];

        if ( isset($setting->captcha_status) && $setting->captcha_status == 0 ) {
            $captchaResponse = $this->recaptcha->verifyResponse($this->input->post('g-recaptcha-response'));
        } else {
            $captchaResponse = [ 'success' => true ];
        }

        if ( $returnArray['return'] ) {
            if ( $captchaResponse['success'] ) {
                if ( customCompute($user) ) {
                    $userType = $this->usertype_m->get_single_usertype([ 'usertypeID' => $user->usertypeID ]);
                    if ( customCompute($userType) ) {
                        if ( $user->active ) {
                            $this->_loginLog($user->usertypeID, $userID);
                            $session = [
                                "loginuserID"         => $userID,
                                "user"                => $user,
                                "name"                => $user->name,
                                "email"               => $user->email,
                                "usertypeID"          => $user->usertypeID,
                                'usertype'            => $userType->usertype,
                                "username"            => $user->username,
                                "photo"               => $user->photo,
                                "lang"                => $lang,
                                "defaultschoolyearID" => $defaultSchoolYearID,
                                "varifyvaliduser"     => $verifyValidUser,
                                "loggedin"            => true
                            ];

                            $this->session->set_userdata($session);
                            $returnArray = [ 'return' => true, 'message' => 'Success', 'user'=> $user ];
                        } else {
                            $returnArray = [ 'return' => false, 'message' => 'You are blocked' ];
                        }
                    } else {
                        $returnArray = [ 'return' => false, 'message' => 'This user role does not exist' ];
                    }
                } else {
                    $returnArray = [ 'return' => false, 'message' => 'Incorrect Signin' ];
                }
            } else {
                $captchaResponseError = ( is_array($captchaResponse['error-codes']) ) ? $captchaResponse['error-codes'][0] : $captchaResponse['error-codes'];
                $returnArray          = [ 'return' => false, 'message' => $captchaResponseError ];
            }
        } else {
            $returnArray = [ 'return' => false, 'message' => $returnArray['message'] ];
        }

        return $returnArray;
    }
    
    private function _loginLog( $userTypeID, $userID )
    {
        $getPreviousData = $this->loginlog_m->get_single_loginlog([
            'userID'     => $userID,
            'usertypeID' => $userTypeID,
            'ip'         => $this->updatechecker->getUserIP(),
            'browser'    => $this->updatechecker->getBrowser()->name,
            'logout'     => null
        ]);

        if ( customCompute($getPreviousData) ) {
            $this->loginlog_m->update_loginlog(['logout' => ( $getPreviousData->login + ( 60 * 5 ) )], $getPreviousData->loginlogID);
        }

        $this->loginlog_m->insert_loginlog([
            'ip'              => $this->updatechecker->getUserIP(),
            'browser'         => $this->updatechecker->getBrowser()->name,
            'operatingsystem' => $this->updatechecker->getBrowser()->platform,
            'login'           => strtotime(date('YmdHis')),
            'usertypeID'      => $userTypeID,
            'userID'          => $userID,
        ]);
    }

}