<?php
// Start session with secure parameters
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// SECURITY: Enforce session timeout (30 minutes)
$timeout = 1800; // 30 minutes

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

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

// SECURITY: Regenerate session ID periodically
if (!isset($_SESSION['SESSION_CREATED'])) {
    $_SESSION['SESSION_CREATED'] = time();
} else if (time() - $_SESSION['SESSION_CREATED'] > 600) {
    // Regenerate every 10 minutes
    session_regenerate_id(true);
    $_SESSION['SESSION_CREATED'] = time();
}

// SECURITY: Verify user agent to prevent session hijacking
if (!isset($_SESSION['USER_AGENT'])) {
    $_SESSION['USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
} else if ($_SESSION['USER_AGENT'] !== $_SERVER['HTTP_USER_AGENT']) {
    SecurityUtils::logSecurityEvent('SESSION_HIJACKING_ATTEMPT', [
        'stored_agent' => $_SESSION['USER_AGENT'],
        'current_agent' => $_SERVER['HTTP_USER_AGENT']
    ]);
    session_unset();
    session_destroy();
    header('Location: ./login.php');
    exit('Session security violation');
}

// SECURITY: Verify IP address (optional, can cause issues with dynamic IPs)
// Uncomment if needed for high-security applications
/*
if (!isset($_SESSION['IP_ADDRESS'])) {
    $_SESSION['IP_ADDRESS'] = $_SERVER['REMOTE_ADDR'];
} else if ($_SESSION['IP_ADDRESS'] !== $_SERVER['REMOTE_ADDR']) {
    SecurityUtils::logSecurityEvent('SESSION_IP_CHANGE', [
        'stored_ip' => $_SESSION['IP_ADDRESS'],
        'current_ip' => $_SERVER['REMOTE_ADDR']
    ]);
    session_unset();
    session_destroy();
    exit('Session security violation: IP mismatch');
}
*/

// Error reporting
error_reporting(E_ALL);
if ($_SERVER['SERVER_NAME'] !== 'localhost') {
    ini_set('display_errors', 0);
} else {
    ini_set('display_errors', 1);
}