<?php
// ============================================================
//  includes/auth_check.php — Admin Session Guard
//  Add at the TOP of every admin-protected page:
//    require_once __DIR__ . '/includes/auth_check.php';
// ============================================================

// Load DB (safe to call multiple times — uses require_once internally)
$_root = dirname(__DIR__);
require_once $_root . '/includes/db.php';

// Start session safely
if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.cookie_httponly', 1);
    ini_set('session.use_strict_mode', 1);
    session_start();
}

// ── Check login ───────────────────────────────────────────────
if (empty($_SESSION[ADMIN_SESSION_KEY]) || empty($_SESSION['admin_id'])) {
    // Build correct redirect path regardless of where this is called from
    $login_url = APP_URL . '/admin/login.php';
    header('Location: ' . $login_url);
    exit;
}

// ── Session timeout ───────────────────────────────────────────
if (!empty($_SESSION['login_time'])) {
    if (time() - $_SESSION['login_time'] > SESSION_LIFETIME) {
        session_unset();
        session_destroy();
        header('Location: ' . APP_URL . '/admin/login.php?expired=1');
        exit;
    }
    // Refresh activity timestamp
    $_SESSION['login_time'] = time();
}

// ── Expose $current_admin globally ───────────────────────────
$current_admin = [
    'id'       => (int)$_SESSION['admin_id'],
    'name'     => $_SESSION['admin_name']     ?? '',
    'username' => $_SESSION['admin_username'] ?? '',
    'role'     => $_SESSION['admin_role']     ?? 'admin',
    'avatar'   => $_SESSION['admin_avatar']   ?? 'logo.png',
];

// ── Helper: Super Admin only pages ───────────────────────────
function require_super_admin(): void {
    global $current_admin;
    if (($current_admin['role'] ?? '') !== 'super_admin') {
        http_response_code(403);
        $f = dirname(__DIR__) . '/admin/403.php';
        if (file_exists($f)) { include $f; } else {
            echo '<!DOCTYPE html><html><head><title>403 Forbidden</title>
            <style>body{font-family:sans-serif;background:#0B2545;color:#fff;display:grid;place-items:center;height:100vh;margin:0}
            .b{text-align:center}.h{font-size:80px;color:#FF6A00;font-weight:800;line-height:1}.t{font-size:22px;margin:10px 0}
            a{color:#FF6A00;text-decoration:none;margin-top:20px;display:inline-block}</style></head>
            <body><div class="b"><div class="h">403</div><div class="t">Super Admin Access Only</div>
            <a href="../admin/dashboard.php">← Back to Dashboard</a></div></body></html>';
        }
        exit;
    }
}