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

/**
 * Admin: Crawler Monitor Page
 * Lists logged AI crawler visits + export options (Pro+ only)
 */
class SS_Admin_Crawler_Monitor {

    public static function render_page() {

        // ✅ Use consistent plan-based gating
        $license = class_exists('SS_Licensing') ? SS_Licensing::get_cached_status() : [];
        $plan = strtolower($license['plan'] ?? 'free');

        if (!in_array($plan, ['pro', 'authority', 'elite'], true)) {
            echo '<div class="wrap" style="margin-top:30px;">
                    <h1 style="display:flex;align-items:center;gap:8px;">
                        <span class="dashicons dashicons-lock" style="color:#dba617;"></span> 
                        Crawler Monitor
                    </h1>
                    <div style="background:#fff8e5;border-left:4px solid #dba617;padding:12px 15px;margin-top:10px;border-radius:4px;">
                        <p>This feature requires the <strong>Pro</strong> or <strong>Authority</strong> edition.</p>
                        <p><a href="https://searchshifter.ai/pricing" target="_blank" 
                            style="color:#2271b1;text-decoration:none;">Upgrade to unlock Crawler Monitor</a></p>
                    </div>
                  </div>';
            return;
        }

        // ✅ Pro mode active
        global $wpdb;
        $table = $wpdb->prefix . 'ss_crawler_logs';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $logs = $wpdb->get_results(
            $wpdb->prepare(
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                "SELECT * FROM {$wpdb->prefix}ss_crawler_logs
                ORDER BY hit_time DESC
                LIMIT %d",
                200
            )
        );

        echo '<div class="wrap">';
        echo '<h1 style="display:flex;align-items:center;gap:8px;">
                <span class="dashicons dashicons-admin-site-alt3" style="color:#2271b1;"></span>
                AI Crawler Monitor
              </h1>';
        echo '<p>Below are detected AI crawlers that have visited your site (e.g., GPTBot, Google-Extended, PerplexityBot, CCBot).</p>';

        // ✅ Include Export Options (CSV / PDF)
        require_once SEARCHSHIFTER_PLUGIN_DIR . 'includes/class-ss-export.php';
        SS_Export::auto('Crawler Monitor', $logs);

        // ✅ Handle Export Actions (FIXED)
      



        // ✅ Display Crawler Table
        if ($logs) {
            echo '<table class="widefat fixed striped" style="margin-top:15px;">';
            echo '<thead><tr>
                    <th width="10%">Bot Name</th>
                    <th width="30%">Visited URL</th>
                    <th width="10%">IP Address</th>
                    <th>User Agent</th>
                    <th width="15%">Detected At</th>
                  </tr></thead><tbody>';

            foreach ($logs as $log) {
                echo '<tr>';
                echo '<td>' . esc_html($log->bot_name) . '</td>';
                echo '<td><a href="' . esc_url($log->url) . '" target="_blank">' . esc_html($log->url) . '</a></td>';
                echo '<td>' . esc_html($log->ip_address) . '</td>';
                echo '<td style="font-size:11px;color:#555;">' . esc_html($log->user_agent) . '</td>';
                echo '<td>' . esc_html($log->hit_time) . '</td>';
                echo '</tr>';
            }

            echo '</tbody></table>';
        } else {
            echo '<p style="margin-top:10px;">No crawler activity detected yet.</p>';
        }

        echo '</div>';
    }
}
add_action('admin_init', function () {

    if (
        isset($_POST['_wpnonce']) &&
        wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['_wpnonce'])),
            'ss_export_crawler-monitor'
        )
    ) {

        global $wpdb;

        $logs = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}ss_crawler_logs
                 ORDER BY hit_time DESC
                 LIMIT %d",
                200
            )
        );

        require_once SEARCHSHIFTER_PLUGIN_DIR . 'includes/class-ss-export.php';

        if (isset($_POST['ss_export_csv_crawler-monitor'])) {
            SS_Export::csv('Crawler-Monitor-Report.csv', $logs);
            exit;
        }

        if (isset($_POST['ss_export_pdf_crawler-monitor'])) {
            SS_Export::pdf('Crawler-Monitor-Report.pdf', $logs);
            exit;
        }
    }
});
