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

/**
 * Check if the current visitor is logged in as admin.
 */
function isAdminLoggedIn(): bool {
    return isset($_SESSION['admin_id']) && $_SESSION['admin_id'] > 0;
}

/**
 * Redirect to login page if not an admin.
 */
function requireAdmin(): void {
    if (!isAdminLoggedIn()) {
        header('Location: ' . BASE_URL . 'login.php');
        exit;
    }
}

/**
 * Get the logged-in admin’s basic data.
 */
function getAdminUser(): ?array {
    if (isAdminLoggedIn()) {
        $db = getDB();
        $stmt = $db->prepare("SELECT id, name, email, is_admin FROM users WHERE id = ?");
        $stmt->bind_param('i', $_SESSION['admin_id']);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }
    return null;
}