<?php
declare(strict_types=1);

/**
 * CENTRALIZED CORS HANDLER
 * For cookie-based authentication (credentials: include)
 *
 * RULES:
 * - NEVER use Access-Control-Allow-Origin: *
 * - MUST echo back the requesting Origin when using credentials
 * - Preflight (OPTIONS) must exit before sessions/output
 */

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

/**
 * 🔒 EDIT THIS LIST ONLY
 */
$allowedOrigins = [
    'http://localhost:5174',
    'http://127.0.0.1:5174',
    'http://192.168.88.59:5174', // your LAN dev
    'https://skizagroundsuite.com', // ✅ PRODUCTION
    'https://finsapdev.qhtestingserver.com',
];

if ($origin && in_array($origin, $allowedOrigins, true)) {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
    header("Vary: Origin");
} else {
    if ($origin) {
        http_response_code(403);
        exit;
    }
}

header("Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS");

header("Access-Control-Allow-Headers: Content-Type, Accept, Authorization, X-Requested-With");

header("Access-Control-Max-Age: 86400");

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    http_response_code(204);
    exit;
}
