<?php
declare(strict_types=1);

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

function isAuthenticated(): bool
{
    return isset($_SESSION["user_id"]);
}

function requireAuth(): void
{
    if (!isAuthenticated()) {
        header("Location: /PIS/login.php");
        exit;
    }
}

function currentUserRole(): string
{
    return $_SESSION["user_role"] ?? "utilisateur";
}

function isAdmin(): bool
{
    return currentUserRole() === "admin";
}

function isSecretaire(): bool
{
    return currentUserRole() === "secretaire";
}

function isUtilisateur(): bool
{
    return currentUserRole() === "utilisateur";
}

function hasRole(array $roles): bool
{
    return in_array(currentUserRole(), $roles, true);
}

function requireAdmin(): void
{
    if (!isAdmin()) {
        $_SESSION["flash"] = ["type" => "error", "message" => "Acces refuse."];
        header("Location: /PIS/index.php");
        exit;
    }
}

function requireAdminOrSecretaire(): void
{
    if (!hasRole(["admin", "secretaire"])) {
        $_SESSION["flash"] = ["type" => "error", "message" => "Acces refuse."];
        header("Location: /PIS/index.php");
        exit;
    }
}

function requireRole(array $roles): void
{
    if (!hasRole($roles)) {
        $_SESSION["flash"] = ["type" => "error", "message" => "Acces refuse."];
        header("Location: /PIS/index.php");
        exit;
    }
}
