<?php
/**
 * ============================================================
 * ADMIN AUTHENTICATION MIDDLEWARE
 * ============================================================
 * Include this file at the top of admin pages that require login
 */

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

// Check if admin is logged in
if (!isAdminLoggedIn()) {
    // For AJAX requests, return JSON error
    if (isAjax()) {
        Response::unauthorized('অনুগ্রহ করে অ্যাডমিন প্যানেলে লগইন করুন');
    }
    
    // Store intended URL for redirect after login
    $_SESSION['admin_intended_url'] = $_SERVER['REQUEST_URI'];
    
    // Redirect to admin login page
    redirect(adminUrl('auth/login.php'));
}

// Check if admin is still active
$adminId = getAdminId();
$admin = Database::fetchOne("SELECT is_active FROM admins WHERE id = ?", [$adminId]);

if (!$admin || !$admin['is_active']) {
    // Clear session
    session_destroy();
    
    if (isAjax()) {
        Response::forbidden('আপনার অ্যাডমিন অ্যাকাউন্ট নিষ্ক্রিয় করা হয়েছে');
    }
    
    redirect(adminUrl('auth/login.php'));
}

// Check session timeout (30 minutes for admin)
$adminSessionLifetime = 1800; // 30 minutes
if (isset($_SESSION['admin_last_activity']) && 
    (time() - $_SESSION['admin_last_activity'] > $adminSessionLifetime)) {
    session_destroy();
    
    if (isAjax()) {
        Response::unauthorized('সেশন মেয়াদ শেষ। পুনরায় লগইন করুন।');
    }
    
    redirect(adminUrl('auth/login.php?expired=1'));
}

// Refresh session timeout
$_SESSION['admin_last_activity'] = time();
