<?php
// /elms/student/logout.php — safe logout (no includes)
declare(strict_types=1);

// Start the SAME session your app uses (global cookie path!)
if (session_status() === PHP_SESSION_NONE) {
  session_set_cookie_params([
    'path'     => '/',                                        // critical (works across /elms/*)
    'secure'   => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
    'httponly' => true,
    'samesite' => 'Lax',
  ]);
  session_start();
}

/* 1) Wipe all session data */
$_SESSION = [];
@session_unset();

/* 2) Kill the session cookie */
if (ini_get('session.use_cookies')) {
  $host   = $_SERVER['HTTP_HOST'] ?? '';
  $secure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';

  // On localhost, omit domain; on real host, set it
  $cookieOpts = [
    'expires'  => time() - 42000,
    'path'     => '/',
    'secure'   => $secure,
    'httponly' => true,
    'samesite' => 'Lax',
  ];
  if ($host !== 'localhost' && $host !== '127.0.0.1') {
    $cookieOpts['domain'] = $host;
  }
  setcookie(session_name(), '', $cookieOpts);
}

/* 3) Clear any custom auth cookies if you use them */
foreach (['remember_me','remember','rm_token','student_auth'] as $c) {
  if (isset($_COOKIE[$c])) {
    setcookie($c, '', [
      'expires'  => time() - 42000,
      'path'     => '/',
      'secure'   => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
      'httponly' => true,
      'samesite' => 'Lax',
    ]);
  }
}

/* 4) Destroy server session */
@session_destroy();

/* 5) Avoid back-button caching, then redirect to the *correct* login */
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

$base  = rtrim(str_replace('\\','/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/'); // -> /elms/student
header('Location: '.$base.'/login.php', true, 303);
exit;
