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

class SS_Admin_Visibility_Dashboard {

    public static function render_page() {
        global $wpdb;


        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $scans = $wpdb->get_results(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            "SELECT id, url, log, finished_at
            FROM {$wpdb->prefix}ss_scans
            WHERE status = 'done'
            ORDER BY finished_at DESC
            LIMIT 50"
        );



        // --- Extract numeric scores from logs like: "Score: 78/100"
        $scores = [];
        foreach ($scans as $scan) {
            if (preg_match('/Score[:\s]+(\d{1,3})/i', $scan->log, $m)) {
                $scores[] = (int) $m[1];
            }
        }

        $avg_score = !empty($scores) ? round(array_sum($scores) / count($scores), 1) : 0.0;

        // --- Overview flags (logs mentioning "issue" or "flag")
        $overview_flags = 0;
        foreach ($scans as $scan) {
            if (stripos($scan->log, 'issue') !== false || stripos($scan->log, 'flag') !== false) {
                $overview_flags++;
            }
        }

        $flag_percent = count($scans) ? round(($overview_flags / count($scans)) * 100, 1) : 0;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $crawler_reads = (int) $wpdb->get_var(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            "SELECT COUNT(*)
            FROM {$wpdb->prefix}ss_crawler_logs
            WHERE hit_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)"
        );

        // --- Trend analysis (based on last 14 days)
        $trend = 'Stable';
        $recent_scores = array_slice($scores, 0, 10);
        $older_scores = array_slice($scores, 10, 10);
        if (!empty($recent_scores) && !empty($older_scores)) {
            $recent_avg = array_sum($recent_scores) / count($recent_scores);
            $older_avg = array_sum($older_scores) / count($older_scores);
            $trend = $recent_avg > $older_avg ? 'Up' : ($recent_avg < $older_avg ? 'Down' : 'Stable');
        }

        ?>
        <div class="wrap ss-dashboard">
            <h1 class="wp-heading-inline">🤖 AI Visibility Dashboard</h1>
            <hr class="wp-header-end">

            <!-- Summary Cards -->
            <div class="ss-cards" style="display:flex;gap:15px;flex-wrap:wrap;margin-top:20px;">
                <div class="ss-card" style="flex:1;min-width:200px;padding:20px;background:#fff;border:2px solid #cbd5e1;border-radius:10px;text-align:center;">
                    <div style="font-size:28px;color:#f59e0b;">⭐</div>
                    <h2 style="margin:8px 0 0;font-size:18px;"><?php echo number_format($avg_score, 1); ?></h2>
                    <p style="margin:0;color:#555;">Average Score</p>
                </div>
                <div class="ss-card" style="flex:1;min-width:200px;padding:20px;background:#fff;border:2px solid #c084fc;border-radius:10px;text-align:center;">
                    <div style="font-size:28px;color:#a855f7;">🧠</div>
                    <h2 style="margin:8px 0 0;font-size:18px;">
                    <?php echo esc_html( intval( $flag_percent ) ); ?>%
                     </h2>

                    <p style="margin:0;color:#555;">Overview Flags (%)</p>
                </div>
                <div class="ss-card" style="flex:1;min-width:200px;padding:20px;background:#fff;border:2px solid #4ade80;border-radius:10px;text-align:center;">
                    <div style="font-size:28px;color:#22c55e;">🤖</div>
                    <h2 style="margin:8px 0 0;font-size:18px;">
                       <?php echo esc_html( intval( $crawler_reads ) ); ?>
                          </h2>

                    <p style="margin:0;color:#555;">Crawler Reads (7d)</p>
                </div>
                <div class="ss-card" style="flex:1;min-width:200px;padding:20px;background:#fff;border:2px solid #60a5fa;border-radius:10px;text-align:center;">
                    <div style="font-size:28px;color:#3b82f6;">📈</div>
                    <h2 style="margin:8px 0 0;font-size:18px;"><?php echo esc_html($trend); ?></h2>
                    <p style="margin:0;color:#555;">Trend</p>
                </div>
            </div>

            <!-- Table -->
            <h2 style="margin-top:35px;">📊 Recent Scans</h2>
            <table class="widefat fixed striped" style="margin-top:10px;">
                <thead>
                    <tr>
                        <th width="5%">ID</th>
                        <th>URL</th>
                        <th width="10%">Score</th>
                        <th width="50%">Log</th>
                        <th width="20%">Finished At</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($scans)): ?>
                        <?php foreach ($scans as $scan): 
                            preg_match('/Score[:\s]+(\d{1,3})/i', $scan->log, $m);
                            $score = isset($m[1]) ? (int) $m[1] : 0;
                            $color = ($score >= 80) ? '#16a34a' : (($score >= 60) ? '#eab308' : '#dc2626');
                        ?>
                            <tr>
                                <td><?php echo esc_html($scan->id); ?></td>
                                <td><a href="<?php echo esc_url($scan->url); ?>" target="_blank"><?php echo esc_html($scan->url); ?></a></td>
                                <td>
                               <strong style="color:<?php echo esc_attr( $color ); ?>">
                                  <?php echo esc_html( intval( $score ) ); ?>
                                     </strong>
                                      </td>

                                <td><?php echo esc_html(wp_trim_words($scan->log, 15)); ?></td>
                                <td><?php echo esc_html($scan->finished_at); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="5">No scans recorded yet.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php
    }
}
