<?php
/**
 * auto-cors-middleware.php
 * Dynamically handles CORS based on the detected environment.
 */

$env = getenv('APP_ENV') ?: 'production';

// Define allowed origins based on environment
$allowed_origins = [
    'development' => [
        'http://localhost:5173',
        'http://localhost:8080',
        'http://127.0.0.1:5173',
        'capacitor://localhost',
        'http://localhost'
    ],
    'production' => [
        // Add production domains here if needed, or use wildcard for generic API
        // "*" is often used for mobile apps where origin is null or capacitor://
        '*' 
    ]
];

$origins = isset($allowed_origins[$env]) ? $allowed_origins[$env] : ['*'];
$http_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : null;

// Handle CORS Headers
if (!headers_sent()) {
    if ($http_origin) {
        if (in_array('*', $origins) || in_array($http_origin, $origins)) {
            header("Access-Control-Allow-Origin: $http_origin");
            header("Access-Control-Allow-Credentials: true");
        }
    } elseif (in_array('*', $origins)) {
        header("Access-Control-Allow-Origin: *");
    }
}


// Common Headers
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, X-Client-Info, apikey");

// Handle Preflight
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}
