<?php
/**
 * Authentication Controller
 * Handles user login, logout, and session management
 *
 * FILE: /var/www/html/barber/app/controllers/AuthController.php
 * 
 * FIXES APPLIED:
 * - Changed all redirect('login') to redirect('auth/login')
 * - This ensures proper URL routing to /barber/auth/login
 *
 * @package RashwansBarber
 * @version 1.1
 * @updated November 21, 2025
 */

class AuthController extends Controller {

    private $userModel;

    public function __construct() {
        parent::__construct();
        $this->userModel = $this->model('User');
    }

    /**
     * Show login page
     * URL: /auth/login
     */
    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 form submission
     * URL: /auth/processLogin (POST)
     */
    public function processLogin() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            // FIX: Changed from 'login' to 'auth/login'
            $this->redirect('auth/login');
        }

        // Validate CSRF token
        $csrfToken = $_POST['csrf_token'] ?? '';
        if (!$this->validateCSRF($csrfToken)) {
            $this->setFlash('Invalid security token. Please try again.', 'error');
            // FIX: Changed from 'login' to 'auth/login'
            $this->redirect('auth/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');
            // FIX: Changed from 'login' to 'auth/login'
            $this->redirect('auth/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');
            // FIX: Changed from 'login' to 'auth/login'
            $this->redirect('auth/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');
            // FIX: Changed from 'login' to 'auth/login'
            $this->redirect('auth/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 and redirect to login page
     * URL: /auth/logout
     */
    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');

        // FIX: Changed from 'login' to 'auth/login'
        $this->redirect('auth/login');
    }

    /**
     * Check session status (AJAX endpoint)
     * URL: /auth/checkSession
     */
    public function checkSession() {
        $response = [
            'logged_in' => $this->isLoggedIn(),
            'user' => $this->isLoggedIn() ? $this->getCurrentUser() : null
        ];

        $this->json($response);
    }
}
?>
