<?php

defined('ABSPATH') || exit;

class InsightPress_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('InsightPress_Settings_API') && !InsightPress_Settings_API::is_feature_enabled('usage_tracking')) {
            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'    => 'InsightPress/' . INSIGHTPRESS_ADVANCED_ANALYTICS_FOR_WOOCOMMERCE_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, '/');
    }
}
