<?php
/**
 * Plugin Name: WhoZex - Bot_Router — Early Cloaking
 * Description: Cache ve tema yüklenmeden ÖNCE bot tespiti yapıp özel sürümü sunar (en güvenilir yöntem). WhoZex - Bot_Router tarafından otomatik oluşturulur — manuel düzenlemeyin.
 * Version: 2.1.0
 */

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

(function () {
  try {
    if (!function_exists('get_option')) { return; }

    $s = get_option('botr_settings');
    if (!is_array($s) || empty($s['enabled'])) { return; }
    if (isset($s['early_serve']) && !$s['early_serve']) { return; }

    $target = isset($s['target_file']) ? trim((string) $s['target_file']) : '';

    $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    if ($ua === '') { return; }

    $map = array(
        'google'     => 'Googlebot|AdsBot-Google|Google-InspectionTool|GoogleOther|Storebot-Google|APIs-Google|Mediapartners-Google',
        'bing'       => 'bingbot|BingPreview|msnbot|adidxbot',
        'yandex'     => 'YandexBot|YandexImages|YandexMobileBot',
        'duckduckgo' => 'DuckDuckBot',
        'pagespeed'  => 'Chrome-Lighthouse|PageSpeed',
    );
    $bots = (isset($s['bots']) && is_array($s['bots'])) ? $s['bots'] : array();
    $bot_key = '';
    foreach ($map as $k => $re) {
        if (!empty($bots[$k]) && preg_match('#(' . $re . ')#i', $ua)) { $bot_key = $k; break; }
    }
    if ($bot_key === '') { return; }

    $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
    if (preg_match('#^/(wp-admin|wp-login\.php|wp-json|xmlrpc\.php|wp-cron\.php|wp-content|wp-includes)#i', $uri)) { return; }
    if (preg_match('#\.(css|js|jpg|jpeg|png|gif|webp|svg|ico|woff2?|ttf|eot|map|pdf|zip|mp4|mp3|xml|txt)(\?|$)#i', $uri)) { return; }
    if (php_sapi_name() === 'cli') { return; }
    if (defined('DOING_CRON') && DOING_CRON) { return; }

    $scope = isset($s['scope']) ? $s['scope'] : 'home';
    $path  = parse_url($uri, PHP_URL_PATH);
    if (!is_string($path)) { $path = '/'; }
    if ($scope === 'regex') {
        $rx = isset($s['scope_regex']) ? trim((string) $s['scope_regex']) : '';
        if ($rx === '') { return; }
        $delim = (strpos($rx, '#') !== false) ? '~' : '#';
        if (!@preg_match($delim . $rx . $delim, $uri)) { return; }
    } elseif ($scope !== 'all') {
        $p = rtrim($path, '/');
        if ($p !== '' && $p !== '/index.php') { return; }
    }

    $detector_file = '/var/www/html/wp-content/plugins/bot-router-v2/includes/class-detector.php';
    $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
    if (file_exists($detector_file)) {
        require_once $detector_file;
        if (class_exists('BOTR_Detector')) {
            $ip = BOTR_Detector::get_client_ip();
            if (!empty($s['verify_dns'])) {
                $res = BOTR_Detector::detect($ua, $ip, true);
                if (!$res || (isset($res['verified']) && $res['verified'] === false)) { return; }
            }
        }
    }

    foreach (array('DONOTCACHEPAGE','DONOTCACHEOBJECT','DONOTCACHEDB','DONOTMINIFY','DONOTCDN') as $c) {
        if (!defined($c)) { define($c, true); }
    }
    if (!headers_sent()) {
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, private', true);
        header('Pragma: no-cache', true);
        header('Expires: 0', true);
        header('Vary: User-Agent', true);
        header('X-Bot-Router: ' . preg_replace('/[^a-z0-9_-]/i', '', $bot_key), true);
    }

    if (!empty($s['log_enabled'])) {
        $logger_file = '/var/www/html/wp-content/plugins/bot-router-v2/includes/class-logger.php';
        if (file_exists($logger_file)) {
            require_once $logger_file;
            if (class_exists('BOTR_Logger')) { BOTR_Logger::log($ua, $ip, $bot_key, 'served'); }
        }
    }

    if ($target === '') {
        $example_file = '/var/www/html/wp-content/plugins/bot-router-v2/includes/class-example-theme.php';
        if (file_exists($example_file)) {
            require_once $example_file;
            if (class_exists('BOTR_Example')) {
                if (!headers_sent()) { header('Content-Type: text/html; charset=UTF-8'); }
                echo BOTR_Example::html(get_option('botr_example_brand', 'whozex'));
                exit;
            }
        }
        return;
    }

    if (preg_match('#^https?://#i', $target)) {
        $ckey = 'botr_remote_' . md5($target);
        $html = get_transient($ckey);
        if ($html === false || $html === null || $html === '') {
            $html = null;
            if (function_exists('wp_remote_get')) {
                $r = wp_remote_get($target, array('timeout' => 8, 'redirection' => 3, 'sslverify' => true));
                if (!is_wp_error($r) && (int) wp_remote_retrieve_response_code($r) === 200) {
                    $html = wp_remote_retrieve_body($r);
                }
            }
            if (($html === null || $html === '') && ini_get('allow_url_fopen')) {
                $ctx = stream_context_create(array('http' => array('timeout' => 8, 'follow_location' => 1)));
                $tmp = @file_get_contents($target, false, $ctx);
                if ($tmp !== false && $tmp !== '') { $html = $tmp; }
            }
            if ($html === null || $html === '') { return; }
            set_transient($ckey, $html, 300);
        }
        // UTF-8 normalize — cache'ten gelse de taze gelse de her zaman (idempotent)
        if (is_string($html) && $html !== '' && function_exists('mb_check_encoding') && !mb_check_encoding($html, 'UTF-8')) {
            $__enc = '';
            if (preg_match('#<meta[^>]+charset=["\']?\s*([\w-]+)#i', $html, $__m)) { if (strtoupper(str_replace('-','',$__m[1])) !== 'UTF8') { $__enc = $__m[1]; } }
            if ($__enc === '') { $__enc = 'Windows-1254'; }
            if (function_exists('mb_convert_encoding')) { $html = mb_convert_encoding($html, 'UTF-8', $__enc); }
            $html = preg_replace('#(<meta[^>]+charset=["\']?\s*)[\w-]+#i', '${1}UTF-8', $html);
        }
        if (!headers_sent()) { header('Content-Type: text/html; charset=UTF-8'); }
        echo $html;
        exit;
    }

    if (!file_exists($target)) { return; }
    include $target;
    exit;
  } catch (\Throwable $e) {
    // Erken-sunum sırasında herhangi bir hata olursa siteyi ASLA çökertme;
    // sessizce normal WordPress render'ına düş.
    return;
  }
})();