<?php
/**
 * Admin Authentication Module
 * Handles access control specifically for the admin panel.
 */

// Ensure this file is not accessed directly
if (!defined('DS')) {
    exit('Direct access not permitted.');
}

/**
 * Checks if the currently logged-in user is an administrator.
 * Validates against the database in real-time to ensure privileges haven't been revoked.
 *
 * @param PDO $pdo The PDO database connection instance.
 * @return bool True if the user is an active admin, false otherwise.
 */
function is_admin($pdo) {
    if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
        return false;
    }

    try {
        $stmt = $pdo->prepare("SELECT role, status FROM users WHERE id = :id LIMIT 1");
        $stmt->bindParam(':id', $_SESSION['user_id'], PDO::PARAM_INT);
        $stmt->execute();
        
        $user = $stmt->fetch();

        // Strictly check for 'admin' role and 'active' status
        if ($user && $user['role'] === 'admin' && $user['status'] === 'active') {
            return true;
        }

        return false;
    } catch (PDOException $e) {
        // Securely log the error
        error_log("Admin Check Error: " . $e->getMessage());
        return false;
    }
}

/**
 * Enforces admin-only access for a page.
 * If the user is not an active admin, they are securely redirected and logged.
 *
 * @param PDO $pdo The PDO database connection instance.
 */
function require_admin($pdo) {
    // If not logged in at all, send to admin login
    if (!isset($_SESSION['user_id'])) {
        set_flash_message('error', 'Please log in to access the admin panel.');
        redirect(SITE_URL . '/admin/login.php');
    }

    // If logged in but not an admin, block access
    if (!is_admin($pdo)) {
        // Log the unauthorized access attempt for security auditing
        error_log("SECURITY ALERT: Unauthorized admin access attempt by User ID: " . $_SESSION['user_id'] . " from IP: " . $_SERVER['REMOTE_ADDR']);
        
        set_flash_message('error', 'Access denied. Administrator privileges are strictly required.');
        redirect(SITE_URL . '/index.php');
    }
}

/**
 * Redirects an already logged-in admin away from the admin login page
 * to the dashboard.
 *
 * @param PDO $pdo The PDO database connection instance.
 */
function redirect_if_admin($pdo) {
    if (is_admin($pdo)) {
        redirect(SITE_URL . '/admin/dashboard.php');
    }
}