<?php
declare(strict_types=1);

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

if (!function_exists('current_user_id')) {
    function current_user_id(): int
    {
        return (int)($_SESSION['user_id'] ?? 0);
    }
}

if (!function_exists('current_role')) {
    function current_role(): string
    {
        return strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
    }
}

if (!function_exists('current_branch_id')) {
    function current_branch_id(): int
    {
        return (int)($_SESSION['branch_id'] ?? 0);
    }
}

if (!function_exists('is_owner')) {
    function is_owner(): bool
    {
        return current_role() === 'OWNER';
    }
}

if (!function_exists('resolve_employee_id_from_user')) {
    function resolve_employee_id_from_user(PDO $pdo, int $userId): int
    {
        $st = $pdo->prepare("
            SELECT id
            FROM employees
            WHERE user_id = ?
            LIMIT 1
        ");
        $st->execute([$userId]);
        return (int)($st->fetchColumn() ?: 0);
    }
}

if (!function_exists('has_page_permission')) {
    function has_page_permission(PDO $pdo, string $permissionKey): bool
    {
        if (is_owner()) {
            return true;
        }

        $employeeId = resolve_employee_id_from_user($pdo, current_user_id());
        if ($employeeId <= 0) {
            return false;
        }

        $st = $pdo->prepare("
            SELECT 1
            FROM employee_permissions
            WHERE employee_id = ?
              AND permission_key = ?
            LIMIT 1
        ");
        $st->execute([$employeeId, $permissionKey]);

        return (bool)$st->fetchColumn();
    }
}

if (!function_exists('require_page_permission')) {
    function require_page_permission(PDO $pdo, string $permissionKey): void
    {
        if (!has_page_permission($pdo, $permissionKey)) {
            http_response_code(403);
            exit('غير مصرح');
        }
    }
}