<?php
/**
 * Country Check Script for HTML Files
 * This script checks if the visitor is from a blocked country
 * and either serves the HTML file or blocks access
 */

// Include the country blocking logic
require_once __DIR__ . '/block_country.php';

// Get the requested file path
$requestedFile = $_SERVER['REQUEST_URI'];
$filePath = __DIR__ . parse_url($requestedFile, PHP_URL_PATH);

// If it's a directory, default to index.html
if (is_dir($filePath)) {
    $filePath = rtrim($filePath, '/') . '/index.html';
}

// If file doesn't exist, let Apache handle 404
if (!file_exists($filePath) || !is_file($filePath)) {
    return false; // Let Apache handle it
}

// Get visitor IP
$visitorIP = getVisitorIP();

// Check if IP should be blocked
if ($visitorIP && $visitorIP !== '127.0.0.1') {
    // Use session caching
    if (session_status() === PHP_SESSION_NONE) {
        @session_start();
    }
    
    $cacheKey = 'country_block_cache';
    $cacheTime = 3600; // 1 hour cache
    $shouldBlock = false;
    
    // Check cache
    if (isset($_SESSION[$cacheKey]) && 
        isset($_SESSION[$cacheKey]['ip']) && 
        $_SESSION[$cacheKey]['ip'] === $visitorIP &&
        isset($_SESSION[$cacheKey]['time']) &&
        (time() - $_SESSION[$cacheKey]['time']) < $cacheTime) {
        $shouldBlock = $_SESSION[$cacheKey]['blocked'] ?? false;
    } else {
        $shouldBlock = @shouldBlockIP($visitorIP);
        $_SESSION[$cacheKey] = [
            'ip' => $visitorIP,
            'blocked' => $shouldBlock,
            'time' => time()
        ];
    }
    
    if ($shouldBlock === true) {
        // Block access
        error_log("Country Block: Blocked HTML access from China - IP: {$visitorIP}, File: {$requestedFile}");
        http_response_code(403);
        header('Content-Type: text/html; charset=utf-8');
        echo <<<HTML
<!DOCTYPE html>
<html lang="en">
<head><script>
// Block Google Analytics for blocked countries (China)
(function() {
    // Check if already blocked in session
    var countryCheck = sessionStorage.getItem('country_check');
    if (countryCheck === 'blocked') {
        // Block GA from loading
        window.gtag = function() { return; };
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push = function() { return; };
        // Remove GA scripts if they exist
        setTimeout(function() {
            var scripts = document.querySelectorAll('script[src*="googletagmanager.com"]');
            scripts.forEach(function(script) { script.remove(); });
        }, 0);
        return;
    }
    
    // Quick country check (only on first load, cached in sessionStorage)
    if (!countryCheck) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://ipapi.co/json/', true);
        xhr.timeout = 500;
        xhr.onload = function() {
            try {
                var data = JSON.parse(xhr.responseText);
                if (data && data.country_code === 'CN') {
                    sessionStorage.setItem('country_check', 'blocked');
                    // Remove GA scripts
                    var scripts = document.querySelectorAll('script[src*="googletagmanager.com"]');
                    scripts.forEach(function(script) { script.remove(); });
                    // Disable GA functions
                    window.gtag = function() { return; };
                    window.dataLayer = window.dataLayer || [];
                    window.dataLayer.push = function() { return; };
                    return;
                }
                sessionStorage.setItem('country_check', 'allowed');
            } catch(e) {
                sessionStorage.setItem('country_check', 'allowed');
            }
        };
        xhr.onerror = function() { sessionStorage.setItem('country_check', 'allowed'); };
        xhr.ontimeout = function() { sessionStorage.setItem('country_check', 'allowed'); };
        xhr.send();
    }
})();
</script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Access Denied</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            color: #333;
        }
        .container {
            background: white;
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            text-align: center;
            max-width: 500px;
        }
        h1 {
            color: #e74c3c;
            margin-bottom: 20px;
        }
        p {
            line-height: 1.6;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔒 Access Denied</h1>
        <p>We're sorry, but access to this website is restricted in your region.</p>
        <p>If you believe this is an error, please contact support.</p>
    </div>
</body>
</html>
HTML;
        exit;
    }
}

