<?php
// config/auth.php  –  include at the top of every protected page
// ---------------------------------------------------------------
//   require_login()              – any logged-in user
//   require_role('admin')        – single role
//   require_role(['admin','editor']) – any of these roles
// ---------------------------------------------------------------

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Role hierarchy  (higher index = more power)
const ROLE_HIERARCHY = [
    'author'     => 1,
    'reviewer'   => 2,
    'editor'     => 3,
    'admin'      => 4,
    'superadmin' => 5,
];

// ── helpers ──────────────────────────────────────────────────

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;
    $allowed = (array) $roles;
    // exact match OR higher in hierarchy
    $currentLevel = ROLE_HIERARCHY[$current] ?? 0;
    foreach ($allowed as $r) {
        $needed = ROLE_HIERARCHY[$r] ?? 99;
        if ($currentLevel >= $needed) return true;
    }
    return false;
}

// ── guards ───────────────────────────────────────────────────

function require_login(string $redirect = '/webadmin/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 = '/webadmin/login.php'): void {
    require_login($redirect);
    if (!has_role($roles)) {
        http_response_code(403);
        include __DIR__ . '/403.php';   // create a simple 403 page, or just die:
        // die('<h2>403 — Access Denied</h2>');
        exit;
    }
}