<?php
declare(strict_types=1);

namespace Middleware;

use Config\Env;

final class CorsMiddleware
{
    public static function handle(): void
    {
        $requestOrigin = $_SERVER['HTTP_ORIGIN'] ?? '';
        $configured = Env::get('CORS_ALLOWED_ORIGINS', Env::get('FRONTEND_URL', '*'));
        $allowed = array_filter(array_map('trim', explode(',', (string)$configured)));
        $originToAllow = '*';

        if (in_array('*', $allowed, true)) {
            $originToAllow = $requestOrigin ?: '*';
        } elseif ($requestOrigin && in_array($requestOrigin, $allowed, true)) {
            $originToAllow = $requestOrigin;
        } elseif (!$requestOrigin && $allowed) {
            $originToAllow = $allowed[0];
        }

        header("Access-Control-Allow-Origin: {$originToAllow}");
        header('Vary: Origin');
        header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-CSRF-Token, X-Guest-Session, X-Requested-With, X-Auth-Token');
        header('Access-Control-Max-Age: 86400');
        if ($originToAllow !== '*') {
            header('Access-Control-Allow-Credentials: true');
        }
        if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') exit;
    }
}