<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/config/functions.php';
ensure_session();

// Best-effort audit before destroying the session
try {
  $uid = (int)($_SESSION['user']['id'] ?? 0);
  if ($uid > 0) {
    audit_log('auth.logout', 'user', $uid, [
      'ip' => client_ip(),
      'ua' => client_ua(),
    ]);
  }
} catch (Throwable $e) {
  // ignore audit failures
}

// Clear all session data
$_SESSION = [];

// Invalidate the session cookie
if (ini_get('session.use_cookies')) {
  $params = session_get_cookie_params();
  setcookie(
    session_name(),
    '',
    time() - 42000,
    $params['path']     ?? '/',
    $params['domain']   ?? '',
    $params['secure']   ?? false,
    $params['httponly'] ?? true
  );
}

// Destroy the session
session_destroy();

// Send the user to the login page
redirect(url_public('login.php'));