// If not blocked, serve the HTML file
if (file_exists($filePath) && is_file($filePath)) {
    $content = file_get_contents($filePath);
    
    // Inject country check script before Google Analytics to prevent tracking
    // This script blocks GA from loading if visitor is from China
    $gaBlockScript = <<<'SCRIPT'
<script>
// Block Google Analytics for blocked countries (China)
(function() {
    // Check if already blocked in session
    var countryCheck = sessionStorage.getItem('country_check');
    if (countryCheck === 'blocked') {
        // Block GA from loading
        window.gtag = function() { return; };
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push = function() { return; };
        // Remove GA scripts if they exist
        setTimeout(function() {
            var scripts = document.querySelectorAll('script[src*="googletagmanager.com"]');
            scripts.forEach(function(script) { script.remove(); });
        }, 0);
        return;
    }
    
    // Quick country check (only on first load, cached in sessionStorage)
    if (!countryCheck) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://ipapi.co/json/', true);
        xhr.timeout = 500;
        xhr.onload = function() {
            try {
                var data = JSON.parse(xhr.responseText);
                if (data && data.country_code === 'CN') {
                    sessionStorage.setItem('country_check', 'blocked');
                    // Remove GA scripts
                    var scripts = document.querySelectorAll('script[src*="googletagmanager.com"]');
                    scripts.forEach(function(script) { script.remove(); });
                    // Disable GA functions
                    window.gtag = function() { return; };
                    window.dataLayer = window.dataLayer || [];
                    window.dataLayer.push = function() { return; };
                    return;
                }
                sessionStorage.setItem('country_check', 'allowed');
            } catch(e) {
                sessionStorage.setItem('country_check', 'allowed');
            }
        };
        xhr.onerror = function() { sessionStorage.setItem('country_check', 'allowed'); };
        xhr.ontimeout = function() { sessionStorage.setItem('country_check', 'allowed'); };
        xhr.send();
    }
})();
</script>
SCRIPT;
    
    // Insert the blocking script right at the start of <head><script>
