<?php
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../core/Auth.php';

function verifyAdmin($requiredPermission = null) {
    global $pdo;
    
    // 1. Verify Token (Standard User Auth) using Auth class
    // Auth::check() returns user_id if valid, or exits with 401/error if not.
    $user_id = Auth::check();

    // 2. Fetch User Role & Permissions
    $stmt = $pdo->prepare("SELECT role, permissions FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        http_response_code(401);
        echo json_encode(['error' => 'User not found']);
        exit;
    }

    // 3. Super Admin Bypass
    if ($user['role'] === 'super_admin') {
        return $user_id;
    }

    // 4. Basic Admin/Moderator Check
    if (!in_array($user['role'], ['admin', 'moderator'])) {
        http_response_code(403);
        echo json_encode(['error' => 'Forbidden: user is not admin/moderator']);
        exit;
    }

    // 5. Specific Permission Check (if required)
    if ($requiredPermission) {
        $permissions = json_decode($user['permissions'], true) ?? [];
        if (!in_array($requiredPermission, $permissions)) {
            http_response_code(403);
            echo json_encode(['error' => "Forbidden: missing permission '$requiredPermission'"]);
            exit;
        }
    }

    return $user_id;
}
