<?php

declare(strict_types=1);

namespace MailerPress\Middleware;

\defined('ABSPATH') || exit;

use MailerPress\Core\Attributes\Action;

class CorsMiddleware
{
    /**
     * Initialize CORS handling
     */
    #[Action('rest_api_init')]
    public function init(): void
    {
        // Remove default WordPress CORS headers
        remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');

        // Add custom CORS headers
        add_filter('rest_pre_serve_request', [$this, 'customCorsHeaders'], 15);
    }

    /**
     * Initialize early CORS handling for preflight requests
     * This must run before WordPress processes the request
     * Using parse_request which fires very early for all requests including REST API
     */
    #[Action('parse_request', priority: 1)]
    public function initEarly(): void
    {
        // Handle OPTIONS preflight requests early
        $this->handlePreflight();
    }

    /**
     * Add custom CORS headers for embed endpoints
     *
     * @param mixed $value
     * @return mixed
     */
    public function customCorsHeaders($value)
    {
        $origin = $_SERVER['HTTP_ORIGIN'] ?? '';

        // Only apply CORS to embed endpoints
        $requestUri = $_SERVER['REQUEST_URI'] ?? '';
        if (strpos($requestUri, '/wp-json/mailerpress/v1/embed/') === false) {
            // For non-embed endpoints, use default WordPress CORS
            return rest_send_cors_headers($value);
        }

        // Always set CORS headers for embed endpoints
        // Note: We can't use '*' with Access-Control-Allow-Credentials, so we use the specific origin
        if ($origin) {
            header('Access-Control-Allow-Origin: ' . $origin);
            header('Access-Control-Allow-Credentials: true');
        } else {
            // If no origin header, allow all origins (for same-origin requests or when origin is missing)
            // But we can't use credentials with wildcard
            header('Access-Control-Allow-Origin: *');
        }

        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, X-MailerPress-API-Key, X-WP-Nonce');
        header('Access-Control-Max-Age: 86400'); // 24 hours

        return $value;
    }

    /**
     * Handle OPTIONS preflight requests
     */
    public function handlePreflight(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'OPTIONS') {
            return;
        }

        $requestUri = $_SERVER['REQUEST_URI'] ?? '';
        if (strpos($requestUri, '/wp-json/mailerpress/v1/embed/') === false) {
            return;
        }

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

        // Always set CORS headers for preflight requests
        // Note: We can't use '*' with Access-Control-Allow-Credentials, so we use the specific origin
        if ($origin) {
            header('Access-Control-Allow-Origin: ' . $origin);
            header('Access-Control-Allow-Credentials: true');
        } else {
            // If no origin header, allow all origins (for same-origin requests)
            // But we can't use credentials with wildcard
            header('Access-Control-Allow-Origin: *');
        }

        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, X-MailerPress-API-Key, X-WP-Nonce');
        header('Access-Control-Max-Age: 86400');

        // Send 200 OK and exit to prevent WordPress from processing the request
        status_header(200);
        exit;
    }
}
