<?php
if (!defined('ABSPATH')) exit;

class SS_Telemetry_Diagnostics {

    public static function init() {
        if (is_admin()) {
            add_action('admin_menu', [__CLASS__, 'menu']);

            // Test actions
            add_action('admin_post_ss_telemetry_ping',           [__CLASS__, 'handle_ping']);
            add_action('admin_post_ss_telemetry_force_error',    [__CLASS__, 'handle_force_error']);
            add_action('admin_post_ss_telemetry_direct_ingest',  [__CLASS__, 'handle_direct_ingest']);
        }
    }

    public static function menu() {
        add_submenu_page(
            'searchshifter',
            'Telemetry Test',
            'Telemetry Test',
            'manage_options',
            'ss-telemetry-test',
            [__CLASS__, 'render']
        );
    }

    private static function api_base_value() {
        if (class_exists('SS_Settings')) {
            return (string) get_option(SS_Settings::OPT_API_BASE, defined('SEARCHSHIFTER_API_BASE') ? SEARCHSHIFTER_API_BASE : '');
        }
        return defined('SEARCHSHIFTER_API_BASE') ? SEARCHSHIFTER_API_BASE : '';
    }

    /** Headers some servers expect (API key + domain) */
    private static function api_headers() {
        $headers = ['Content-Type' => 'application/json'];

        $apiKey = class_exists('SS_Settings') ? (string) get_option(SS_Settings::OPT_API_KEY, '') : '';
        $domain = class_exists('SS_Settings')
            ? (string) get_option(SS_Settings::OPT_DOMAIN, wp_parse_url(get_site_url(), PHP_URL_HOST))
            : (string) wp_parse_url(get_site_url(), PHP_URL_HOST);

        if ($apiKey) {
            $headers['Authorization'] = 'Bearer '.$apiKey;
            $headers['X-Api-Key']     = $apiKey;
        }
        if ($domain) {
            $headers['X-Domain']     = $domain;      // your middleware commonly reads this
            $headers['X-SS-Domain']  = $domain;      // future-proof mirror
        }
        $headers['X-SS-Client'] = 'wordpress';
        $headers['User-Agent']  = 'SearchShifter/' . (defined('SEARCHSHIFTER_VERSION') ? SEARCHSHIFTER_VERSION : 'unknown');

        return $headers;
    }

    public static function render() {
        if (!current_user_can('manage_options')) return;

        $api_base = self::api_base_value();
        $enabled  = class_exists('SS\\Core\\Telemetry') ? SS\Core\Telemetry::isEnabled() : false;

        echo '<div class="wrap"><h1>Telemetry Test</h1>';

        // Notices (also shows result of blocking direct-ingest call)
        if (
            isset($_GET['ss_telemetry_notice'], $_GET['_wpnonce']) &&
            wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'ss_telemetry_notice' )
        ) {

            $n = sanitize_text_field(
                wp_unslash( $_GET['ss_telemetry_notice'] )
            );
            if ($n === 'ping')          echo '<div class="notice notice-success"><p>Queued test telemetry. It will flush on page end.</p></div>';
            if ($n === 'forced_error')  echo '<div class="notice notice-warning"><p>Forced API error sent. Check <code>telemetry_events</code> for an <code>api_error</code> row.</p></div>';
            if ($n === 'unexpected_ok') echo '<div class="notice notice-info"><p>Unexpected OK from forced error call.</p></div>';
            if ($n === 'no_telemetry')  echo '<div class="notice notice-error"><p>Telemetry is OFF. Enable it in SearchShifter settings to test.</p></div>';
            if ($n === 'bad_api_base')  echo '<div class="notice notice-error"><p>API Base must end with <code>/api</code>. Current: <code>'.esc_html($api_base).'</code></p></div>';
            if (strpos($n, 'code=') === 0 || strpos($n, 'wp_error:') === 0) {
                echo '<div class="notice notice-info"><p>'.esc_html(urldecode($n)).'</p></div>';
            }
        }

        echo '<p><strong>API Base URL:</strong> <code>'.esc_html($api_base ?: '—').'</code></p>';
        echo '<p><strong>Telemetry Enabled:</strong> '.($enabled ? '<span style="color:#0a0">Yes</span>' : '<span style="color:#a00">No</span>').'</p>';
       $bufSize = class_exists('SS\\Core\\Telemetry') ? SS\Core\Telemetry::bufferSize() : 0;
echo '<p><strong>Telemetry buffer size:</strong> '.intval($bufSize).'</p>';

if (defined('SS_TEL_DEBUG_FILE') && SS_TEL_DEBUG_FILE && file_exists(SS_TEL_DEBUG_FILE)) {
    $tail = @file_get_contents(SS_TEL_DEBUG_FILE);
    $tail = $tail ? implode("\n", array_slice(explode("\n", $tail), -80)) : '';
    echo '<h2>Log Tail</h2><pre style="max-height:280px;overflow:auto;background:#111;color:#0f0;padding:10px;">'.esc_html($tail ?: '(empty)').'</pre>';
} else {
    echo '<p><em>Debug log file: </em><code>'.esc_html(defined('SS_TEL_DEBUG_FILE') ? SS_TEL_DEBUG_FILE : '(not set)').'</code></p>';
}


