<?php
// config/auth.php

declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/** Check if user is logged in */
function is_logged_in(): bool
{
    return isset($_SESSION['user']) && is_array($_SESSION['user']);
}

/** Get logged in user array or null */
function current_user(): ?array
{
    return $_SESSION['user'] ?? null;
}

/** Force login */
function require_login(): void
{
    if (!is_logged_in()) {
        header("Location: /school-crm/public/index.php");
        exit;
    }
}

/** Require a specific role */
function require_role(string $role): void
{
    require_login();
    $u = current_user();
    if (!$u || ($u['role'] ?? '') !== $role) {
        http_response_code(403);
        exit("403 Forbidden");
    }
}

/** Require Admin */
function require_admin(): void
{
    require_role('ADMIN');
}

/** Require Rep */
function require_rep(): void
{
    require_role('REP');
}

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

function csrf_validate(?string $token): bool
{
    return is_string($token) && isset($_SESSION['csrf']) && hash_equals($_SESSION['csrf'], $token);
}
if (!function_exists('require_rep')) {
    function require_rep(): void
    {
        require_login();
        $u = current_user();
        if (!$u || ($u['role'] ?? '') !== 'REP') {
            http_response_code(403);
            exit("403 Forbidden");
        }
    }
}
