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

class Login_m extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('rbac_m');
    }

    public function signin()
    {
        date_default_timezone_set('Asia/Kolkata');
        $username = $this->input->post('username');
        $password = $this->input->post('password');

        $this->db->where('username', $username);
        $this->db->where('password', $password);
        $query = $this->db->get('user');

        if ($query->num_rows() <= 0) {
            return 2;
        }

        $userdata = $query->row();
        if (!$userdata) {
            return 2;
        }

        if ($this->db->field_exists('status', 'user') && isset($userdata->status) && (int) $userdata->status === 0) {
            return 'disabled';
        }

        $is_super = false;
        $permissions = array();
        $role_name = '';
        $role_id = isset($userdata->role_id) ? (int) $userdata->role_id : 0;

        if ($this->rbac_m->tables_ready()) {
            $is_super = $this->rbac_m->is_superadmin_user($userdata);
            if ($is_super) {
                $permissions = array();
            } else {
                $permissions = $this->rbac_m->permissions_for_user($userdata);
                unset($permissions['_superadmin']);
            }
            if ($role_id) {
                $role = $this->rbac_m->get_role($role_id);
                if ($role) {
                    $role_name = $role->name;
                }
            }
        } else {
            // Pre-RBAC install: only Admin can sign in
            if ($userdata->usertype !== 'Admin') {
                return 2;
            }
            $is_super = true;
        }

        $data = array(
            'name' => $userdata->name,
            'usertype' => $userdata->usertype,
            'username' => $userdata->username,
            'userid' => $userdata->id,
            'uname' => $userdata->university_name,
            'logo1' => isset($userdata->logo1) ? $userdata->logo1 : '',
            'logo2' => isset($userdata->logo2) ? $userdata->logo2 : '',
            'role_id' => $role_id,
            'role_name' => $role_name,
            'is_superadmin' => $is_super ? 1 : 0,
            'permissions' => $permissions,
            'loggedin' => true,
        );

        // Cache app font preference for UI / exports
        $this->load->model('settings_m');
        if ($this->settings_m->table_ready()) {
            $data['ui_font_family'] = $this->settings_m->get('ui_font_family', 'ibm_plex');
        } else {
            $data['ui_font_family'] = 'ibm_plex';
        }

        $this->session->set_userdata($data);
        return 1;
    }
}
