<?php
/**
 * Purchase Manager Session Validator
 * Ensures session is valid and not expired
 */

header('Content-Type: application/json');

// Start session with proper configuration
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if purchase manager is logged in
if (!isset($_SESSION['purchase_manager_id']) || empty($_SESSION['purchase_manager_id'])) {
    http_response_code(401);
    echo json_encode([
        'valid' => false,
        'message' => 'No active session'
    ]);
    exit;
}

// Optional: Check for session timeout (30 minutes)
$timeout = 1800; // 30 minutes
$_SESSION['last_activity'] = $_SESSION['last_activity'] ?? time();

if (time() - $_SESSION['last_activity'] > $timeout) {
    // Session expired
    session_destroy();
    http_response_code(401);
    echo json_encode([
        'valid' => false,
        'message' => 'Session expired. Please login again.'
    ]);
    exit;
}

// Update last activity
$_SESSION['last_activity'] = time();

// Session is valid
echo json_encode([
    'valid' => true,
    'purchase_manager_id' => $_SESSION['purchase_manager_id'],
    'purchase_manager_name' => $_SESSION['purchase_manager_name'] ?? 'Purchase Manager',
    'purchase_manager_email' => $_SESSION['purchase_manager_email'] ?? '',
    'message' => 'Session is valid'
]);
?>
