<?php
// /elms/includes/student_auth.php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/elms_settings.php';


$mysqli = $mysqli ?? ($conn ?? null);

if ($mysqli instanceof mysqli) {
    $timeoutMinutes = (int)elms_setting($mysqli, 'session_timeout_minutes', '60');
    $timeoutSeconds = max(5, $timeoutMinutes) * 60;

    $lastActivity = (int)($_SESSION['last_activity_at'] ?? time());

    if (!empty($_SESSION['student_id']) && (time() - $lastActivity) > $timeoutSeconds) {
        session_unset();
        session_destroy();
        header('Location: /elms/student/login.php?timeout=1');
        exit;
    }

    $_SESSION['last_activity_at'] = time();
}

$helpers = __DIR__ . '/helpers.php';
if (is_file($helpers)) {
    require_once $helpers;
}

$bootstrap = __DIR__ . '/bootstrap.php';
if (is_file($bootstrap)) {
    require_once $bootstrap;
}

if (!function_exists('student_current_url')) {
    function student_current_url(): string
    {
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $uri    = $_SERVER['REQUEST_URI'] ?? '/';

        return $scheme . '://' . $host . $uri;
    }
}

if (!function_exists('student_app_url')) {
    function student_app_url(string $path = ''): string
    {
        $path = ltrim($path, '/');
        return '/elms/' . $path;
    }
}

if (!function_exists('require_student_login')) {
    function require_student_login(string $fallbackPath = 'student/dashboard.php'): void
    {
        if (!empty($_SESSION['student_id'])) {
            return;
        }

        $next = student_current_url();
        $login = student_app_url('student/login.php');

        $pathOnly = parse_url($next, PHP_URL_PATH);

        if ($pathOnly === '/elms/student/login.php') {
            $next = student_app_url($fallbackPath);
        }

        header('Location: ' . $login . '?next=' . rawurlencode($next));
        exit;
    }
}


if ($mysqli instanceof mysqli) {
    if (elms_setting_on($mysqli, 'maintenance_mode', 'off')) {
        $role = strtolower((string)($_SESSION['role'] ?? ''));

        if (!in_array($role, ['super_admin', 'admin'], true)) {
            http_response_code(503);
            exit('ELMS is currently under maintenance. Please try again later.');
        }
    }
}
require_student_login();

$studentId = (int)($_SESSION['student_id'] ?? 0);
$studentName = $_SESSION['student_name'] ?? $_SESSION['full_name'] ?? 'Student';
$studentEmail = $_SESSION['student_email'] ?? $_SESSION['academic_email'] ?? '';
$studentRegNo = $_SESSION['center_reg_no'] ?? $_SESSION['student_reg_no'] ?? '';

$GLOBALS['STUDENT_ID'] = $studentId;
$GLOBALS['STUDENT_NAME'] = (string)$studentName;
$GLOBALS['STUDENT_EMAIL'] = (string)$studentEmail;
$GLOBALS['STUDENT_REG_NO'] = (string)$studentRegNo;