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

class SS_Crawler_Monitor {

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

    public static function detect_crawler() {
        if (is_admin()) {
            return;
        }

        $ua = isset($_SERVER['HTTP_USER_AGENT'])
            ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT']))
            : '';

        if (!$ua) {
            return;
        }

        $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) {
                self::log_hit($bot_name, $ua);
                return;
            }
        }
    }

    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'        => isset($_SERVER['REQUEST_URI'])
                ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI']))
                : '',
            'ip_address' => isset($_SERVER['REMOTE_ADDR'])
                ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']))
                : '',
            'hit_time'   => current_time('mysql'),
        ];

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Safe insert into custom table using $wpdb->insert() with sanitized data and formats
        $wpdb->insert(
            $table,
            $data,
            ['%s', '%s', '%s', '%s', '%s']
        );
    }


}
