<?php
/**
 * Authentication Middleware
 * Checks if admin user is logged in, redirects to login page if not
 * Include this file at the top of any protected admin page
 */

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * Check if user is authenticated
 */
function isAdminLoggedIn() {
    return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
}

/**
 * Require authentication - redirect to login if not logged in
 */
function requireAuth() {
    if (!isAdminLoggedIn()) {
        // Store the requested URL to redirect back after login
        $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
        
        // Redirect to login page
        header('Location: login.php');
        exit;
    }
}

/**
 * Get current admin user data
 */
function getCurrentAdmin() {
    if (!isAdminLoggedIn()) {
        return null;
    }
    
    return [
        'id' => $_SESSION['admin_id'] ?? null,
        'username' => $_SESSION['admin_username'] ?? null,
        'email' => $_SESSION['admin_email'] ?? null,
        'full_name' => $_SESSION['admin_full_name'] ?? null,
        'role' => $_SESSION['admin_role'] ?? null,
        'login_time' => $_SESSION['login_time'] ?? null
    ];
}

/**
 * Check if user has specific role
 */
function hasRole($role) {
    if (!isAdminLoggedIn()) {
        return false;
    }
    
    $userRole = $_SESSION['admin_role'] ?? null;
    
    // Super admin has access to everything
    if ($userRole === 'super_admin') {
        return true;
    }
    
    return $userRole === $role;
}

/**
 * Require specific role - redirect to 403 if user doesn't have permission
 */
function requireRole($role) {
    requireAuth(); // First check if logged in
    
    if (!hasRole($role)) {
        http_response_code(403);
        include '403.php'; // You can create a 403 forbidden page
        exit;
    }
}

// Auto-protect: If this file is included and AUTO_PROTECT is defined, automatically require auth
if (defined('AUTO_PROTECT') && AUTO_PROTECT === true) {
    requireAuth();
}
?>
