<?php 

class StatsAjax {
    public static function init(): void
    {
        add_action('wp_ajax_zoddak_send_stats', [self::class, 'handle']);
        add_action('wp_ajax_nopriv_zoddak_send_stats', [self::class, 'handle']);
    }

    public static function handle(): void
    {
        $input = [
            'agency_domain' => get_option('siteurl'), // o home_url()
            'agency_token'  => get_option('zoddak_api_token'),
            'property_ref'  => sanitize_text_field($_POST['property_ref'] ?? ''),
            'event'         => sanitize_text_field($_POST['event'] ?? ''),
            'extra_data'    => sanitize_text_field($_POST['extraData'] ?? ''),
            'user_agent'    => sanitize_text_field($_POST['user_agent'] ?? ''),
            'session_id'    => sanitize_text_field($_POST['session_id'] ?? ''),
            'lang'          => sanitize_text_field($_POST['lang'] ?? ''),
            'mobile'        => sanitize_text_field($_POST['mobile'] ?? ''),
            'ip_address'    => $_SERVER['REMOTE_ADDR'] ?? null,
        ];

        $api_url = zoddak_get_api_base_url() . '/wpstats/saveStat';

        $response = wp_remote_post($api_url, [
            'method'  => 'POST',
            'timeout' => 10,
            'headers' => [
                'Content-Type' => 'application/json',
                'API-TOKEN'    => ZODDAK_STATS_TOKEN,
            ],
            'body' => wp_json_encode($input),
        ]);

        if (is_wp_error($response)) {
            wp_send_json_error(['message' => 'External API Error'], 500);
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $json = json_decode($body, true);

        // Si tu API no responde JSON válido, evita petar devolviendo algo útil
        if (!is_array($json)) {
            wp_send_json_error([
                'message' => 'Invalid API response',
                'status'  => $code,
                'raw'     => $body,
            ], 502);
        }

        wp_send_json($json, $code ?: 200);
    }
}