<?php
// auth_check.php — include at the top of every protected page

// 10-hour session lifetime
ini_set('session.gc_maxlifetime', 36000);
session_set_cookie_params(36000);

session_name('mhp_purchasing_session');
session_start();

$timeout = 36000; // 10 hours

if (!isset($_SESSION['user_id'])) {
    // Return JSON for AJAX calls, redirect for normal page loads
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }
    header('Location: login.php');
    exit;
}

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout) {
    session_unset();
    session_destroy();
    header('Location: login.php?expired=1');
    exit;
}

$_SESSION['LAST_ACTIVITY'] = time();
