<?php
/**
 * Admin Panel: GEO Diagnostics
 *
 * Location:
 * /wp-content/plugins/searchshifter/admin/class-ss-admin-geo-diagnostics.php
 *
 * Works with:
 * - includes/geo_diagnostics.php (engine)
 * - AJAX: searchshifter_geo_run_scan
 * - Authority plan gating handled in SS_Setup
 */

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

if (!class_exists('SS_Admin_GEO_Diagnostics')) {

    class SS_Admin_GEO_Diagnostics {
        /**
         * Render admin page
         */
        public static function render_page() {

            // Safety: check authority license
            $license = class_exists('SS_Licensing') ? SS_Licensing::get_cached_status() : [];
            $plan = strtolower($license['plan'] ?? 'free');

            if (!in_array($plan, ['authority', 'elite'], true)) {
                echo '<div class="wrap"><h1>🔒 GEO Diagnostics</h1>
                    <p>This feature requires the <strong>Authority</strong> or <strong>Elite</strong> edition.</p>
                    <a href="https://searchshifter.ai/pricing" class="button button-primary" target="_blank">Upgrade</a>
                    </div>';
                return;
            }

            ?>

            <div class="wrap ss-geo-wrap">
                <h1 style="margin-bottom: 10px;">🌐 GEO Diagnostics</h1>
                <p style="margin-bottom: 20px;">Analyze AI visibility readiness and track progress over time for this website.</p>

                <div class="ss-geo-card" style="background:#fff;padding:25px;border-radius:8px;border:1px solid #e1e1e1;max-width:900px;">
                    <h2>Run GEO Scan</h2>

                    <table class="form-table">
                        <tr>
                            <th><label for="ss_geo_domain">Domain</label></th>
                            <td>
                                <input type="text" id="ss_geo_domain" class="regular-text" placeholder="example.com" />
                                <p class="description">Enter your registered domain.</p>
                            </td>
                        </tr>
                    </table>

                    <p>
                        <button class="button button-primary" id="ss_geo_run_btn">Run Scan</button>
                    </p>

                    <div id="ss_geo_loading" style="display:none;margin:10px 0;">
                        <span class="spinner is-active" style="float:none;visibility:visible;"></span>
                        Running GEO diagnostics…
                    </div>

                    <div id="ss_geo_results" style="margin-top:20px;"></div>
                    <div id="ss_geo_history" style="margin-top:30px;"></div>

                </div>
            </div>

            <script>
                (function($){

                    $('#ss_geo_run_btn').on('click', function(e){
                        e.preventDefault();

                        let domain = $('#ss_geo_domain').val()
                        .replace(/^https?:\/\//, '')
                        .replace(/\/$/, '')
                        .trim();
                        if (!domain) {
                            alert('Please enter a domain.');
                            return;
                        }

                        $('#ss_geo_loading').show();
                        $('#ss_geo_results').html('');

                        $.post(ajaxurl, {
                            action: 'searchshifter_geo_run_scan',
                            domain: domain,
                            _nonce: '<?php echo esc_js( wp_create_nonce( 'searchshifter_geo_run_scan' ) ); ?>'

                        })
                        .done(function(resp) {

                            $('#ss_geo_loading').hide();

                            if (resp.success) {
                                const d = resp.data;

                                let messages = [];
                                let statusLabel = 'Partial AI Visibility';
                                let statusClass = 'warning';

                                if (d.signals?.dns_resolves) messages.push('✅ AI crawlers can reach your site');
                                else messages.push('❌ AI crawlers cannot reach your site');

                                if (d.signals?.uses_https) messages.push('✅ Secure HTTPS detected');
                                else messages.push('⚠️ HTTPS not detected');

                                if (d.signals?.has_cdn) messages.push('✅ CDN detected');
                                else messages.push('⚠️ CDN not detected');

                                if (d.signals?.dns_resolves && d.signals?.uses_https && d.signals?.has_cdn) {
                                    statusLabel = 'AI-Ready';
                                    statusClass = 'success';
                                }

                                $('#ss_geo_results').html(`
                                    <h2>GEO Visibility Summary</h2>
                                    <div class="ss-geo-summary ss-${statusClass}">
                                        <ul>${messages.map(m => `<li>${m}</li>`).join('')}</ul>
                                        <strong>Status:</strong> ${statusLabel}
                                    </div>
                                `);

                                loadGeoHistory(domain);

                            } else {
                                $('#ss_geo_results').html(
                                    '<div class="notice notice-error"><p>Error: ' + resp.data + '</p></div>'
                                );
                            }

                        })
                        .fail(function(xhr) {
                            $('#ss_geo_loading').hide();
                            $('#ss_geo_results').html(
                                '<div class="notice notice-error"><p>Request failed</p></div>'
                            );
                        });


                    });

                    function loadGeoHistory(domain) {
                        $.post(ajaxurl, {
                            action: 'searchshifter_geo_recent_scans',
                            domain: domain,
                            searchshifter_nonce: '<?php echo esc_js( wp_create_nonce( 'searchshifter_geo_recent_scans' ) ); ?>'
                        }, function(resp) {

                            if (!resp.success || !resp.data.length) {
                                $('#ss_geo_history').html('<p>No previous scans found.</p>');
                                return;
                            }

                            let rows = resp.data.map(scan => `
                                <tr>
                                    <td>${scan.created_at}</td>
                                    <td><strong>${scan.score}</strong></td>
                                    <td>${scan.score >= 80 ? '✅ Strong' : scan.score >= 50 ? '⚠️ Partial' : '❌ Weak'}</td>
                                </tr>
                            `).join('');

                            $('#ss_geo_history').html(`
                            <h2>Previous GEO Scans</h2>
                                <p class="description">Use this history to demonstrate progress and improvements over time.</p>
                                <table class="widefat striped">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Score</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>${rows}</tbody>
                                </table>
                            `);
                        });
                    }

                })(jQuery);
            </script>

            <style>
                .ss-geo-wrap h1 { font-size: 28px; }
                .ss-geo-card { box-shadow: 0 2px 6px rgba(0,0,0,0.06); }
                pre { white-space: pre-wrap; word-break: break-all; }

                .ss-geo-summary {
                    padding: 15px;
                    border-radius: 6px;
                    margin-bottom: 10px;
                }
                .ss-geo-summary ul {
                    margin-left: 18px;
                }
                .ss-success {
                    background: #e7f7ec;
                    border-left: 4px solid #2ecc71;
                }
                .ss-warning {
                    background: #fff6e5;
                    border-left: 4px solid #f39c12;
                }
                .ss-geo-history tr:first-child {
                background: #f0f9ff;
                }


            </style>

            <?php
        }

    }


}

add_action('wp_ajax_searchshifter_geo_run_scan', 'searchshifter_geo_run_scan');

function searchshifter_geo_run_scan() {
        
    check_ajax_referer('searchshifter_geo_run_scan', '_nonce');

    $domain = '';

    if ( isset( $_POST['domain'] ) ) {
        $domain = sanitize_text_field(
            wp_unslash( $_POST['domain'] )
        );
    }

    if (!$domain) {
        wp_send_json_error('Missing domain');
    }

    $api_key = get_option('ss_api_token');
    $api_base = defined('SEARCHSHIFTER_API_BASE')
        ? SEARCHSHIFTER_API_BASE
        : get_option('searchshifter_api_base');


    if (!$api_key || !$api_base) {
            wp_send_json_error('Site not registered with SearchShifter Hub');
    }

    $response = wp_remote_post($api_base . '/api/geo-scan', [
        'headers' => [
            'Authorization' => 'Bearer ' . $api_key,
            'X-Domain'      => $domain,
            'Content-Type'  => 'application/json',
            ],
            'body'    => json_encode(['domain' => $domain]),
            'timeout' => 60,
    ]);

    if (is_wp_error($response)) {
        wp_send_json_error($response->get_error_message());
    }

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

    if ($code !== 200) {
        wp_send_json_error($body['error'] ?? 'GEO scan failed');
    }

    wp_send_json_success($body);
}

add_action('wp_ajax_searchshifter_geo_recent_scans', 'searchshifter_geo_recent_scans');

function searchshifter_geo_recent_scans() {

        $api_key = get_option('ss_api_token');
        $api_base = defined('SEARCHSHIFTER_API_BASE')
            ? SEARCHSHIFTER_API_BASE
            : get_option('searchshifter_api_base');

        $domain = '';

        if (
            isset( $_POST['domain'], $_POST['searchshifter_nonce'] )
            && wp_verify_nonce(
                sanitize_text_field( wp_unslash( $_POST['searchshifter_nonce'] ) ),
                'searchshifter_geo_recent_scans'
            )
        ) {
            $domain = sanitize_text_field(
                wp_unslash( $_POST['domain'] )
            );
        }


        if (!$api_key || !$api_base || !$domain) {
            wp_send_json_error('Missing config');
        }

        $response = wp_remote_get($api_base . '/api/geo-scan/recents', [
            'headers' => [
                'Authorization' => 'Bearer ' . $api_key,
                'X-Domain'      => $domain,
            ],
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            wp_send_json_error($response->get_error_message());
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);

        wp_send_json_success($body['scans'] ?? []);
}
