<?php
declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

function current_user(): ?array
{
    if (!isset($_SESSION['user_id'])) {
        return null;
    }

    static $user = null;
    if ($user === null) {
        $pdo = Database::getConnection();
        $stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id LIMIT 1');
        $stmt->execute(['id' => $_SESSION['user_id']]);
        $user = $stmt->fetch() ?: null;
    }

    return $user;
}

function require_login(): void
{
    if (!isset($_SESSION['user_id'])) {
        redirect('auth/login.php');
    }
}

function require_role(array $roles): void
{
    require_login();
    $user = current_user();

    if (!$user || !in_array($user['role'], $roles, true)) {
        // Simple 403
        http_response_code(403);
        echo 'Access denied.';
        exit;
    }
}

function is_super_admin(): bool
{
    $user = current_user();
    return $user && $user['role'] === 'super_admin';
}

function is_school_admin(): bool
{
    $user = current_user();
    return $user && $user['role'] === 'school_admin';
}

function is_teacher(): bool
{
    $user = current_user();
    return $user && $user['role'] === 'teacher';
}

function is_parent_user(): bool
{
    $user = current_user();
    return $user && $user['role'] === 'parent';
}
