<?php
declare(strict_types=1);

/**
 * _cors.php (cookie-based CORS: credentials: "include")
 * Fixes:
 * - Preflight wildcard origin not allowed
 * - Origin mismatch (no trailing slashes)
 * - Duplicate ACAO headers (removes any previously set one)
 *
 * NOTE: You MUST NOT use "*" with credentials. Use explicit allowlist.
 */

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

// ✅ No trailing slash. Browser Origin never includes trailing "/"
$allowed = [
  'http://localhost:5174',
  'http://127.0.0.1:5174',
  'http://localhost:3000',
  'http://127.0.0.1:3000',
  'https://finsapdev.qhtestingserver.com',
];

// Always remove any existing header to avoid duplicates.
// (Helps if some PHP include set it earlier.)
header_remove('Access-Control-Allow-Origin');
header_remove('Access-Control-Allow-Credentials');
header_remove('Access-Control-Allow-Methods');
header_remove('Access-Control-Allow-Headers');
header_remove('Access-Control-Max-Age');

$originAllowed = ($origin !== '' && in_array($origin, $allowed, true));

if ($originAllowed) {
  header("Access-Control-Allow-Origin: $origin");
  header('Vary: Origin');
  header('Access-Control-Allow-Credentials: true');
  header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
  header('Access-Control-Allow-Headers: Content-Type, Accept, Authorization, X-Requested-With, X-Idempotency-Key');
  header('Access-Control-Max-Age: 86400');
}

// ✅ Preflight must return immediately (even before session_start)
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
  // If not allowed, still respond (browser needs a response); 403 is fine.
  http_response_code($originAllowed ? 204 : 403);
  exit;
}

// If a disallowed origin calls a non-OPTIONS request, fail fast with JSON.
// This makes it obvious in logs/devtools what happened.
if ($origin !== '' && !$originAllowed) {
  header('Content-Type: application/json; charset=utf-8');
  http_response_code(403);
  echo json_encode([
    'ok' => false,
    'error' => 'CORS origin not allowed',
    'origin' => $origin,
  ], JSON_UNESCAPED_SLASHES);
  exit;
}
