<?php
/**
 * Plugin Name: Mission Control CORS
 * Description: Allow the Mission Control dashboard at sol1.tail2d1d46.ts.net to call the WC REST API in the browser. Drop this file in wp-content/mu-plugins/ and it loads automatically — no activation step needed.
 * Author: Nitrous
 * Version: 1.0.0
 */

if (!defined('ABSPATH')) exit;

/**
 * Origins allowed to call /wp-json/* with credentials.
 * Add more entries here if Mission Control gets a new public URL.
 */
function mc_cors_allowed_origins() {
    return [
        'https://sol1.tail2d1d46.ts.net',
        'http://localhost:4000',
        'http://127.0.0.1:4000',
    ];
}

function mc_cors_send_headers() {
    $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
    if ($origin && in_array($origin, mc_cors_allowed_origins(), true)) {
        header('Access-Control-Allow-Origin: ' . $origin);
        header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, X-WP-Nonce, X-Requested-With');
        header('Access-Control-Expose-Headers: Link, X-WP-Total, X-WP-TotalPages');
        header('Access-Control-Max-Age: 86400');
        header('Vary: Origin');
    }
}

/**
 * Replace WP core's CORS handler so the headers above are actually used on the
 * REST response (core hard-codes Access-Control-Allow-Origin: *, which is rejected
 * by browsers when the request includes credentials/Authorization).
 */
add_action('rest_api_init', function () {
    remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
    add_filter('rest_pre_serve_request', function ($value) {
        mc_cors_send_headers();
        return $value;
    }, 15);
}, 15);

/**
 * Handle CORS preflight (OPTIONS) before WordPress 404s on it.
 * Browsers send this before any /wp-json call that carries Authorization.
 */
add_action('init', function () {
    if (
        isset($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']) &&
        $_SERVER['REQUEST_METHOD'] === 'OPTIONS' &&
        strpos($_SERVER['REQUEST_URI'], '/wp-json/') === 0
    ) {
        mc_cors_send_headers();
        status_header(204);
        exit;
    }
}, 0);
