<?php
/**
 * =====================================================================
 *  Nadiplayer - CORS bootstrap for Samsung Tizen TV / webOS / file://
 * =====================================================================
 *  Drop this file into the root of your cPanel "nadiplayer" folder, then
 *  at the very top of every entry-point PHP file (auth.php, index.php,
 *  api.php, etc.) add:
 *
 *      <?php require __DIR__ . '/cors.php'; ?>
 *
 *  …BEFORE any other output (no blank lines, no echo, no BOM).
 *
 *  Why every header matters:
 *  ------------------------------------------------------------------
 *  • Tizen WGT loads index.html via file:// → browser sends
 *    `Origin: null` (the LITERAL string, per CORS spec).
 *  • webOS does the same.
 *  • Capacitor Android sends `Origin: https://localhost`.
 *  • Web browsers send `Origin: https://nadiplayer-v125.preview...` etc.
 *
 *  When credentials (cookies / Authorization header) are in play, the
 *  CORS spec FORBIDS `Access-Control-Allow-Origin: *` — you MUST echo
 *  back the exact incoming Origin. So we whitelist and reflect.
 * =====================================================================
 */

// ---- 1. Decide which Origin we trust ------------------------------------
$incomingOrigin = $_SERVER['HTTP_ORIGIN'] ?? '';

$allowedOrigins = [
    'null',                                          // Tizen WGT, webOS WGT (file://)
    'https://localhost',                             // Capacitor Android default
    'http://localhost',                              // Capacitor iOS default / dev
    'capacitor://localhost',                         // Capacitor (older)
    'ionic://localhost',                             // Ionic (if ever)
    'https://4kmovies.vip',                          // Your production web host
    'https://nadi.kr',                               // Your domain
    'https://nadiplayer-edit.preview.emergentagent.com', // Emergent preview
];

// Allow any *.preview.emergentagent.com (preview environments) AND any
// localhost dev port (e.g. http://localhost:3000, http://127.0.0.1:5173)
$originIsAllowed = in_array($incomingOrigin, $allowedOrigins, true)
    || preg_match('#^https?://localhost(:\d+)?$#i', $incomingOrigin)
    || preg_match('#^https?://127\.0\.0\.1(:\d+)?$#i', $incomingOrigin)
    || preg_match('#^https://[a-z0-9-]+\.preview\.emergentagent\.com$#i', $incomingOrigin);

// ---- 2. Emit CORS headers -----------------------------------------------
if ($originIsAllowed && $incomingOrigin !== '') {
    // Reflect the exact origin (required when Allow-Credentials is true).
    header('Access-Control-Allow-Origin: ' . $incomingOrigin);
} else {
    // No Origin header at all → curl/server-to-server: be permissive.
    header('Access-Control-Allow-Origin: *');
}

header('Vary: Origin');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, Accept, Origin, X-API-Key, X-Device-ID, X-App-Version');
header('Access-Control-Expose-Headers: Content-Length, Content-Range, X-Proxy-Error');
header('Access-Control-Max-Age: 86400'); // cache pre-flight for 24h

// ---- 3. Handle pre-flight (OPTIONS) -------------------------------------
// Browsers send an OPTIONS request before any non-simple request. We must
// answer 204 with the CORS headers above and an EMPTY body, then exit.
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// Done — execution continues into the calling script.
