<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../models/User.php';

class Auth
{
    public static function startSession(): void
    {
        if (session_status() === PHP_SESSION_ACTIVE) {
            return;
        }
        session_name(SESSION_NAME);
        session_start([
            'cookie_httponly' => true,
            'cookie_samesite' => 'Lax',
            'use_strict_mode' => true,
        ]);
    }

    public static function attempt(string $username, string $password): bool
    {
        self::startSession();
        $userModel = new User();
        $user = $userModel->findByUsername($username);
        if (!$user || !password_verify($password, $user['password_hash'])) {
            return false;
        }
        if (!empty($user['suspended'])) {
            return false;
        }

        $_SESSION['auth'] = [
            'id' => (int)$user['id'],
            'username' => $user['username'],
            'role' => $user['role'],
        ];
        return true;
    }

    public static function user(): ?array
    {
        self::startSession();
        return $_SESSION['auth'] ?? null;
    }

    public static function check(): bool
    {
        return self::user() !== null;
    }

    /** Admin or manager may access the staff panel */
    public static function requireAdmin(): void
    {
        $user = self::user();
        if (!$user || !in_array($user['role'], ['admin', 'manager'], true)) {
            header('Location: ' . appPath('/admin/home.php'));
            exit;
        }
    }

    public static function isStaff(): bool
    {
        $user = self::user();
        return $user && in_array($user['role'], ['admin', 'manager'], true);
    }

    public static function logout(): void
    {
        self::startSession();
        $_SESSION = [];
        session_destroy();
    }
}
