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

class Login extends CI_Controller {

	function __construct() {
		parent::__construct();
		date_default_timezone_set("Asia/Kolkata");
	}

	/**
	 * Load Login Method
	* 
	* @param1       
	* @return       view page
	* @access       public
	* @author       Manoj Kr Sah
	* @copyright    N/A
	* @link         application/login
	* @since        12th Jan 2026
	* @deprecated   N/A
	**/

	public function index(){
		
		if ($this->session->userdata('is_logged_in') === TRUE) {
			redirect(base_url('adminex/dashboard'));
		}

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

		if ($this->form_validation->run() === TRUE)
		{
			$data = $this->input->post();
			$data = array_map('trim', $data);
			$data = $this->security->xss_clean($data);
			
			$md5_data   = md5(trim($data['password']));
			$salt_key   = get_encript_id(trim($data['password']));
			$password   = $md5_data.$salt_key;
			$user_id    = $this->db->escape_like_str($data['username']);
			
			$credentials = array(
				'email'      => $user_id,
				'password'   => $password,
				'status' 	 => 1
			);

			$user_exsist = $this->CommonModel->RetriveRecordByWhere(TBL_USERS,$credentials)->row();
			
			if (!empty($user_exsist) && $user_exsist->email === $user_id ) 
			{
				$this->CommonModel->set_cookies($user_id,trim($data['password']));
				$this->CommonModel->unlock_account($user_id);
				$this->session->set_userdata([
					'user_id'      	=> $user_exsist->id,
					'user_name'   	=> $user_exsist->f_name.' '.$user_exsist->l_name,
					'user_email'   	=> $user_exsist->email,
					'user_status'   => $user_exsist->status,
					'is_logged_in' 	=> TRUE
				]);
				redirect(base_url('adminex/dashboard'));
			}
			else{
				$login_attempt = $this->CommonModel->block_account($user_id);
				if( $login_attempt >= PWD_BLOCK_LIMIT){
					$msg = AC_BLOCKED;
				}else{
					$msg = WRONG_PWD;
				}
				$this->session->set_flashdata('error', $msg.' Login Attempts '.$login_attempt);
				redirect(base_url('adminex'));
				exit();
			}
		}
		else{
			$data['meta_title'] = 'makhana';
			$data['meta_desc']  = 'makhana desc';
			$this->load->view('admin/login/login', $data);
		}
	}
}
