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

class SS_Advanced_Reporting {

    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_menu', [__CLASS__, 'menu']);
        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']);
    }

    /* ======================================================
     * MENU
     * ====================================================== */
    public static function menu() {
        add_submenu_page(
            'searchshifter',
            'Advanced Reporting',
            'Advanced Reporting',
            'manage_options',
            'ss-advanced-reporting',
            [__CLASS__, 'page']
        );
    }

    /* ======================================================
     * ASSETS
     * ====================================================== */
 public static function assets($hook) {
    if ($hook !== 'searchshifter_page_ss-advanced-reporting') return;

    wp_enqueue_script(
        'chartjs',
        'https://cdn.jsdelivr.net/npm/chart.js',
        [],
        null,
        true
    );

    wp_register_style('ss-adv-report', false);
    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');

        ?>

        <div class="wrap">
            <h1>Advanced Reporting</h1>

            <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">

                <input type="url" id="ss_logo"
                       value="<?php echo esc_attr($brand['logo']); ?>"
                       placeholder="Logo URL">

                <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>Visibility Report</strong>
                    <p>Scans + recommendations summary</p>
                </div>
                <div class="ss-card" data-type="crawler">
                    <strong>Crawler Activity</strong>
                    <p>AI bot & crawler monitoring</p>
                </div>
            </div>

            <h3>Filters</h3>
            <input type="date" id="ss_from">
            <input type="date" id="ss_to">

            <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 id="ss_output" class="ss-report-table"></div>

            <hr>

            <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" 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>
/* 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 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: $('#_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 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="'+$('#_nonce').val()+'">');
        f.append('<input type="hidden" name="type" value="'+type+'">');
        f.append('<input type="hidden" name="format" value="'+fmt+'">');
        $('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: $('#_nonce').val(),
            company: $('#ss_company').val(),
            logo: $('#ss_logo').val()
        }).done(() => location.reload());
    });

    /* =========================
       SAVE COMPETITORS
    ========================= */
    $('#ss-save').on('click', function(){
        $.post(ajaxurl,{
            action: 'ss_save_competitors',
            _nonce: $('#_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: $('#_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>'));

    });

});
</script>

<?php
    }

    /* ======================================================
     * SAVE BRAND
     * ====================================================== */
    public static function save_brand() {
        check_ajax_referer(self::NONCE,'_nonce');

        update_option(self::OPTION_BRAND,[
            'company'=>sanitize_text_field($_POST['company']),
            'logo'=>esc_url_raw($_POST['logo'])
        ]);

        wp_send_json_success();
    }

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

        $type = sanitize_text_field($_POST['type'] ?? 'scans');

        ob_start();

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

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

            echo '<div class="ss-summary">Total Records: '.count($rows).'</div>';
            echo '<table class="widefat striped"><thead><tr>
                <th>ID</th><th>Bot</th><th>URL</th><th>IP</th><th>Time</th>
            </tr></thead><tbody>';

            foreach ($rows as $r) {
                echo "<tr>
                    <td>{$r->id}</td>
                    <td>{$r->bot_name}</td>
                    <td><a href='{$r->url}' target='_blank'>{$r->url}</a></td>
                    <td>{$r->ip_address}</td>
                    <td>{$r->hit_time}</td>
                </tr>";
            }

        } else {

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

            echo '<div class="ss-summary">Total Pages: '.count($rows).'</div>';
            echo '<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>';

            foreach ($rows as $r) {

                preg_match('/Score:\s*(\d+\/\d+)/', $r->log ?? '', $m);
                $score = $m[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++;

                echo "<tr>
                    <td>{$r->id}</td>
                    <td><a href='{$r->url}' target='_blank'>{$r->url}</a></td>
                    <td>{$r->status}</td>
                    <td>{$score}</td>
                    <td>".($pending ? "{$pending} pending" : "✅ Optimized")."</td>
                    <td>{$r->finished_at}</td>
                </tr>";
            }
        }

        echo '</tbody></table>';

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

    /* ======================================================
     * EXPORT
     * ====================================================== */
    public static function export() {
        check_admin_referer(self::NONCE,'_nonce');
        global $wpdb;

        $type = sanitize_text_field($_POST['type']);
        $rows = ($type === 'crawler')
            ? $wpdb->get_results("SELECT * FROM {$wpdb->prefix}ss_crawler_logs ORDER BY id DESC")
            : $wpdb->get_results("SELECT * FROM {$wpdb->prefix}ss_scans ORDER BY id DESC");

        if ($_POST['format'] === 'csv') {
            SS_Export::csv($type.'-report.csv', $rows, $type);
        } else {
            SS_Export::pdf($type.'-report.pdf', $rows, $type, get_option(self::OPTION_BRAND));
        }
    }

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

        $urls = array_filter(array_map(function($u){
            return filter_var(trim($u), FILTER_VALIDATE_URL);
        }, explode("\n", $_POST['competitors'] ?? '')));

        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' : esc_url($url),
            'schema'     => $schema,
            'visibility' => $visibility,
            'total'      => $schema + $visibility,
            'own'        => $own
        ];
    }

    ob_start(); ?>
    <table class="widefat striped">
        <thead>
            <tr>
                <th>Domain</th>
                <th>Schema</th>
                <th>Visibility</th>
                <th>Total</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 $r['schema']; ?></td>
                <td><?php echo $r['visibility']; ?></td>
                <td><strong><?php echo $r['total']; ?></strong></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

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

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

}

add_action('plugins_loaded',['SS_Advanced_Reporting','init']);
