<?php
// ============================================================
//  auth_check.php — Session Guard
//  Place in: /admin/includes/auth_check.php
//  Add at the TOP of EVERY protected admin page:
//    require_once 'includes/auth_check.php';
// ============================================================
require_once __DIR__ . '/db.php';

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

// ── Check if logged in ────────────────────────────────────────
if (empty($_SESSION[ADMIN_SESSION_KEY]) || empty($_SESSION['admin_id'])) {
    header('Location: ' . rtrim(dirname($_SERVER['PHP_SELF']), '/admin') . '/admin/login.php');
    exit;
}

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

// ── Expose current admin data as a global array ───────────────
$current_admin = [
    'id'       => $_SESSION['admin_id'],
    'name'     => $_SESSION['admin_name'],
    'username' => $_SESSION['admin_username'],
    'role'     => $_SESSION['admin_role'],
    'avatar'   => $_SESSION['admin_avatar'],
];

// ── Helper: require super_admin role ─────────────────────────
function require_super_admin(): void {
    global $current_admin;
    if ($current_admin['role'] !== 'super_admin') {
        http_response_code(403);
        include __DIR__ . '/../403.php';
        exit;
    }
}
