<?php 
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Loginmodel extends CI_Model 
{
    function __construct() {
        parent::__construct();
    }
    public function loginValidation() {
        $username  = trim($this->security->xss_clean($this->input->post('user_name')));
        $password  = trim($this->input->post('password')); // Do not xss_clean passwords, it breaks verification of special characters
        $captcha   = $this->security->xss_clean($this->input->post('captcha'));
        $captchaa  = $this->security->xss_clean($this->input->post('captchaa'));
        $captchab  = $this->security->xss_clean($this->input->post('captchab'));
        if (is_numeric($captchaa) && is_numeric($captchab) && is_numeric($captcha)) {
            $captchac = $captchaa + $captchab;
            if ($captcha == $captchac) {
                $this->db->select('a.*, b.branch_name, b.branch_code');
                $this->db->from('tbl_admin a');
                $this->db->join('tbl_branches b', 'a.branch_id = b.branch_id', 'left');
                $this->db->where('a.email', $username);
                $this->db->where('a.status', 'Active');
                $query = $this->db->get();
                if ($query->num_rows() > 0) {
                    $row = $query->row();
                    if (password_verify($password, $row->password)) {
                        $data = array(
                            'admin_id'      => $row->admin_id,
                            'name'          => $row->name,
                            'email'         => $row->email,
                            'mobile'        => $row->mobile,
                            'branch_id'     => $row->branch_id,
                            'branch_name'   => $row->branch_name,
                            'branch_code'   => $row->branch_code,
                            'role'          => $row->role,
                            'is_logged_in'  => true
                        );
                        $this->session->set_userdata($data);
                        return true;
                    } else {
                        log_message('error', 'Login failed: Wrong password for user ' . $username);
                        return false; // Wrong password
                    }
                } else {
                    log_message('error', 'Login failed: Email not found or inactive for user ' . $username);
                    return false; // Email not found or inactive
                }
            } else {
                log_message('error', 'Login failed: Wrong captcha answer');
                return false; // Wrong captcha answer
            }
        } else {
            log_message('error', 'Login failed: Invalid captcha values');
            return false; // Invalid captcha values
        }
    }
}