<?php
/**
 * session_config_school.php
 * Final merged & hardened session configuration
 * Compatible with:
 *  - emis_code based authentication
 *  - registrations table
 *  - remember_school cookie
 */

/* =========================
   PHP SESSION SECURITY
========================= */
ini_set('session.use_only_cookies', 1);
ini_set('session.use_strict_mode', 1);
ini_set('session.use_trans_sid', 0);
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_samesite', 'Lax');

/* =========================
   SESSION COOKIE SETTINGS
========================= */
session_set_cookie_params([
    'lifetime' => 0, // session cookie only
    'path'     => '/',
    'domain'   => '',
    'secure'   => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'),
    'httponly' => true,
    'samesite' => 'Lax'
]);

/* =========================
   SESSION LIMITS
========================= */
$session_timeout      = 1800; // 30 minutes idle
$max_session_lifetime = 7200; // 2 hours absolute

session_name('SCH_SESS_' . substr(md5(__FILE__), 0, 8));
session_start();

/* =========================
   SESSION META DATA
========================= */
if (!isset($_SESSION['CREATED'])) {
    $_SESSION['CREATED'] = time();
}

if (!isset($_SESSION['LAST_ACTIVITY'])) {
    $_SESSION['LAST_ACTIVITY'] = time();
}

if (!isset($_SESSION['USER_AGENT'])) {
    $_SESSION['USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'] ?? '';
}

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/* =========================
   TIMEOUT ENFORCEMENT
========================= */
// Idle timeout
if (isset($_SESSION['LAST_ACTIVITY']) &&
    (time() - $_SESSION['LAST_ACTIVITY']) > $session_timeout) {
    destroySchoolSession();
}

// Absolute lifetime
if (isset($_SESSION['CREATED']) &&
    (time() - $_SESSION['CREATED']) > $max_session_lifetime) {
    destroySchoolSession();
}

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

/* =========================
   SESSION VALIDATION
========================= */
function validateSchoolSession()
{
    global $session_timeout;

    if (empty($_SESSION['emis_code'])) {
        return false;
    }

    if (!isset($_SESSION['LAST_ACTIVITY']) ||
        (time() - $_SESSION['LAST_ACTIVITY']) > $session_timeout) {
        return false;
    }

    if (!isset($_SESSION['USER_AGENT']) ||
        $_SESSION['USER_AGENT'] !== ($_SERVER['HTTP_USER_AGENT'] ?? '')) {
        return false;
    }

    return true;
}

/* =========================
   SECURE SESSION REGENERATION
========================= */
function secureSchoolSessionRegeneration()
{
    session_regenerate_id(true);

    $_SESSION['CREATED']       = time();
    $_SESSION['LAST_ACTIVITY'] = time();
    $_SESSION['USER_AGENT']    = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $_SESSION['csrf_token']    = bin2hex(random_bytes(32));
}

/* =========================
   CSRF HELPERS
========================= */
function validateCsrfToken($token)
{
    return isset($_SESSION['csrf_token']) &&
           hash_equals($_SESSION['csrf_token'], $token);
}

function regenerateCsrfToken()
{
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    return $_SESSION['csrf_token'];
}

/* =========================
   FULL SESSION DESTROY
========================= */
function destroySchoolSession()
{
    // Remove remember-me cookie
    if (isset($_COOKIE['remember_school'])) {
        setcookie(
            'remember_school',
            '',
            time() - 3600,
            '/',
            '',
            (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'),
            true
        );
    }

    $_SESSION = [];

    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(
            session_name(),
            '',
            time() - 42000,
            $params['path'],
            $params['domain'],
            $params['secure'],
            $params['httponly']
        );
    }

    session_destroy();
}
?>