<?php
declare(strict_types=1);

/**
 * ZG SIM Bot — Webhook handler
 * This file is called by Telegram webhook
 */

require_once __DIR__ . '/../../bootstrap.php';

/* ===== UPDATE QABUL QILISH ===== */
$update = json_decode(file_get_contents('php://input'), true);
if (!is_array($update)) {
    exit;
}

processUpdate($update);

function processUpdate(array $update): void
{
    global $db, $SERVICES, $availableLangs, $defaultLang;
    
    // Handle message
    if (isset($update['message'])) {
        $message = $update['message'];
        $from = $message['from'] ?? [];
        $chatId = $message['chat']['id'] ?? null;
        $text = trim($message['text'] ?? '');
        $messageId = $message['message_id'] ?? null;

        if (!$chatId || !$from) {
            return;
        }

        $user = ensureUser($db, $from);
        $id = $user['user_id'];

        // BLOKLANGANLIKNI TEKSHIRISH
        if (!empty($user['is_banned']) && (int)$id !== ADMIN_ID) {
            tg('sendMessage', [
                'chat_id' => $chatId,
                'text' => __('banned'),
                'parse_mode' => 'HTML',
            ]);
            return;
        }

        // /start YOKI /cancel BOSILSA BARCHA HOLATLARNI TOZALASH
        if ($text === '/start' || $text === '/cancel') {
            $db->updateUser($id, ['step' => null, 'temp_data' => null]);

            if (!checkSub($id)) {
                sendSubMessage($chatId);
                return;
            }

            tg('sendMessage', [
                'chat_id' => $chatId,
                'text' => getMainMenuText(),
                'parse_mode' => 'HTML',
                'reply_markup' => json_encode(getMainMenuKeyboard($id)),
            ]);
            return;
        }

        // /lang — TIL TANLASH
        if ($text === '/lang') {
            $keyboard = [
                'inline_keyboard' => [
                    [
                        ['text' => '🇺🇿 O\'zbekcha', 'callback_data' => 'setlang_uz'],
                        ['text' => '🇷🇺 Русский', 'callback_data' => 'setlang_ru'],
                    ],
                    [
                        ['text' => '🇬🇧 English', 'callback_data' => 'setlang_en'],
                    ],
                ],
            ];

            tg('sendMessage', [
                'chat_id' => $chatId,
                'text' => __('lang_title'),
                'parse_mode' => 'HTML',
                'reply_markup' => json_encode($keyboard),
            ]);
            return;
        }

        $userStep = $user['step'] ?? null;

        // 1. ADMIN OMMAVIY XABAR YUBORISH HOLATIDA BO'LSA
        if ((int)$id === ADMIN_ID && $userStep === 'waiting_broadcast') {
            $db->updateUser($id, ['step' => null, 'temp_data' => null]);

            tg('sendMessage', [
                'chat_id' => $chatId,
                'text' => __('admin_broadcast_progress'),
                'parse_mode' => 'HTML',
            ]);

            $sent = 0;
            $failed = 0;
            $users = $db->getAllUsers();
            foreach ($users as $u) {
                $res = tg('sendMessage', [
                    'chat_id' => $u['user_id'],
                    'text' => $text,
                    'parse_mode' => 'HTML',
                ]);
                if (!empty($res['ok'])) {
                    $sent++;
                } else {
                    $failed++;
                }
                usleep(50000); // 50ms delay
            }

            tg('sendMessage', [
                'chat_id' => $chatId,
                'text' => sprintf(__('admin_broadcast_done'), ['sent' => $sent, 'failed' => $failed]),
                'parse_mode' => 'HTML',
                'reply_markup' => json_encode(getAdminPanelKeyboard($db->countRequestsByStatus('new'))),
            ]);
            return;
        }

        // 2. ADMIN JAVOB YUBORISH HOLATIDA
        if ((int)$id === ADMIN_ID && $userStep === 'waiting_reply') {
            $temp = json_decode($user['temp_data'] ?? '{}', true);
            $targetUserId = $temp['target_user_id'] ?? null;
            $reqId = $temp['req_id'] ?? null;

            $db->updateUser($id, ['step' => null, 'temp_data' => null]);

            if ($targetUserId) {
                tg('sendMessage', [
                    'chat_id' => $targetUserId,
                    'text' => __('admin_reply_prefix') . "\n\n" . $text,
                    'parse_mode' => 'HTML',
                ]);
            }

            if ($reqId) {
                $request = $db->getRequest($reqId);
                if ($request) {
                    $cbMessageText = $request['service'] . ' - ' . $request['note'];
                    tg('editMessageText', [
                        'chat_id' => $chatId,
                        'message_id' => $messageId,
                        'text' => $cbMessageText . __('admin_status_replied'),
                        'parse_mode' => 'HTML',
                    ]);
                }
            }

            tg('sendMessage', [
                'chat_id' => $chatId,
                'text' => __('admin_reply_sent'),
                'parse_mode' => 'HTML',
                'reply_markup' => json_encode(getAdminPanelKeyboard($db->countRequestsByStatus('new'))),
            ]);
            return;
        }

        // 3. FOYDALANUVCHI XABAR YUBORAYOTGANDA (xizmat uchun matn)
        if ($userStep === 'waiting_note') {
            $serviceKey = $user['temp_data'] ?? '';
            if (isset($SERVICES[$serviceKey])) {
                $db->updateUser($id, ['step' => null, 'temp_data' => null, 'last_request_ts' => time()]);

                $reqId = 'req_' . $id . '_' . time();
                $db->createRequest([
                    'request_id' => $reqId,
                    'user_id' => $id,
                    'first_name' => $user['first_name'] ?? '',
                    'last_name' => $user['last_name'] ?? '',
                    'username' => $user['username'] ?? null,
                    'service' => $serviceKey,
                    'note' => $text,
                    'status' => 'new',
                    'requested_at' => date('Y-m-d H:i:s'),
                ]);

                // Adminga yuborish
                $adminText = sprintf(__('admin_new_request'), [
                    'id' => $reqId,
                    'user' => $user['first_name'] ?? '',
                    'username' => isset($user['username']) ? '@' . $user['username'] : '—',
                    'service' => $serviceKey,
                    'note' => $text,
                ]);

                tg('sendMessage', [
                    'chat_id' => ADMIN_ID,
                    'text' => $adminText,
                    'parse_mode' => 'HTML',
                    'reply_markup' => json_encode(getAdminRequestKeyboard($reqId, $id)),
                ]);

                // Foydalanuvchiga tasdiq
                tg('sendMessage', [
                    'chat_id' => $chatId,
                    'text' => __('request_sent'),
                    'parse_mode' => 'HTML',
                    'reply_markup' => json_encode(getMainMenuKeyboard($id)),
                ]);
            }
            return;
        }

        // Oddiy matn - menyuni qayta ko'rsatish
        tg('sendMessage', [
            'chat_id' => $chatId,
            'text' => getMainMenuText(),
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode(getMainMenuKeyboard($id)),
        ]);
        return;
    }

    // Handle callback query
    if (isset($update['callback_query'])) {
        $cb = $update['callback_query'];
        $callbackId = $cb['id'] ?? '';
        $from = $cb['from'] ?? [];
        $chatId = $cb['message']['chat']['id'] ?? null;
        $messageId = $cb['message']['message_id'] ?? null;
        $data = $cb['data'] ?? '';

        if (!$chatId || !$from || !$callbackId) {
            return;
        }

        $user = ensureUser($db, $from);
        $id = $user['user_id'];

        if (!empty($user['is_banned']) && (int)$id !== ADMIN_ID) {
            tg('answerCallbackQuery', ['callback_query_id' => $callbackId, 'text' => __('banned'), 'show_alert' => true]);
            return;
        }

        // 1. OBUNA TEKSHIRISH
        if ($data === 'check_sub') {
            if (checkSub($id)) {
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId, 'text' => __('sub_ok'), 'show_alert' => true]);
                tg('editMessageText', [
                    'chat_id' => $chatId,
                    'message_id' => $messageId,
                    'text' => getMainMenuText(),
                    'parse_mode' => 'HTML',
                    'reply_markup' => json_encode(getMainMenuKeyboard($id)),
                ]);
            } else {
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId, 'text' => __('sub_not_yet'), 'show_alert' => true]);
            }
            return;
        }

        // 2. TIL O'ZGARTIRISH
        if (str_starts_with($data, 'setlang_')) {
            $lang = substr($data, 8);
            if (in_array($lang, $availableLangs, true)) {
                setUserLang($db, $id, $lang);
                setLang($lang);
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId, 'text' => __('lang_changed')]);
                tg('editMessageText', [
                    'chat_id' => $chatId,
                    'message_id' => $messageId,
                    'text' => getMainMenuText(),
                    'parse_mode' => 'HTML',
                    'reply_markup' => json_encode(getMainMenuKeyboard($id)),
                ]);
            }
            return;
        }

        // 3. ADMIN PANEL
        if ((int)$id === ADMIN_ID) {
            if ($data === 'admin_panel') {
                $newCount = $db->countRequestsByStatus('new');
                tg('editMessageText', [
                    'chat_id' => $chatId,
                    'message_id' => $messageId,
                    'text' => __('admin_panel_title'),
                    'parse_mode' => 'HTML',
                    'reply_markup' => json_encode(getAdminPanelKeyboard($newCount)),
                ]);
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId]);
                return;
            }

            if ($data === 'admin_stat') {
                $totalUsers = $db->countUsers();
                $todayUsers = $db->countUsersToday();
                $banned = $db->countBanned();
                $totalReq = $db->countRequests();
                $newReq = $db->countRequestsByStatus('new');
                $doneReq = $db->countRequestsByStatus('done');
                $rejectReq = $db->countRequestsByStatus('rejected');

                $statText = sprintf(__('admin_stat_text'), [
                    'total_users' => $totalUsers,
                    'today_users' => $todayUsers,
                    'banned' => $banned,
                    'total_req' => $totalReq,
                    'new_req' => $newReq,
                    'done_req' => $doneReq,
                    'reject_req' => $rejectReq,
                ]);

                tg('editMessageText', [
                    'chat_id' => $chatId,
                    'message_id' => $messageId,
                    'text' => $statText,
                    'parse_mode' => 'HTML',
                    'reply_markup' => json_encode([
                        'inline_keyboard' => [[['text' => __('btn_back_main'), 'callback_data' => 'admin_panel']]],
                    ]),
                ]);
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId]);
                return;
            }

            if ($data === 'admin_broadcast') {
                $db->updateUser($id, ['step' => 'waiting_broadcast', 'temp_data' => null]);
                tg('editMessageText', [
                    'chat_id' => $chatId,
                    'message_id' => $messageId,
                    'text' => __('admin_broadcast_prompt'),
                    'parse_mode' => 'HTML',
                    'reply_markup' => json_encode([
                        'inline_keyboard' => [[['text' => __('btn_cancel'), 'callback_data' => 'admin_panel']]],
                    ]),
                ]);
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId]);
                return;
            }

            if ($data === 'admin_pending') {
                $requests = $db->getRequestsByStatus('new');
                if (empty($requests)) {
                    tg('answerCallbackQuery', ['callback_query_id' => $callbackId, 'text' => __('admin_no_pending'), 'show_alert' => true]);
                    return;
                }
                $req = $requests[0];
                $reqText = sprintf(__('admin_request_detail'), [
                    'id' => $req['request_id'],
                    'user' => $req['first_name'] ?? '',
                    'username' => isset($req['username']) ? '@' . $req['username'] : '—',
                    'service' => $req['service'],
                    'note' => $req['note'],
                    'time' => $req['requested_at'],
                ]);
                tg('editMessageText', [
                    'chat_id' => $chatId,
                    'message_id' => $messageId,
                    'text' => $reqText,
                    'parse_mode' => 'HTML',
                    'reply_markup' => json_encode(getAdminRequestKeyboard($req['request_id'], $req['user_id'])),
                ]);
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId]);
                return;
            }

            if ($data === 'admin_backup') {
                $csvPath = __DIR__ . '/../../users_backup_' . date('Ymd_His') . '.csv';
                $db->exportUsersCsv($csvPath);
                tg('sendDocument', [
                    'chat_id' => $chatId,
                    'document' => new CURLFile($csvPath, 'text/csv', basename($csvPath)),
                    'caption' => __('admin_backup_caption'),
                ]);
                @unlink($csvPath);
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId, 'text' => __('admin_backup_done')]);
                return;
            }

            if (str_starts_with($data, 'reply_')) {
                $reqId = substr($data, 6);
                $request = $db->getRequest($reqId);
                if ($request) {
                    $db->updateUser($id, [
                        'step' => 'waiting_reply',
                        'temp_data' => json_encode(['target_user_id' => $request['user_id'], 'req_id' => $reqId]),
                    ]);
                    tg('editMessageText', [
                        'chat_id' => $chatId,
                        'message_id' => $messageId,
                        'text' => sprintf(__('admin_reply_prompt'), ['user' => $request['first_name'] ?? '', 'id' => $reqId]),
                        'parse_mode' => 'HTML',
                        'reply_markup' => json_encode([
                            'inline_keyboard' => [[['text' => __('btn_cancel'), 'callback_data' => 'admin_panel']]],
                        ]),
                    ]);
                }
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId]);
                return;
            }

            if (str_starts_with($data, 'done_') || str_starts_with($data, 'reject_')) {
                $isDone = str_starts_with($data, 'done_');
                $reqId = substr($data, $isDone ? 5 : 7);
                $newStatus = $isDone ? 'done' : 'rejected';

                $request = $db->getRequest($reqId);
                if ($request) {
                    $db->updateRequestStatus($reqId, $newStatus);

                    $targetUser = $request['user_id'];
                    $serviceName = $request['service'];

                    if ($isDone) {
                        $userNotice = __('user_notice_done', ['service' => $serviceName, 'id' => $reqId]);
                        $adminBadge = __('admin_status_done');
                    } else {
                        $userNotice = __('user_notice_reject', ['service' => $serviceName, 'id' => $reqId]);
                        $adminBadge = __('admin_status_reject');
                    }

                    tg('sendMessage', [
                        'chat_id' => $targetUser,
                        'text' => $userNotice,
                        'parse_mode' => 'HTML',
                    ]);

                    $cbMessageText = $cb['message']['text'] ?? '';
                    tg('editMessageText', [
                        'chat_id' => $chatId,
                        'message_id' => $messageId,
                        'text' => $cbMessageText . $adminBadge,
                        'parse_mode' => 'HTML',
                    ]);
                }
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId, 'text' => 'Holat yangilandi!']);
                return;
            }

            if (str_starts_with($data, 'ban_') || str_starts_with($data, 'unban_')) {
                $isBan = str_starts_with($data, 'ban_');
                $targetId = substr($data, $isBan ? 4 : 6);
                $db->updateUser($targetId, ['is_banned' => $isBan ? 1 : 0]);
                $actionText = $isBan ? __('admin_banned') : __('admin_unbanned');
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId, 'text' => $actionText, 'show_alert' => true]);

                $requests = $db->getRequestsByStatus('new');
                if (!empty($requests)) {
                    $req = $requests[0];
                    tg('editMessageText', [
                        'chat_id' => $chatId,
                        'message_id' => $messageId,
                        'text' => sprintf(__('admin_request_detail'), [
                            'id' => $req['request_id'],
                            'user' => $req['first_name'] ?? '',
                            'username' => isset($req['username']) ? '@' . $req['username'] : '—',
                            'service' => $req['service'],
                            'note' => $req['note'],
                            'time' => $req['requested_at'],
                        ]),
                        'parse_mode' => 'HTML',
                        'reply_markup' => json_encode(getAdminRequestKeyboard($req['request_id'], $req['user_id'], $isBan)),
                    ]);
                }
                return;
            }

            if ($data === 'back_to_main') {
                tg('editMessageText', [
                    'chat_id' => $chatId,
                    'message_id' => $messageId,
                    'text' => getMainMenuText(),
                    'parse_mode' => 'HTML',
                    'reply_markup' => json_encode(getMainMenuKeyboard($id)),
                ]);
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId]);
                return;
            }
        }

        // 4. XIZMAT TANLASH (foydalanuvchi)
        if (isset($SERVICES[$data])) {
            $lastReq = (int)($user['last_request_ts'] ?? 0);
            $now = time();
            if (($now - $lastReq) < COOLDOWN_SECONDS && (int)$id !== ADMIN_ID) {
                $wait = COOLDOWN_SECONDS - ($now - $lastReq);
                tg('answerCallbackQuery', [
                    'callback_query_id' => $callbackId,
                    'text' => __('cooldown', ['wait' => $wait]),
                    'show_alert' => true,
                ]);
                return;
            }

            $db->updateUser($id, [
                'step' => 'waiting_note',
                'temp_data' => $data,
            ]);

            $srvTitle = __('service_' . $data);
            $priceText = __($SERVICES[$data]['price_key']);
            $promptText = __($SERVICES[$data]['prompt_key']);

            tg('editMessageText', [
                'chat_id' => $chatId,
                'message_id' => $messageId,
                'text' => $priceText . "\n\n" . $promptText,
                'parse_mode' => 'HTML',
                'reply_markup' => json_encode([
                    'inline_keyboard' => [[['text' => __('btn_cancel'), 'callback_data' => 'back_to_main']]],
                ]),
            ]);

            tg('answerCallbackQuery', ['callback_query_id' => $callbackId]);
            return;
        }

        if ($data === 'price_list') {
            $text = __('price_list_text');
            tg('editMessageText', [
                'chat_id' => $chatId,
                'message_id' => $messageId,
                'text' => $text,
                'parse_mode' => 'HTML',
                'reply_markup' => json_encode([
                    'inline_keyboard' => [[['text' => __('btn_back_main'), 'callback_data' => 'back_to_main']]],
                ]),
            ]);
            tg('answerCallbackQuery', ['callback_query_id' => $callbackId]);
            return;
        }

        if ($data === 'back_to_main') {
            if (!checkSub($id)) {
                sendSubMessage($chatId);
                tg('answerCallbackQuery', ['callback_query_id' => $callbackId]);
                return;
            }
            tg('editMessageText', [
                'chat_id' => $chatId,
                'message_id' => $messageId,
                'text' => getMainMenuText(),
                'parse_mode' => 'HTML',
                'reply_markup' => json_encode(getMainMenuKeyboard($id)),
            ]);
            tg('answerCallbackQuery', ['callback_query_id' => $callbackId]);
            return;
        }

        tg('answerCallbackQuery', ['callback_query_id' => $callbackId, 'text' => __('error_unknown')]);
        return;
    }
}