        echo '<p><em>If API Base is wrong (e.g., <code>…/apis</code>), telemetry cannot reach the server, so no DB rows will appear.</em></p>';

        if ($enabled) {
            echo '<form method="post" action="'.esc_url(admin_url('admin-post.php')).'" style="display:inline-block;margin-right:12px">';
            wp_nonce_field('ss_telemetry_ping');
            echo '<input type="hidden" name="action" value="ss_telemetry_ping" />';
            submit_button('Send Telemetry Test Ping', 'secondary', 'submit', false);
            echo '</form>';

            echo '<form method="post" action="'.esc_url(admin_url('admin-post.php')).'" style="display:inline-block;margin-right:12px">';
            wp_nonce_field('ss_telemetry_force_error');
            echo '<input type="hidden" name="action" value="ss_telemetry_force_error" />';
            submit_button('Force API Error (expect telemetry)', 'secondary', 'submit', false);
            echo '</form>';

            echo '<form method="post" action="'.esc_url(admin_url('admin-post.php')).'" style="display:inline-block">';
            wp_nonce_field('ss_telemetry_direct_ingest');
            echo '<input type="hidden" name="action" value="ss_telemetry_direct_ingest" />';
            submit_button('Send Direct Ingest (blocking)', 'secondary', 'submit', false);
            echo '</form>';
        } else {
            echo '<p><em>Enable the Telemetry checkbox in SearchShifter settings to use these test buttons.</em></p>';
        }

        echo '</div>';
    }

    public static function handle_ping() {
        if (!current_user_can('manage_options')) wp_die('No permission');
        check_admin_referer('ss_telemetry_ping');

        if (!class_exists('SS\\Core\\Telemetry') || !SS\Core\Telemetry::isEnabled()) {
            wp_safe_redirect( admin_url('admin.php?page=ss-telemetry-test&ss_telemetry_notice=no_telemetry') ); exit;
        }

        SS\Core\Telemetry::queue('test_event', ['screen'=>'diagnostics']);
        wp_safe_redirect( admin_url('admin.php?page=ss-telemetry-test&ss_telemetry_notice=ping') ); exit;
    }

    public static function handle_force_error() {
        if (!current_user_can('manage_options')) wp_die('No permission');
        check_admin_referer('ss_telemetry_force_error');

        $api_base = self::api_base_value();
        if (!$api_base || !preg_match('#/api/?$#', $api_base)) {
            wp_safe_redirect( admin_url('admin.php?page=ss-telemetry-test&ss_telemetry_notice=bad_api_base') ); exit;
        }

        // Use Http client (non-blocking) – headers handled there already
        $r = \SS\Core\Http::postJson('license.validate', '/__nonexistent__', []);
        $flag = !empty($r['ok']) ? 'unexpected_ok' : 'forced_error';
        wp_safe_redirect( admin_url('admin.php?page=ss-telemetry-test&ss_telemetry_notice=' . $flag) ); exit;
    }

    public static function handle_direct_ingest() {
        if (!current_user_can('manage_options')) wp_die('No permission');
        check_admin_referer('ss_telemetry_direct_ingest');

        $api_base = self::api_base_value();
        if (!$api_base || !preg_match('#/api/?$#', $api_base)) {
            wp_safe_redirect( admin_url('admin.php?page=ss-telemetry-test&ss_telemetry_notice=bad_api_base') ); exit;
        }

        // Minimal, valid event
        $installation_id = class_exists('SS\\Core\\Telemetry') ? SS\Core\Telemetry::installationId() : uniqid('ss_', true);
        $host            = wp_parse_url(home_url(), PHP_URL_HOST);
        $domain_hash     = hash('sha256', is_string($host) ? strtolower($host) : '');

        $event = [
            'installation_id' => $installation_id,
            'domain_hash'     => $domain_hash,
            'plugin_version'  => (defined('SEARCHSHIFTER_VERSION') ? SEARCHSHIFTER_VERSION : 'unknown'),
            'php_version'     => PHP_VERSION,
            'wp_version'      => get_bloginfo('version'),
            'site_locale'     => get_locale(),
            'platform'        => 'wordpress',
            'event'           => 'direct_test',
            'timestamp'       => gmdate('c'),
            'feature_flags'   => ['qa'=>false,'llms'=>false,'schema'=>false],
            'data'            => ['endpoint' => 'diagnostics'],
        ];

        $endpoint = rtrim($api_base, '/') . '/telemetry/ingest';

        // BLOCKING request with headers (API key + domain)
        $resp = wp_remote_post($endpoint, [
            'timeout'  => 10,
            'blocking' => true,
            'headers'  => self::api_headers(),
            'body'     => wp_json_encode(['events' => [$event]]),
        ]);

        if (is_wp_error($resp)) {
            $msg = rawurlencode('wp_error: ' . $resp->get_error_message());
            wp_safe_redirect( admin_url('admin.php?page=ss-telemetry-test&ss_telemetry_notice=' . $msg) ); exit;
        }

        $code = (int) wp_remote_retrieve_response_code($resp);
        $body = wp_remote_retrieve_body($resp);
        $msg  = rawurlencode('code='.$code.' body='.substr($body,0,200));
        wp_safe_redirect( admin_url('admin.php?page=ss-telemetry-test&ss_telemetry_notice=' . $msg) ); exit;
    }
}
