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

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

// Check if user is logged in
if (!isLoggedIn()) {
    // For AJAX requests, return JSON error
    if (isAjax()) {
        Response::unauthorized('অনুগ্রহ করে লগইন করুন');
    }
    
    // Store intended URL for redirect after login
    $_SESSION['intended_url'] = $_SERVER['REQUEST_URI'];
    
    // Redirect to login page
    redirect(url('public/pages/login.php'));
}

// Check if user is blocked
$userId = getUserId();
$user = Database::fetchOne("SELECT is_blocked FROM users WHERE id = ?", [$userId]);

if (!$user || $user['is_blocked']) {
    // Clear session
    session_destroy();
    
    if (isAjax()) {
        Response::forbidden('আপনার অ্যাকাউন্ট ব্লক করা হয়েছে');
    }
    
    setFlash('error', 'আপনার অ্যাকাউন্ট ব্লক করা হয়েছে। সাপোর্টে যোগাযোগ করুন।');
    redirect(url('public/pages/login.php'));
}

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