<?php

function can(array $user, string $module, string $action, PDO $pdo): bool
{
    if ($user['role'] === 'super_admin') {
        return true; // full override
    }

    $stmt = $pdo->prepare("
        SELECT can_view, can_create, can_edit, can_delete
        FROM role_permissions
        WHERE role = ?
        AND module_key = ?
        LIMIT 1
    ");

    $stmt->execute([$user['role'], $module]);
    $perm = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$perm) {
        return false;
    }

    return match ($action) {
        'view'   => (bool)$perm['can_view'],
        'create' => (bool)$perm['can_create'],
        'edit'   => (bool)$perm['can_edit'],
        'delete' => (bool)$perm['can_delete'],
        default  => false,
    };
}

function require_permission(array $user, string $module, string $action, PDO $pdo): void
{
    if (!can($user, $module, $action, $pdo)) {
        json_response(false, 'Access denied.', [], 403);
    }
}

function enforce_rsp_isolation(array $user, int $rsp_id): void
{
    if (!empty($user['rsp_id']) && $user['rsp_id'] !== $rsp_id) {
        json_response(false, 'RSP isolation violation.', [], 403);
    }
}

function log_admin_action(
    PDO $pdo,
    int $user_id,
    string $module,
    string $action,
    ?int $record_id = null
): void {
    $stmt = $pdo->prepare("
        INSERT INTO admin_audit_logs
        (user_id, module_key, action_type, record_id, ip_address, created_at)
        VALUES (?, ?, ?, ?, ?, NOW())
    ");

    $stmt->execute([
        $user_id,
        $module,
        $action,
        $record_id,
        $_SERVER['REMOTE_ADDR'] ?? null
    ]);
}