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

if (!function_exists('require_student')) {
  function require_student(): void {
    if (empty($_SESSION['student_id'])) {
      $next = $_SERVER['REQUEST_URI'] ?? '/';
      $login = function_exists('app_url') ? app_url('/student/login.php') : '/elms/student/login.php';
      header('Location: '.$login.'?next='.rawurlencode($next)); exit;
    }
  }
}



 
require_once __DIR__ . '/bootstrap.php';

if (!function_exists('current_url')) {
  function 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;
  }
}

/**
 * Redirect to student/login.php if not logged in.
 * $fallbackPath is where to go after login if we can't safely use the current URL.
 */
function require_student_login(string $fallbackPath = 'student/'): void {
  if (!empty($_SESSION['student_id'])) return;

  $base = app_url();                 // canonical app base
  $next = current_url();
  if (strpos($next, $base) !== 0) {  // keep redirects inside the app
    $next = app_url($fallbackPath);
  }

  $login = app_url('student/login.php');
  // avoid redirecting BACK to login itself
  $pathOnly = parse_url($next, PHP_URL_PATH);
  if ($pathOnly === APP_ROOT.'/student/login.php') {
    $next = app_url($fallbackPath);
  }

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