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

class SS_Crawler_Monitor {

    public static function init() {
        error_log('[CrawlerMonitor] ✅ init() loaded');
        add_action('template_redirect', [__CLASS__, 'detect_crawler']);
    }

    public static function detect_crawler() {
        if (is_admin()) {
            error_log('[CrawlerMonitor] Skipped (admin area)');
            return;
        }

        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
        if (!$ua) {
            error_log('[CrawlerMonitor] No User-Agent header');
            return;
        }

        error_log('[CrawlerMonitor] Checking UA: ' . $ua);

        $bots = [
            'GPTBot'          => 'GPTBot',
            'Google-Extended' => 'Google-Extended',
            'PerplexityBot'   => 'PerplexityBot',
            'CCBot'           => 'CCBot',
            'Claude-Web'      => 'Claude-Web',
            'FacebookBot'     => 'Facebook AI',
        ];

        foreach ($bots as $key => $bot_name) {
            if (stripos($ua, $key) !== false) {
                error_log("[CrawlerMonitor] Bot detected → $bot_name");
                self::log_hit($bot_name, $ua);
                return;
            }
        }

        error_log('[CrawlerMonitor] No match found.');
    }

    private static function log_hit($bot_name, $ua) {
        global $wpdb;
        $table = $wpdb->prefix . 'ss_crawler_logs';

        $data = [
            'bot_name'    => sanitize_text_field($bot_name),
            'user_agent'  => sanitize_textarea_field($ua),
            'url'         => esc_url_raw($_SERVER['REQUEST_URI'] ?? ''),
            'ip_address'  => sanitize_text_field($_SERVER['REMOTE_ADDR'] ?? ''),
            'hit_time'    => current_time('mysql'),
        ];

        $result = $wpdb->insert($table, $data);

        if ($result === false) {
            error_log('[CrawlerMonitor] ❌ Insert failed: ' . $wpdb->last_error);
        } else {
            error_log('[CrawlerMonitor] ✅ Insert success for ' . $bot_name);
        }
    }
}