// Block Google Analytics for blocked countries (China)
(function() {
    // Check if already blocked in session
    var countryCheck = sessionStorage.getItem('country_check');
    if (countryCheck === 'blocked') {
        // Block GA from loading
        window.gtag = function() { return; };
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push = function() { return; };
        // Remove GA scripts if they exist
        setTimeout(function() {
            var scripts = document.querySelectorAll('script[src*="googletagmanager.com"]');
            scripts.forEach(function(script) { script.remove(); });
        }, 0);
        return;
    }
    
    // Quick country check (only on first load, cached in sessionStorage)
    if (!countryCheck) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://ipapi.co/json/', true);
        xhr.timeout = 500;
        xhr.onload = function() {
            try {
                var data = JSON.parse(xhr.responseText);
                if (data && data.country_code === 'CN') {
                    sessionStorage.setItem('country_check', 'blocked');
                    // Remove GA scripts
                    var scripts = document.querySelectorAll('script[src*="googletagmanager.com"]');
                    scripts.forEach(function(script) { script.remove(); });
                    // Disable GA functions
                    window.gtag = function() { return; };
                    window.dataLayer = window.dataLayer || [];
                    window.dataLayer.push = function() { return; };
                    return;
                }
                sessionStorage.setItem('country_check', 'allowed');
            } catch(e) {
                sessionStorage.setItem('country_check', 'allowed');
            }
        };
        xhr.onerror = function() { sessionStorage.setItem('country_check', 'allowed'); };
        xhr.ontimeout = function() { sessionStorage.setItem('country_check', 'allowed'); };
        xhr.send();
    }
})();
</script> tag
    if (strpos($content, '<head><script>
// Block Google Analytics for blocked countries (China)
(function() {
    // Check if already blocked in session
    var countryCheck = sessionStorage.getItem('country_check');
    if (countryCheck === 'blocked') {
        // Block GA from loading
        window.gtag = function() { return; };
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push = function() { return; };
        // Remove GA scripts if they exist
        setTimeout(function() {
            var scripts = document.querySelectorAll('script[src*="googletagmanager.com"]');
            scripts.forEach(function(script) { script.remove(); });
        }, 0);
        return;
    }
    
    // Quick country check (only on first load, cached in sessionStorage)
    if (!countryCheck) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://ipapi.co/json/', true);
        xhr.timeout = 500;
        xhr.onload = function() {
            try {
                var data = JSON.parse(xhr.responseText);
                if (data && data.country_code === 'CN') {
                    sessionStorage.setItem('country_check', 'blocked');
                    // Remove GA scripts
                    var scripts = document.querySelectorAll('script[src*="googletagmanager.com"]');
                    scripts.forEach(function(script) { script.remove(); });
                    // Disable GA functions
                    window.gtag = function() { return; };
                    window.dataLayer = window.dataLayer || [];
                    window.dataLayer.push = function() { return; };
                    return;
                }
                sessionStorage.setItem('country_check', 'allowed');
            } catch(e) {
                sessionStorage.setItem('country_check', 'allowed');
            }
        };
        xhr.onerror = function() { sessionStorage.setItem('country_check', 'allowed'); };
        xhr.ontimeout = function() { sessionStorage.setItem('country_check', 'allowed'); };
        xhr.send();
    }
})();
</script>') !== false) {
        $content = str_replace('<head><script>
// Block Google Analytics for blocked countries (China)
(function() {
    // Check if already blocked in session
    var countryCheck = sessionStorage.getItem('country_check');
    if (countryCheck === 'blocked') {
        // Block GA from loading
        window.gtag = function() { return; };
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push = function() { return; };
        // Remove GA scripts if they exist
        setTimeout(function() {
            var scripts = document.querySelectorAll('script[src*="googletagmanager.com"]');
            scripts.forEach(function(script) { script.remove(); });
        }, 0);
        return;
    }
    
    // Quick country check (only on first load, cached in sessionStorage)
    if (!countryCheck) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://ipapi.co/json/', true);
        xhr.timeout = 500;
        xhr.onload = function() {
            try {
                var data = JSON.parse(xhr.responseText);
                if (data && data.country_code === 'CN') {
                    sessionStorage.setItem('country_check', 'blocked');
                    // Remove GA scripts
                    var scripts = document.querySelectorAll('script[src*="googletagmanager.com"]');
                    scripts.forEach(function(script) { script.remove(); });
                    // Disable GA functions
                    window.gtag = function() { return; };
                    window.dataLayer = window.dataLayer || [];
                    window.dataLayer.push = function() { return; };
                    return;
                }
                sessionStorage.setItem('country_check', 'allowed');
            } catch(e) {
                sessionStorage.setItem('country_check', 'allowed');
            }
        };
        xhr.onerror = function() { sessionStorage.setItem('country_check', 'allowed'); };
        xhr.ontimeout = function() { sessionStorage.setItem('country_check', 'allowed'); };
        xhr.send();
    }
})();
</script>', '<head><script>
// Block Google Analytics for blocked countries (China)
(function() {
    // Check if already blocked in session
    var countryCheck = sessionStorage.getItem('country_check');
    if (countryCheck === 'blocked') {
        // Block GA from loading
        window.gtag = function() { return; };
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push = function() { return; };
        // Remove GA scripts if they exist
        setTimeout(function() {
            var scripts = document.querySelectorAll('script[src*="googletagmanager.com"]');
            scripts.forEach(function(script) { script.remove(); });
        }, 0);
        return;
    }
    
    // Quick country check (only on first load, cached in sessionStorage)
    if (!countryCheck) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://ipapi.co/json/', true);
        xhr.timeout = 500;
        xhr.onload = function() {
            try {
                var data = JSON.parse(xhr.responseText);
                if (data && data.country_code === 'CN') {
                    sessionStorage.setItem('country_check', 'blocked');
                    // Remove GA scripts
                    var scripts = document.querySelectorAll('script[src*="googletagmanager.com"]');
                    scripts.forEach(function(script) { script.remove(); });
                    // Disable GA functions
                    window.gtag = function() { return; };
                    window.dataLayer = window.dataLayer || [];
                    window.dataLayer.push = function() { return; };
                    return;
                }
                sessionStorage.setItem('country_check', 'allowed');
            } catch(e) {
                sessionStorage.setItem('country_check', 'allowed');
            }
        };
        xhr.onerror = function() { sessionStorage.setItem('country_check', 'allowed'); };
        xhr.ontimeout = function() { sessionStorage.setItem('country_check', 'allowed'); };
        xhr.send();
    }
})();
</script>' . $gaBlockScript, $content);
    } elseif (strpos($content, '<html') !== false) {
        // If no head tag, insert right after html tag
        $content = preg_replace('/(<html[^>]*>)/i', '$1' . $gaBlockScript, $content, 1);
    } else {
        $content = $gaBlockScript . $content;
    }
    
    // Determine content type
    $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
    if ($ext === 'html' || $ext === 'htm') {
        header('Content-Type: text/html; charset=utf-8');
    } else {
        header('Content-Type: ' . mime_content_type($filePath));
    }
    
    echo $content;
    exit;
}

return false; // Let Apache handle if we can't serve it

