<?php
require_once __DIR__ . '/../../includes/functions.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_name(ADMIN_SESSION_NAME);
    session_start();
}

function admin_user(): ?array {
    return $_SESSION['admin_user'] ?? null;
}

function require_admin(): void {
    if (!admin_user()) {
        header('Location: /admin/login.php');
        exit;
    }
}

/** Call after require_admin(). Redirects non-matching roles back to the dashboard with a flash message. */
function require_role(string $role): void {
    $user = admin_user();
    if (!$user || $user['role'] !== $role) {
        flash_set('error', 'You do not have permission to access that page.');
        header('Location: /admin/index.php');
        exit;
    }
}

function admin_login(string $email, string $password): bool {
    $stmt = db()->prepare('SELECT * FROM users WHERE email = ? LIMIT 1');
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    if ($user && password_verify($password, $user['password_hash'])) {
        $_SESSION['admin_user'] = ['id' => $user['id'], 'name' => $user['name'], 'email' => $user['email'], 'role' => $user['role']];
        return true;
    }
    return false;
}

function admin_logout(): void {
    $_SESSION = [];
    session_destroy();
}

function csrf_token(): string {
    if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(32));
    return $_SESSION['csrf'];
}

function csrf_check(): bool {
    return isset($_POST['csrf']) && isset($_SESSION['csrf']) && hash_equals($_SESSION['csrf'], $_POST['csrf']);
}
