<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in
if (!isset($_SESSION['user'])) {
    header('Location: login.php');
    exit;
}

// Optional: Check if user session is still valid
$user = $_SESSION['user'];

// You might want to add more validation here:
// 1. Check if user still exists in database
// 2. Check if user is active
// 3. Check session expiration

// Example: Simple session timeout (30 minutes)
$session_timeout = 30 * 60; // 30 minutes in seconds
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $session_timeout)) {
    // Session expired
    session_unset();
    session_destroy();
    header('Location: login.php?expired=1');
    exit;
}

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

// Optional: Regenerate session ID periodically for security
$regenerate_time = 15 * 60; // 15 minutes
if (!isset($_SESSION['created'])) {
    $_SESSION['created'] = time();
} elseif (time() - $_SESSION['created'] > $regenerate_time) {
    // Regenerate session ID
    session_regenerate_id(true);
    $_SESSION['created'] = time();
}
?>