<?php
session_start();
require_once __DIR__ . '/../config/config.php';

// Check for session validity and remote logout
if (isAuthenticated() && isset($_SESSION['user_id'])) {
    if (!isSessionValid($_SESSION['user_id'])) {
        // Session has been invalidated (remote logout)
        session_destroy();
        if (!isset($isAjax)) {
            redirect(APP_URL . '/login.php?error=session_invalidated');
        }
    }
    
    // Update last activity and online status
    $db = getDB();
    $stmt = $db->prepare("UPDATE users SET last_activity = NOW() WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    
    // Update or insert online status
    $stmt = $db->prepare("
        INSERT INTO online_status (user_id, is_online, last_seen) 
        VALUES (?, 1, NOW()) 
        ON DUPLICATE KEY UPDATE is_online = 1, last_seen = NOW()
    ");
    $stmt->execute([$_SESSION['user_id']]);}

// Check if request is AJAX
$isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
          strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';

// Set headers for non-HTML responses
if ($isAjax) {
    header('Content-Type: application/json');
}
?>
