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

    class SS_Advanced_Reporting {
        const NONCE = 'ss_adv_report_nonce';

        // const NONCE              = 'ss_adv_report_nonce';
        const OPTION_BRAND       = 'ss_advreport_branding';
        const OPTION_COMPETITORS = 'ss_advreport_competitors';

        /* ======================================================
        * INIT
        * ====================================================== */
        public static function init() { 

            add_action('admin_enqueue_scripts', [__CLASS__, 'assets']);

            // Advanced Reporting
            add_action('wp_ajax_ss_adv_preview', [__CLASS__, 'preview']);
            add_action('admin_post_ss_adv_export', [__CLASS__, 'export']);
            add_action('wp_ajax_ss_adv_save_brand', [__CLASS__, 'save_brand']);

            // Competitive Analysis
            add_action('wp_ajax_ss_save_competitors', [__CLASS__, 'save_competitors']);
            add_action('wp_ajax_ss_competitive_benchmark', [__CLASS__, 'run_benchmark']);
        }

        /* ======================================================
        * ASSETS
        * ====================================================== */
        public static function assets($hook) {

            if ($hook !== 'searchshifter_page_ss-advanced-reporting') {
                return;
            }
            wp_enqueue_media();
            wp_enqueue_script(
                'ss-chartjs',
                SEARCHSHIFTER_PLUGIN_URL . 'assets/js/chartjs/chart.umd.js',
                [],
                '4.4.0',
                true
            );


            wp_register_style(
                'ss-adv-report',
                false,
                [],
                SEARCHSHIFTER_VERSION // plugin version constant
            );

            wp_enqueue_style('ss-adv-report');

            wp_add_inline_style('ss-adv-report', '
                .ss-grid{
                    display:grid;
                    grid-template-columns:repeat(2,1fr);
                    gap:16px;
                    margin-bottom:20px;
                }
                .ss-card{
                    border:1px solid #e5e7eb;
                    padding:16px;
                    border-radius:10px;
                    background:#fff;
                    cursor:pointer;
                    transition:0.2s ease;
                }
                .ss-card.active{
                    border-color:#2271b1;
                    background:#f0f7ff;
                }
                .ss-card strong{
                    display:block;
                    font-size:15px;
                    font-weight:600;
                }
                .ss-card p{
                    margin:6px 0 0;
                    font-size:13px;
                    color:#64748b;
                }
            ');
        }



        /* ======================================================
        * PAGE UI
        * ====================================================== */
        public static function page() {

          

            if (!current_user_can('manage_options')) {
                wp_die('Unauthorized');
            }

            $brand = get_option(self::OPTION_BRAND, [
                'company' => 'SearchShifter',
                'logo'    => ''
            ]);

            $competitors = get_option(self::OPTION_COMPETITORS, []);
            // wp_nonce_field(self::NONCE, '_nonce', false, true);
            // echo '<input type="hidden" id="_nonce" name="_nonce" value="' . wp_create_nonce(self::NONCE) . '">';


            ?>
        <input type="hidden" id="ss_adv_nonce"
                    value="<?php echo esc_attr( wp_create_nonce( self::NONCE ) ); ?>">
                    <div class="wrap">
                        <h1>Advanced Reporting</h1>

                        <div class="notice notice-info" style="padding:18px;margin-top:15px;">

                            <h2 style="margin-top:0;">🚀 Quick Start Guide</h2>

                            <ol style="margin-left:18px;line-height:1.8;">

                                <li>
                                    <strong>Set Your Branding</strong><br>
                                    Add your company name and logo for white-label PDF reports.
                                </li>

                                <li>
                                    <strong>Select Report Type</strong><br>
                                    Choose between AI Visibility reports or AI Crawler monitoring.
                                </li>

                                <li>
                                    <strong>Apply Filters</strong><br>
                                    Optionally choose a date range to export specific records.
                                </li>

                                <li>
                                    <strong>Preview Before Export</strong><br>
                                    Use Preview to verify report data before downloading.
                                </li>

                                <li>
                                    <strong>Run Competitive Benchmark</strong><br>
                                    Compare your website against competitors for SEO and AI visibility signals.
                                </li>

                            </ol>

                        </div>

                        <h2>White-label Branding</h2>
                        <form id="ss-brand-form">
                            <input type="text" id="ss_company"
                                value="<?php echo esc_attr($brand['company']); ?>"
                                placeholder="Company Name">

                            <div class="ss-field">
                                <label>Logo</label>

                                <div class="ss-logo-row">

                                    <!-- Preview -->
                                    <div id="ss-logo-preview" class="ss-logo-preview">
                                        <?php if (!empty($brand['logo'])): ?>
                                            <img src="<?php echo esc_url($brand['logo']); ?>">
                                        <?php else: ?>
                                            <span>No logo</span>
                                        <?php endif; ?>
                                    </div>

                                    <!-- Controls -->
                                    <div class="ss-logo-controls">
                                        <input type="hidden" id="ss_logo"
                                            value="<?php echo esc_attr($brand['logo']); ?>">

                                        <button type="button" class="button" id="ss-upload-logo">
                                            Upload
                                        </button>

                                        <button type="button" class="button" id="ss-remove-logo">
                                            Remove
                                        </button>
                                    </div>

                                </div>
                            </div>
                    <br>

              

                    <button class="button button-primary">Save Branding</button>
                </form>

                <hr>

                <h2>Select Report Type</h2>
                <div class="ss-grid">
                    <div class="ss-card active" data-type="scans">
                        <strong>AI Visibility Performance</strong>
                        <p>Shows optimization scores, recommendations, and AI visibility health.</p>
                    </div>
                    <div class="ss-card" data-type="crawler">
                        <strong>AI Bot & Search Engine Visits</strong>
                        <p>Track visits from AI bots, crawlers, and search engines.</p>
                    </div>
                </div>

                <!-- <h3>Filters</h3>

                <div class="ss-filter-row">

                    <div>
                        <label><strong>From Date</strong></label><br>
                        <input type="date" id="ss_from">
                    </div>

                    <div>
                        <label><strong>To Date</strong></label><br>
                        <input type="date" id="ss_to">
                    </div>

                    <div style="padding-top:22px;">
                        <button type="button" class="button" id="ss_reset_filters">
                            Reset Filters
                        </button>
                    </div>

                </div> -->
 

                <p>
                    <button class="button button-primary" id="ss_preview">Preview</button>
                    <button class="button" id="ss_csv">Export CSV</button>
                    <button class="button" id="ss_pdf">Export PDF</button>
                </p>

                <div class="ss-preview-wrap">

                    <div class="ss-preview-header">
                        <h3>📄 Report Preview</h3>
                        <small>Preview generated report data before export.</small>
                    </div>

                    <div id="ss_output" class="ss-report-table">
                        <div class="ss-empty-state">
                            Select filters and click Preview to generate a report.
                        </div>
                    </div>

                </div>

                <hr>
            <div class="ss-competitor-box">
                <h2>Competitive Analysis</h2>

                <p>
                    <button class="button button-primary" id="ss-run">
                        Run Competitive Benchmark
                    </button>
                </p>

                <div id="ss-results"></div>

                <h3>Add Competitor URLs</h3>
                <textarea
                    id="ss-competitors"
                    placeholder="Enter one competitor URL per line..."rows="4" style="width:100%;max-width:600px;"><?php
                                    echo esc_textarea(implode("\n", $competitors));
                ?></textarea>

                <p>
                    <button class="button" id="ss-save">Save Competitors</button>
                </p>

                
                <style>
                    .ss-competitor-box{
                        background:#fff;
                        border:1px solid #e5e7eb;
                        border-radius:10px;
                        padding:20px;
                        margin-top:30px;
                    }
                    .ss-preview-wrap{
                        background:#fff;
                        border:1px solid #e5e7eb;
                        border-radius:10px;
                        padding:16px;
                        margin-top:20px;
                    }

                    .ss-preview-header{
                        margin-bottom:14px;
                    }

                    .ss-empty-state{
                        padding:40px;
                        text-align:center;
                        color:#64748b;
                        border:2px dashed #e2e8f0;
                        border-radius:8px;
                        background:#f8fafc;
                    }
                    .ss-logo-row{
                        display:flex;
                        align-items:center;
                        gap:16px;
                        margin-top:8px;
                    }

                    .ss-logo-preview{
                        width:120px;
                        height:120px;
                        border:1px dashed #cbd5f5;
                        border-radius:8px;
                        display:flex;
                        align-items:center;
                        justify-content:center;
                        background:#f8fafc;
                    }

                    .ss-logo-preview img{
                        max-width:70px;
                        max-height:70px;
                    }

                    .ss-logo-preview span{
                        font-size:12px;
                        color:#64748b;
                    }

                    .ss-logo-controls{
                        display:flex;
                        flex-direction:column;
                        gap:8px;
                    }
                    /* Admin-safe force styles */
                    .ss-grid{
                        display:grid !important;
                        grid-template-columns:repeat(2,1fr) !important;
                        gap:16px !important;
                        margin:16px 0 !important;
                    }

                    .ss-card{
                        display:block !important;
                        border:1px solid #e5e7eb !important;
                        padding:16px !important;
                        border-radius:10px !important;
                        background:#fff !important;
                        cursor:pointer !important;
                    }

                    .ss-card.active{
                        border-color:#2271b1 !important;
                        background:#f0f7ff !important;
                    }

                    .ss-card strong{
                        display:block !important;
                        font-size:15px !important;
                        font-weight:600 !important;
                    }

                    .ss-card p{
                        margin:6px 0 0 !important;
                        font-size:13px !important;
                        color:#64748b !important;
                    }
                </style>

            </div>

            <script>
                jQuery(function($){


                            let mediaUploader;

                            $('#ss-upload-logo').on('click', function(e){
                                e.preventDefault();

                                if (mediaUploader) {
                                    mediaUploader.open();
                                    return;
                                }

                                mediaUploader = wp.media({
                                    title: 'Select Logo',
                                    button: { text: 'Use this logo' },
                                    multiple: false
                                });

                                mediaUploader.on('select', function(){
                                    const attachment = mediaUploader.state().get('selection').first().toJSON();

                                    $('#ss_logo').val(attachment.url);

                                    $('#ss-logo-preview').html(
                                        `<img src="${attachment.url}">`
                                    );
                                });

                                mediaUploader.open();
                            });

                            $('#ss-remove-logo').on('click', function(){
                                $('#ss_logo').val('');
                                $('#ss-logo-preview').html('<span>No logo</span>');
                            });

                        
                            $('#ss_reset_filters').on('click', function(){

                                $('#ss_from').val('');
                                $('#ss_to').val('');

                                $('#ss_preview').trigger('click');

                            });
               
                    let type = 'scans';

                    /* =========================
                    REPORT TYPE SELECT
                    ========================= */
                    $('.ss-card').on('click', function(){
                        $('.ss-card').removeClass('active');
                        $(this).addClass('active');
                        type = $(this).data('type');
                    });

                    /* =========================
                    PREVIEW
                    ========================= */
                    $('#ss_preview').on('click', function(){

                        $('#ss_output').html('<p>Loading preview…</p>');

                        $.post(ajaxurl,{
                            action: 'ss_adv_preview',
                            _nonce: $('#ss_adv_nonce').val(),
                            type: type, 
                            from: $('#ss_from').val(),
                            to: $('#ss_to').val()
                        })
                        .done(function(r){
                            $('#ss_output').html(r.success ? r.data.html : '<p>No data</p>');
                        })
                        .fail(function(xhr){
                            $('#ss_output').html('<p>Preview failed ('+xhr.status+')</p>');
                        });

                    });

                    /* =========================
                    EXPORT
                    ========================= */
                    function exportFile(fmt){
                        const f = $('<form method="post" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>"></form>');

                        f.append('<input type="hidden" name="action" value="ss_adv_export">');
                        f.append('<input type="hidden" name="_nonce" value="'+$('#ss_adv_nonce').val()+'">'); // ✅ ADD
                        f.append('<input type="hidden" name="type" value="'+type+'">');
                        f.append('<input type="hidden" name="format" value="'+fmt+'">');
                        f.append('<input type="hidden" name="from" value="'+$('#ss_from').val()+'">');
                        f.append('<input type="hidden" name="to" value="'+$('#ss_to').val()+'">');

                        $('body').append(f);
                        f.submit();
                        f.remove();
                    }

                    $('#ss_csv').on('click', () => exportFile('csv'));
                    $('#ss_pdf').on('click', () => exportFile('pdf'));

                    /* =========================
                    SAVE BRAND
                    ========================= */
                    $('#ss-brand-form').on('submit', function(e){
                        e.preventDefault();

                        $.post(ajaxurl,{
                            action: 'ss_adv_save_brand',
                            _nonce: $('#ss_adv_nonce').val(),
                            company: $('#ss_company').val(),
                            logo: $('#ss_logo').val()
                        }).done(function(res){
                        if(res.success){
                            $('#ss-brand-form').append('<span id="ss-save-msg" style="margin-left:10px;color:green;">Saved ✓</span>');
                            setTimeout(()=> $('#ss-save-msg').fadeOut(), 2000);
                        } else {
                            alert('Error saving');
                        }
                    });
                    });

                    /* =========================
                    SAVE COMPETITORS
                    ========================= */
                    $('#ss-save').on('click', function(){
                        $.post(ajaxurl,{
                            action: 'ss_save_competitors',
                            _nonce: $('#ss_adv_nonce').val(),
                            competitors: $('#ss-competitors').val()
                        })
                        .done(res => alert(res.success ? 'Saved' : 'Error'))
                        .fail(xhr => alert('Failed ('+xhr.status+')'));
                    });

                    /* =========================
                    COMPETITIVE BENCHMARK
                    ========================= */
                    $('#ss-run').on('click', function(){

                        $('#ss-results').html('<p>Running analysis…</p>');

                        $.post(ajaxurl,{
                            action: 'ss_competitive_benchmark',
                             _nonce: $('#ss_adv_nonce').val()
                        })
                        .done(function(res){

                            if(!res.success){
                                $('#ss-results').html('<p>No data</p>');
                                return;
                            }

                            $('#ss-results').html(res.data.html);

                            setTimeout(function(){

                                if (typeof Chart === 'undefined') {
                                    console.error('Chart.js not loaded');
                                    return;
                                }

                                const ctx = document.getElementById('ssChart');
                                if(!ctx) return;

                                new Chart(ctx, {
                                    type: 'bar',
                                    data: {
                                        labels: res.data.rows.map(r => r.domain),
                                        datasets: [
                                            {
                                                label: 'Schema',
                                                data: res.data.rows.map(r => r.schema),
                                                backgroundColor: res.data.rows.map(r => r.own ? '#2271b1' : '#94a3b8')
                                            },
                                            {
                                                label: 'Visibility',
                                                data: res.data.rows.map(r => r.visibility),
                                                backgroundColor: res.data.rows.map(r => r.own ? '#22c55e' : '#bbf7d0')
                                            }
                                        ]
                                    },
                                    options: {
                                        responsive: true,
                                        plugins: { legend: { position: 'top' } },
                                        scales: { y: { beginAtZero: true } }
                                    }
                                });

                            }, 100);

                        })
                        .fail(xhr => $('#ss-results').html('<p>Benchmark failed ('+xhr.status+')</p>'));

                    });


                    $(document).on('click', '#ss-close-preview', function(){
                        $('#ss_output').html('');
                    });

                });

                $('#ss_logo').on('input', function(){
                    const url = $(this).val();

                    if(!url){
                        $('#ss-logo-preview').html('');
                        return;
                    }

                    $('#ss-logo-preview').html(
                        `<img src="${url}" 
                            onerror="this.style.display='none';"
                            style="max-height:60px;border:1px solid #ddd;padding:5px;border-radius:6px;">`
                    );
                });

                
            </script>
        </div>
        <?php
        }

        /* ======================================================
        * SAVE BRAND
        * ====================================================== */
        public static function save_brand() {

            // Verify nonce (AJAX-safe)
            if (
                ! isset($_POST['_nonce']) ||
                ! wp_verify_nonce(
                    sanitize_text_field(wp_unslash($_POST['_nonce'])),
                    self::NONCE
                )
            ) {
                wp_send_json_error(['message' => 'Invalid nonce'], 403);
            }

            // Prepare defaults
            $company = '';
            $logo    = '';

            // Validate + unslash + sanitize
            if (isset($_POST['company'])) {
                $company = sanitize_text_field(
                    wp_unslash($_POST['company'])
                );
            }

            if (isset($_POST['logo'])) {
                $logo = esc_url_raw(
                    wp_unslash($_POST['logo'])
                );
            }

            // Save option
            update_option(
                self::OPTION_BRAND,
                [
                    'company' => $company,
                    'logo'    => $logo,
                ]
            );

            wp_send_json_success();
        }

        /* ======================================================
        * PREVIEW
        * ====================================================== */
        public static function preview() {
            // check_ajax_referer( self::NONCE, '_nonce' );

            global $wpdb;

            // Verify nonce first
            if (
                ! isset($_POST['_nonce']) ||
                ! wp_verify_nonce(
                    sanitize_text_field(wp_unslash($_POST['_nonce'])),
                    self::NONCE
                )
            ) {
                wp_send_json_error(['message' => 'Invalid nonce'], 403);
            }

            // Default value
            $type = 'scans';

            // Validate + unslash + sanitize
            if (isset($_POST['type'])) {
                $type = sanitize_text_field(
                    wp_unslash($_POST['type'])
                );
            }

            $from = '';
            $to   = '';

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

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

            ob_start();
            echo '<button id="ss-close-preview" class="button" style="margin-bottom:10px;">Close Preview</button>';
            ?>

            <?php if ( $type === 'crawler' ) :
              $where = "1=1";

                if ($from) {
                    $where .= $wpdb->prepare(" AND DATE(hit_time) >= %s", $from);
                }
                if ($to) {
                    $where .= $wpdb->prepare(" AND DATE(hit_time) <= %s", $to);
                }
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

                $rows = $wpdb->get_results(
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    "SELECT * FROM {$wpdb->prefix}ss_crawler_logs WHERE $where ORDER BY id DESC LIMIT 300"
                );

                ?>

                <div class="ss-summary">
                    Total Records: <?php echo esc_html( count( $rows ) ); ?>
                </div>

                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Bot</th>
                            <th>URL</th>
                            <th>IP</th>
                            <th>Time</th>
                        </tr>
                    </thead>
                    <tbody>

                    <?php 
                    $counter=1;
                    foreach ( $rows as $r ) : ?>
                        <tr>
                            <td><?php echo esc_html( $counter++ ); ?></td>

                            <td><?php echo esc_html( $r->bot_name ); ?></td>

                            <td>
                                <a href="<?php echo esc_url( $r->url ); ?>" target="_blank" rel="noopener">
                                    <?php echo esc_html( $r->url ); ?>
                                </a>
                            </td>

                            <td><?php echo esc_html( $r->ip_address ); ?></td>

                            <td><?php echo esc_html( $r->hit_time ); ?></td>
                        </tr>
                    <?php endforeach; ?>

                    </tbody>
                </table>

            <?php else :

                
                $where = "1=1";

                if ($from) {
                    $where .= $wpdb->prepare(" AND DATE(finished_at) >= %s", $from);
                }
                if ($to) {
                    $where .= $wpdb->prepare(" AND DATE(finished_at) <= %s", $to);
                }
         
                $rows = $wpdb->get_results(
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    "SELECT * FROM {$wpdb->prefix}ss_scans WHERE $where ORDER BY id DESC LIMIT 300"
                );
                ?>

                <div class="ss-summary">
                    Total Pages: <?php echo esc_html( count( $rows ) ); ?>
                </div>

                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>URL</th>
                            <th>Status</th>
                            <th>Score</th>
                            <th>Recommendations</th>
                            <th>Finished</th>
                        </tr>
                    </thead>
                    <tbody>

                    <?php 
                        $counter = 1;
                        foreach ( $rows as $r ) :

                        // preg_match( '/Score:\s*(\d+\/\d+)/', $r->log ?? '', $m );
                        // $score = $m[1] ?? 'N/A';
                        preg_match_all('/Score:\s*(\d+\/\d+)/i', $r->log ?? '', $matches);

                        $score = !empty($matches[1])
                            ? trim(end($matches[1]))
                            : 'N/A';

                        // $pending = 0;
                        // if ( stripos( $r->log, 'add structured data' ) === false ) { $pending++; }
                        // if ( stripos( $r->log, 'add a q&a section' ) === false ) { $pending++; }
                        // if ( stripos( $r->log, 'link to glossary' ) === false ) { $pending++; }

                        $log = strtolower($r->log ?? '');

                        $hasGlossary =
                            strpos($log, 'fix applied: link to glossary terms') !== false ||
                            strpos($log, 'found: glossary linked') !== false;

                        $hasSchema =
                            strpos($log, 'fix applied: add structured data (schema.org)') !== false ||
                            strpos($log, 'found: schema added') !== false;

                        $hasQA =
                            strpos($log, 'fix applied: add faq section') !== false ||
                            strpos($log, 'found: q&a section found') !== false ||
                            strpos($log, 'found: content length ok') !== false;

                        $pending = 0;

                        if (!$hasSchema) {
                            $pending++;
                        }

                        if (!$hasQA) {
                            $pending++;
                        }

                        if (!$hasGlossary) {
                            $pending++;
                        }
                        ?>

                        <tr>
                            <td><?php echo esc_html( $counter++ ); ?></td>

                            <td>
                                <a href="<?php echo esc_url( $r->url ); ?>" target="_blank" rel="noopener">
                                    <?php echo esc_html( $r->url ); ?>
                                </a>
                            </td>

                            <td><?php echo esc_html( $r->status ); ?></td>

                            <td><?php echo esc_html( $score ); ?></td>

                            <td>
                                <?php
                                if ( $pending ) {
                                    echo esc_html( intval( $pending ) . ' pending' );
                                } else {
                                    echo '✅ Optimized';
                                }
                                ?>
                            </td>

                            <td><?php echo esc_html( $r->finished_at ); ?></td>
                        </tr>

                    <?php endforeach; ?>

                    </tbody>
                </table>

            <?php endif;

            wp_send_json_success(
                array(
                    'html' => ob_get_clean(),
                )
            );
        }


        /* ======================================================
        * EXPORT
        * ====================================================== */
        public static function export() {

            global $wpdb;

            /* ------------------------------------
            * NONCE VERIFICATION
            * ------------------------------------ */
            if (
                ! isset($_POST['_nonce']) ||
                ! wp_verify_nonce(
                    sanitize_text_field(wp_unslash($_POST['_nonce'])),
                    self::NONCE
                )
            ) {
                wp_die( esc_html__( 'Invalid request', 'searchshifter' ) );
            }

            /* ------------------------------------
            * INPUT (validated + unslashed)
            * ------------------------------------ */
            $type   = 'scans';
            $format = 'csv';

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

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

            /* ------------------------------------
            * DATABASE (justified direct query)
            * ------------------------------------ */
            $from = '';
            $to   = '';

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

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

            $where = "1=1";

            if ($from) {
                $where .= $wpdb->prepare(
                    " AND DATE(finished_at) >= %s",
                    $from
                );
            }

            if ($to) {
                $where .= $wpdb->prepare(
                    " AND DATE(finished_at) <= %s",
                    $to
                );
            }

            if ($type === 'crawler') {

                $where = "1=1";

                if ($from) {
                    $where .= $wpdb->prepare(
                        " AND DATE(hit_time) >= %s",
                        $from
                    );
                }

                if ($to) {
                    $where .= $wpdb->prepare(
                        " AND DATE(hit_time) <= %s",
                        $to
                    );
                }

                $rows = $wpdb->get_results(
                    "SELECT * FROM {$wpdb->prefix}ss_crawler_logs
                    WHERE $where
                    ORDER BY id DESC"
                );

            } else {

                $rows = $wpdb->get_results(
                    "SELECT * FROM {$wpdb->prefix}ss_scans
                    WHERE $where
                    ORDER BY id DESC"
                );
            }

            /* ------------------------------------
            * EXPORT
            * ------------------------------------ */
            if ($format === 'csv') {

                SS_Export::csv(
                    $type . '-report.csv',
                    $rows,
                    $type
                );

            } else {

                SS_Export::pdf(
                    $type . '-report.pdf',
                    $rows,
                    $type,
                    get_option(self::OPTION_BRAND)
                );
            }

            exit;
        }


        /* ======================================================
        * COMPETITORS
        * ====================================================== */
        public static function save_competitors() {

            /* ------------------------------------
            * NONCE VERIFICATION (AJAX)
            * ------------------------------------ */
            if (
                ! isset($_POST['_nonce']) ||
                ! wp_verify_nonce(
                    sanitize_text_field(wp_unslash($_POST['_nonce'])),
                    self::NONCE
                )
            ) {
                wp_send_json_error(['message' => 'Invalid nonce'], 403);
            }

            /* ------------------------------------
            * INPUT (validated + unslashed)
            * ------------------------------------ */
            $competitors_raw = '';

            if (isset($_POST['competitors'])) {
                $competitors_raw = sanitize_textarea_field(
                    wp_unslash($_POST['competitors'])
                );
            }

            /* ------------------------------------
            * PROCESS + SANITIZE
            * ------------------------------------ */
            $urls = array_filter(
                array_map(
                    function ($u) {
                        $u = trim($u);
                        return filter_var($u, FILTER_VALIDATE_URL)
                            ? esc_url_raw($u)
                            : false;
                    },
                    explode("\n", $competitors_raw)
                )
            );

            update_option(self::OPTION_COMPETITORS, $urls);

            wp_send_json_success();
        }


        public static function run_benchmark() {
            // check_ajax_referer(self::NONCE,'_nonce');

            $competitors = get_option(self::OPTION_COMPETITORS, []);
            array_unshift($competitors, home_url());

            $rows = [];

            foreach ($competitors as $url) {

                $res = wp_remote_get($url, ['timeout'=>10]);
                if (is_wp_error($res)) continue;

                $html = wp_remote_retrieve_body($res);

                $schema =
                    preg_match('/ld\+json/i',$html) +
                    preg_match('/Organization/i',$html) +
                    preg_match('/FAQPage/i',$html) +
                    preg_match('/HowTo/i',$html) +
                    preg_match('/Article/i',$html);

                $visibility =
                    preg_match('/<title>/i',$html) +
                    preg_match('/meta name="description"/i',$html) +
                    preg_match('/<h1/i',$html) +
                    preg_match('/canonical/i',$html) +
                    preg_match('/robots/i',$html);

                $own = untrailingslashit($url) === untrailingslashit(home_url());

                $rows[] = [
                    'domain' => $own
                        ? 'Your Site'
                        : wp_parse_url( $url, PHP_URL_HOST ),
                    'schema'     => $schema,
                    'visibility' => $visibility,
                    'total'      => $schema + $visibility,
                    'own'        => $own
                ];
            }

            ob_start(); ?>
            <table class="widefat striped">
                <thead>
                    <tr>
                        <th>Domain</th>
                        <th>Structured Data</th>
                        <th>AI Visibility</th>
                        <th>Overall Score</th>
                    </tr>
                </thead>
                <tbody>
                <?php 
                foreach ($rows as $r): ?>
                    <tr style="<?php echo $r['own'] ? 'background:#f0f7ff;font-weight:600;' : ''; ?>">
                        <td><?php echo esc_html($r['domain']); ?><?php if ($r['own']) echo ' (You)'; ?></td>
                        <td>
                            <?php echo intval($r['schema']); ?>/4
                            <br><small>Schema signals detected</small>
                        </td>

                        <td>
                            <?php echo intval($r['visibility']); ?>/5
                            <br><small>AI signals detected</small>
                        </td>
                        <td>
                            <strong>
                                <?php echo intval($r['total']); ?>/9
                            </strong>
                            <br><small>Optimization strength</small>
                        </td>

                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>

            <canvas id="ssChart" height="90"></canvas>
            <?php

            wp_send_json_success([
                'html' => ob_get_clean(),
                'rows' => $rows
            ]);
        }

    }



