<?php
/**
 * config/auth.php
 */
if (session_status() === PHP_SESSION_NONE) session_start();

const ROLE_HIERARCHY = [
    'author'     => 1,
    'reviewer'   => 2,
    'editor'     => 3,
    'subadmin'   => 3,
    'admin'      => 4,
    'superadmin' => 5,
];

function is_logged_in(): bool {
    return !empty($_SESSION['admin_user_id']);
}

function current_role(): string {
    return $_SESSION['admin_role'] ?? '';
}

function has_role(string|array $roles): bool {
    $current = current_role();
    if (!$current) return false;
    $currentLevel = ROLE_HIERARCHY[$current] ?? 0;
    foreach ((array)$roles as $r) {
        if ($currentLevel >= (ROLE_HIERARCHY[$r] ?? 99)) return true;
    }
    return false;
}

function require_login(string $redirect = '/admin/login.php'): void {
    if (!is_logged_in()) {
        $_SESSION['intended_url'] = $_SERVER['REQUEST_URI'];
        header("Location: $redirect"); exit;
    }
}

function require_role(string|array $roles, string $redirect = '/admin/login.php'): void {
    require_login($redirect);
    if (!has_role($roles)) {
        http_response_code(403);
        die('<h2 style="font-family:sans-serif;text-align:center;margin-top:100px;color:#dc2626">403 — Access Denied</h2>');
    }
}

/**
 * require_page_access() - Har protected page ke top pe lagao
 * 
 * - superadmin → always allowed
 * - admin      → always allowed  
 * - dashboard  → always allowed (koi bhi logged-in user)
 * - subadmin   → sirf wahi pages jo DB mein hain uske liye
 */
function require_page_access(?string $file = null): void {
    require_login();

    $role = current_role();

    // superadmin aur admin ko sab allow
    if (in_array($role, ['superadmin', 'admin'])) return;

    $file = $file ?? basename($_SERVER['PHP_SELF']);

    // dashboard hamesha allow
    if ($file === 'admin_dashboard.php') return;

    // DB se permissions load karo (session cache mein rakho)
    if (!isset($_SESSION['admin_page_perms'])) {
        global $pdo;
        $uid = (int)($_SESSION['admin_user_id'] ?? 0);
        if ($uid && isset($pdo)) {
            try {
                $st = $pdo->prepare(
                    "SELECT permission_key FROM admin_user_permissions WHERE user_id = ?"
                );
                $st->execute([$uid]);
                $_SESSION['admin_page_perms'] = $st->fetchAll(PDO::FETCH_COLUMN);
            } catch (\Exception $e) {
                $_SESSION['admin_page_perms'] = [];
            }
        } else {
            $_SESSION['admin_page_perms'] = [];
        }
    }

    if (!in_array($file, $_SESSION['admin_page_perms'], true)) {
        http_response_code(403);
        die('<div style="font-family:sans-serif;text-align:center;margin-top:100px;">
            <h2 style="color:#dc2626">403 — Access Denied</h2>
            <p style="color:#6b7280">You do not have permission to view this page.</p>
            <a href="admin_dashboard.php" style="color:#3b82f6;text-decoration:none;">&#8592; Back to Dashboard</a>
        </div>');
    }
}

// Permissions cache clear karo (permissions update ke baad call karo)
function clear_page_perms_cache(): void {
    unset($_SESSION['admin_page_perms']);
}