<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

function is_super_admin(): bool
{
    return strtolower((string) ($_SESSION['role_name'] ?? '')) === 'super admin';
}

function user_permissions(?int $userId = null): array
{
    $userId ??= isset($_SESSION['user_id']) ? (int) $_SESSION['user_id'] : 0;

    if ($userId <= 0) {
        return [];
    }

    if (
        isset($_SESSION['_permissions_loaded_for'], $_SESSION['permissions'])
        && (int) $_SESSION['_permissions_loaded_for'] === $userId
    ) {
        return (array) $_SESSION['permissions'];
    }

    $permissions = array_map(
        static fn(array $row): string => $row['permission_key'],
        db_fetch_all(
            'SELECT DISTINCT p.permission_key
             FROM permissions p
             INNER JOIN role_permissions rp ON rp.permission_id = p.id
             INNER JOIN users u ON u.role_id = rp.role_id
             WHERE u.id = :user_id',
            ['user_id' => $userId]
        )
    );

    $_SESSION['permissions'] = $permissions;
    $_SESSION['_permissions_loaded_for'] = $userId;

    return $permissions;
}

function can(string $permission): bool
{
    if (empty($_SESSION['user_id'])) {
        return false;
    }

    if (is_super_admin()) {
        return true;
    }

    return in_array($permission, user_permissions(), true);
}

function require_permission(string $permission): void
{
    if (!can($permission)) {
        abort_request(403, 'Access denied', 'Your account does not have permission to access this area.');
    }
}

function is_club_admin(): bool
{
    return strtolower((string) ($_SESSION['role_name'] ?? '')) === 'club admin';
}

function require_club_scope(?int $clubId): void
{
    if (!is_club_admin()) {
        return;
    }

    if ($clubId === null || user_club_id() !== $clubId) {
        abort_request(403, 'Club scope denied', 'Club Admin users can only access records belonging to their assigned club.');
    }
}
