<?php
// Allow CORS only for your frontend domains
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

$allowed_origins = [
    "https://upwork.com",
    "https://localhost", // secure local dev
    "http://localhost"   // fallback, if running non-SSL
];

if (in_array($origin, $allowed_origins)) {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
    header("Vary: Origin"); // important when caching
}

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, Accept");
    exit(0);
}

header("Content-Type: application/json");

// Collect cookies
$cookieArray = [];
foreach ($_COOKIE as $key => $value) {
    $cookieArray[] = $key . "=" . $value;
}

// Return response
echo json_encode([
    "cookies" => implode("; ", $cookieArray)
]);
