<?php
/**
 * session.php — PHP 8.4 compatible (trainer-side session guard)
 *
 * Changes from original:
 *  - Replaced interpolated query with a prepared statement (SQLi fix).
 *  - Added exit() after header() redirect.
 *  - $login_session derived safely from fetch result with null-coalescing.
 */

require('configuration.php');
session_start(['gc_maxlifetime' => 14400, 'cookie_httponly' => true]);

$user_check = $_SESSION['login_user'] ?? null;

$login_session = null;

if ($user_check !== null) {
    $stmt = mysqli_prepare(
        $connection,
        "SELECT trainer_username AS username FROM trainer WHERE trainer_username = ? LIMIT 1"
    );

    if ($stmt) {
        mysqli_stmt_bind_param($stmt, 's', $user_check);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $row    = mysqli_fetch_assoc($result);
        mysqli_stmt_close($stmt);

        $login_session = $row['username'] ?? null;
    }
}

if ($login_session === null) {
    header('Location: index.php');
    exit();
}
