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

/**
 * Auth Controller
 * 
 * @property CI_Input $input
 * @property CI_Form_validation $form_validation
 * @property CI_Session $session
 * @property User_model $User_model
 * @property Log_model $Log_model
 */
class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('User_model');
        $this->load->model('Log_model');
    }

    /**
     * Login page
     */
    public function login() {
        // Redirect if already logged in
        if (is_logged_in()) {
            $this->_redirect_based_on_role();
            return;
        }

        if ($this->input->method() == 'post') {
            $this->_handle_login();
        } else {
            $this->load->view('auth/login');
        }
    }

    /**
     * Handle login submission
     */
    private function _handle_login() {
        $this->form_validation->set_rules('username', 'Username', 'required|trim');
        $this->form_validation->set_rules('password', 'Password', 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('auth/login');
            return;
        }

        $username = $this->input->post('username');
        $password = $this->input->post('password');

        // Check failed attempts
        $failed_attempts = $this->Log_model->get_failed_attempts($username, 30);
        if ($failed_attempts >= 5) {
            $this->Log_model->log_login(null, $username, 'failed', 'Account locked due to multiple failed attempts');
            set_flash('error', 'Account temporarily locked. Please try again later.');
            redirect('login');
            return;
        }

        // Verify credentials
        $user = $this->User_model->verify_password($username, $password);

        if ($user && $user->status == 'active') {
            // Check portal access restrictions
            $current_portal = $this->config->item('portal_id');
            $allowed_portals = $user->allowed_portals;
            
            // Verify user can access this portal
            if (!empty($allowed_portals) && $allowed_portals !== '*') {
                $allowed_list = array_map('trim', explode(',', $allowed_portals));
                
                if (!in_array($current_portal, $allowed_list)) {
                    // User cannot access this portal
                    $this->Log_model->log_login(null, $username, 'failed', 'Portal access denied - user not authorized for this portal');
                    set_flash('error', 'You do not have access to this portal.');
                    redirect('login');
                    return;
                }
            }
            
            // Set session
            $session_data = [
                'user_id' => $user->id,
                'username' => $user->username,
                'email' => $user->email,
                'role' => $user->role,
                'portal_id' => $current_portal,
                'allowed_portals' => $user->allowed_portals,
                'logged_in' => TRUE
            ];
            $this->session->set_userdata($session_data);

            // Log successful login
            $this->Log_model->log_login($user->id, $username, 'success');
            $this->Log_model->log_audit($user->id, 'Login', 'Auth', 'User logged in successfully');

            set_flash('success', 'Welcome back, ' . $user->username . '!');
            $this->_redirect_based_on_role();
        } else {
            // Log failed attempt
            $reason = !$user ? 'Invalid credentials' : 'Account is inactive';
            $this->Log_model->log_login(null, $username, 'failed', $reason);

            set_flash('error', 'Invalid username or password.');
            redirect('login');
        }
    }

    /**
     * Logout
     */
    public function logout() {
        if (is_logged_in()) {
            $user_id = current_user_id();
            $username = current_username();

            // Log logout
            $this->Log_model->log_audit($user_id, 'Logout', 'Auth', 'User logged out');

            // Destroy session
            $this->session->sess_destroy();

            set_flash('success', 'You have been logged out successfully.');
        }

        redirect('login');
    }

    /**
     * Redirect based on user role
     */
    private function _redirect_based_on_role() {
        if (is_admin()) {
            redirect('admin/dashboard');
        } else {
            redirect('user/dashboard');
        }
    }
}
