<?php

defined('ABSPATH') || exit;

class ShopCentral_Remote_API
{
    private static $token = 'z1yN6YtKp3dQw8VhR2cU9mlb7XjA4DFMG0He9qPiDoSrTuWvYlZkBnCfDgEhJiY5';
    private static $base_url = 'https://dominopress.com/api/woocommerce/';

    /**
     * Send a POST request to the remote API
     */
    public static function post($endpoint, $body, $blocking = false)
    {
        // Global guard for usage tracking - don't send data if disabled
        if (class_exists('ShopCentral_Settings_API') && !ShopCentral_Settings_API::is_feature_enabled('usage_tracking')) {
            error_log('ShopCentral: Tracking blocked - usage tracking not enabled');
            return false;
        }

        $url = self::$base_url . ltrim($endpoint, '/');
        $host = parse_url($url, PHP_URL_HOST);

        // Ensure we allow requests to our domain even from local environments
        add_filter('http_request_host_is_external', function ($is_external, $request_host, $request_url) use ($host) {
            if ($request_host === $host || $request_host === '127.0.0.1' || $request_host === 'localhost') {
                return true;
            }
            return $is_external;
        }, 10, 3);

        $response = wp_remote_post($url, [
            'method'    => 'POST',
            'timeout'   => 30,
            'blocking'  => $blocking,
            'headers'   => [
                'Content-Type'  => 'application/json',
                'Authorization' => 'Bearer ' . self::$token,
                'User-Agent'    => 'ShopCentral/' . SHOPCENTRAL_VERSION . '; ' . get_bloginfo('url')
            ],
            'body'        => json_encode($body),
            'data_format' => 'body',
        ]);

        return $response;
    }

    /**
     * Get the full URL for an endpoint
     */
    public static function get_url($endpoint)
    {
        return self::$base_url . ltrim($endpoint, '/');
    }
}
