<?php
/**
 * Authentication Controller
 * Handles user login, logout, and session management
 * 
 * @package RashwansBarber
 * @version 1.0
 */

class AuthController extends Controller {
    
    private $userModel;
    
    public function __construct() {
        parent::__construct();
        $this->userModel = $this->model('User');
    }
    
    /**
     * Show login page
     */
    public function login() {
        // If already logged in, redirect to dashboard
        if ($this->isLoggedIn()) {
            $this->redirect('dashboard');
        }
        
        $data = [
            'title' => 'Login - ' . config('app_name'),
            'error' => $_GET['error'] ?? null
        ];
        
        $this->view('auth/login', $data);
    }
    
    /**
     * Process login
     */
    public function processLogin() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('login');
        }
        
        // Validate CSRF token
        $csrfToken = $_POST['csrf_token'] ?? '';
        if (!$this->validateCSRF($csrfToken)) {
            $this->setFlash('Invalid security token. Please try again.', 'error');
            $this->redirect('login');
        }
        
        // Get and sanitize input
        $username = $this->sanitize($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $rememberMe = isset($_POST['remember_me']);
        
        // Validate input
        if (empty($username) || empty($password)) {
            $this->setFlash('Please enter both username and password.', 'error');
            $this->redirect('login');
        }
        
        // Attempt login
        $user = $this->userModel->login($username, $password);
        
        if (!$user) {
            $this->logAudit('failed_login', 'users', null, null, ['username' => $username]);
            $this->setFlash('Invalid username or password.', 'error');
            $this->redirect('login');
        }
        
        // Check for account locked
        if (is_array($user) && isset($user['error']) && $user['error'] === 'account_locked') {
            $this->setFlash('Your account has been locked due to multiple failed login attempts. Please contact an administrator.', 'error');
            $this->redirect('login');
        }
        
        // Set session variables
        $_SESSION['user_id'] = $user['user_id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['full_name'] = $user['full_name'];
        $_SESSION['role_id'] = $user['role_id'];
        $_SESSION['role_name'] = $user['role_name'];
        $_SESSION['location_id'] = $user['location_id'];
        $_SESSION['location_name'] = $user['location_name'];
        $_SESSION['permissions'] = json_decode($user['permissions'], true);
        $_SESSION['logged_in'] = true;
        
        // Remember me functionality
        if ($rememberMe) {
            $token = bin2hex(random_bytes(32));
            setcookie('remember_token', $token, time() + (86400 * 30), '/'); // 30 days
            // TODO: Store token in database for validation
        }
        
        // Log successful login
        $this->logAudit('login', 'users', $user['user_id']);
        
        // Set success message
        $this->setFlash('Welcome back, ' . $user['full_name'] . '!', 'success');
        
        // Redirect to intended page or dashboard
        $redirectTo = $_SESSION['redirect_after_login'] ?? 'dashboard';
        unset($_SESSION['redirect_after_login']);
        
        $this->redirect($redirectTo);
    }
    
    /**
     * Logout user
     */
    public function logout() {
        // Log logout action
        if (isset($_SESSION['user_id'])) {
            $this->logAudit('logout', 'users', $_SESSION['user_id']);
        }
        
        // Clear session
        session_unset();
        session_destroy();
        
        // Clear remember me cookie
        if (isset($_COOKIE['remember_token'])) {
            setcookie('remember_token', '', time() - 3600, '/');
        }
        
        // Start new session for flash message
        session_start();
        $this->setFlash('You have been logged out successfully.', 'success');
        
        $this->redirect('login');
    }
    
    /**
     * Check session status (AJAX endpoint)
     */
    public function checkSession() {
        $response = [
            'logged_in' => $this->isLoggedIn(),
            'user' => $this->isLoggedIn() ? $this->getCurrentUser() : null
        ];
        
        $this->json($response);
    }
}
?>
