<?php

/**
 * DEMOBANK SESSION HANDLER
 * - Start sessions safely
 * - Set secure session options
 * - Optional session timeout
 */

if (session_status() === PHP_SESSION_NONE) {

    // Secure session cookie parameters
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params([
        'lifetime' => $cookieParams['lifetime'], 
        'path' => $cookieParams['path'], 
        'domain' => $cookieParams['domain'], 
        'secure' => isset($_SERVER['HTTPS']), // only send cookie over HTTPS
        'httponly' => true,                  // JS cannot access cookie
        'samesite' => 'Strict',              // prevent CSRF
    ]);

    session_start();
}

/**
 * SESSION TIMEOUT (optional)
 * - Auto logout after inactivity (e.g., 30 min)
 */
$timeout = 1800; // 30 minutes in seconds

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $timeout)) {
    // Last request was more than timeout
    session_unset();
    session_destroy();
    header("Location: /auth/login.php?timeout=1");
    exit;
}

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

/**
 * GENERIC SESSION FUNCTIONS
 */

// Set session data
function setSession($key, $value) {
    $_SESSION[$key] = $value;
}

// Get session data
function getSession($key) {
    return $_SESSION[$key] ?? null;
}

// Remove session key
function unsetSession($key) {
    if (isset($_SESSION[$key])) {
        unset($_SESSION[$key]);
    }
}

// Destroy session completely
function destroySession() {
    session_unset();
    session_destroy();
}