<?php

/* ===============================
   KYC VERIFICATION HELPERS
================================ */

function getPendingKycRequestByUserId(PDO $pdo, int $userId): ?array {
    $stmt = $pdo->prepare("
        SELECT *
        FROM kyc_verification_requests
        WHERE user_id = :user_id
          AND status IN ('pending', 'submitted', 'rejected')
        ORDER BY id DESC
        LIMIT 20
    ");
    $stmt->execute([':user_id' => $userId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

    foreach ($rows as $row) {
        if (requestHasPendingKycItems($pdo, (int)$row['id'])) {
            return $row;
        }
    }

    return null;
}

function requestHasPendingKycItems(PDO $pdo, int $requestId): bool {
    try {
        $stmt = $pdo->prepare("
            SELECT COUNT(*) AS total
            FROM kyc_verification_request_items
            WHERE request_id = :request_id
              AND status IN ('pending','failed','reupload_required')
        ");
        $stmt->execute([':request_id' => $requestId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return ((int)($row['total'] ?? 0)) > 0;
    } catch (Throwable $e) {
        return false;
    }
}

function formatKycRequestedItems(PDO $pdo, array $request): string {
    $map = [
        'selfie_verification' => 'Selfie Verification',
        'video_verification'  => 'Video Verification',
        'passport_image'      => 'Passport Image',
        'id_card_front'       => 'ID Card Front',
        'id_card_back'        => 'ID Card Back',
        'proof_of_address'    => 'Proof of Address',
        'source_of_funds'     => 'Source of Funds Document',
        'custom_document'     => 'Additional Verification Document'
    ];

    $lines = [];

    try {
        $stmt = $pdo->prepare("
            SELECT item_key, item_label, status
            FROM kyc_verification_request_items
            WHERE request_id = :request_id
              AND status IN ('pending','failed','reupload_required')
            ORDER BY id ASC
        ");
        $stmt->execute([':request_id' => (int)$request['id']]);
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        foreach ($items as $item) {
            $label = trim((string)($item['item_label'] ?? ''));
            if ($label === '') {
                $key = (string)($item['item_key'] ?? 'custom_document');
                $label = $map[$key] ?? $key;
            }

            $status = strtolower((string)($item['status'] ?? 'pending'));
            if (in_array($status, ['failed', 'reupload_required'], true)) {
                $label .= ' (Re-upload Required)';
            }

            $lines[] = '• ' . $label;
        }
    } catch (Throwable $e) {
        $lines = [];
    }

    if (empty($lines)) {
        $json = $request['requested_items'] ?? null;
        if (!$json) return "• Additional Verification Document";
        $items = json_decode((string)$json, true);
        if (!is_array($items) || empty($items)) return "• Additional Verification Document";
        foreach ($items as $item) {
            $lines[] = '• ' . ($map[$item] ?? $item);
        }
    }

    return implode("\n", $lines);
}

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

function bot_debug_log(string $message): void {
    $dir = __DIR__ . '/uploads/wallet_transfer_verification';
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
    @file_put_contents($dir . '/bot_runtime_debug.log', '[' . date('Y-m-d H:i:s') . '] ' . $message . PHP_EOL, FILE_APPEND);
}

register_shutdown_function(function () {
    $e = error_get_last();
    if ($e) {
        $dir = __DIR__ . '/uploads/wallet_transfer_verification';
        if (!is_dir($dir)) {
            @mkdir($dir, 0755, true);
        }
        @file_put_contents($dir . '/bot_fatal_debug.log', '[' . date('Y-m-d H:i:s') . '] ' . json_encode($e, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
    }
});

require_once "config.php"; // must provide $pdo (PDO connection)

require_once __DIR__ . '/bot_token.php';

if (!isset($token) || trim((string)$token) === '') {
    die('Telegram bot token is missing.');
}
$update = json_decode(file_get_contents("php://input"), true);
file_put_contents(__DIR__.'/test_update.txt', json_encode($update).PHP_EOL, FILE_APPEND);
if (!function_exists('blocked_debug_log')) {
function blocked_debug_log($message) {
    @file_put_contents(__DIR__.'/bot_block_debug.log', '[' . date('Y-m-d H:i:s') . '] ' . $message . PHP_EOL, FILE_APPEND);
}
}

bot_debug_log("BOT HIT webhook request received");

$state_file = __DIR__ . "/users_state.json";
if (!file_exists($state_file)) {
    file_put_contents($state_file, json_encode([]));
}
$states = json_decode(file_get_contents($state_file), true);
if (!is_array($states)) {
    $states = [];
}

function saveStates($states, $state_file) {
    file_put_contents($state_file, json_encode($states, JSON_UNESCAPED_UNICODE));
}

function sendMessage($chat_id, $message, $reply_markup = null) {
    global $token;

    $payload = [
        'chat_id' => $chat_id,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];

    if ($reply_markup) {
        $payload['reply_markup'] = json_encode($reply_markup);
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.telegram.org/bot{$token}/sendMessage");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);

    if ($response === false) {
        if (function_exists('bot_debug_log')) {
            bot_debug_log('sendMessage cURL error: ' . curl_error($ch));
        }
    } else {
        if (function_exists('bot_debug_log')) {
            bot_debug_log('sendMessage response: ' . $response);
        }
    }

    curl_close($ch);
}

function answerCallbackQuery($callback_id, $text = '') {
    global $token;

    $payload = [
        'callback_query_id' => $callback_id,
        'text' => $text
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.telegram.org/bot{$token}/answerCallbackQuery");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);

    if ($response === false) {
        if (function_exists('bot_debug_log')) {
            bot_debug_log('answerCallbackQuery cURL error: ' . curl_error($ch));
        }
    } else {
        if (function_exists('bot_debug_log')) {
            bot_debug_log('answerCallbackQuery response: ' . $response);
        }
    }

    curl_close($ch);
}

function sendInlineKeyboard($chat_id, $text, $buttons) {
    sendMessage($chat_id, $text, ['inline_keyboard' => $buttons]);
}

function normalizeMobile($mobile) {
    $mobile = trim($mobile);
    return preg_replace('/\s+/', '', $mobile);
}

function normalizeDob($dob) {
    $dob = trim($dob);
    $ts = strtotime($dob);
    if ($ts === false) return false;
    return date("Y-m-d", $ts);
}

function generateTicketId() {
    return 'FP-CS-' . str_pad((string) random_int(1, 99999), 5, '0', STR_PAD_LEFT);
}

function getQueuePosition($pdo) {
    $stmt = $pdo->query("SELECT COUNT(*) AS total FROM support_chats WHERE status = 'waiting'");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return ((int)($row['total'] ?? 0)) + 1;
}

function estimateWaitMinutes($queuePosition) {
    $minutes = max(2, $queuePosition * 2);
    return $minutes;
}

function buildTranscriptText($pdo, $chatId) {
    $stmt = $pdo->prepare("SELECT sender, message, created_at FROM support_messages WHERE chat_id = :chat_id ORDER BY id ASC");
    $stmt->execute([':chat_id' => $chatId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $lines = [];
    foreach ($rows as $row) {
        $sender = strtoupper((string)($row['sender'] ?? 'SYSTEM'));
        $createdAt = (string)($row['created_at'] ?? '');
        $message = (string)($row['message'] ?? '');
        $lines[] = "[{$createdAt}] {$sender}: {$message}";
    }

    return implode("\n", $lines);
}

function generateSupportTicketId() {
    return 'FP-TK-' . str_pad((string) random_int(1, 99999), 5, '0', STR_PAD_LEFT);
}

function createSupportTicketRecord($pdo, $stateData, $cardType, $issueType, $description, $telegramId = null) {
    $user = $stateData['user'] ?? [];
    $ticketId = generateSupportTicketId();
    $userId = $user['id'] ?? null;
    $customerName = $user['name'] ?? 'Unverified Customer';
    $category = 'Card Support';
    $department = 'Card Operations Department';
    $status = 'Open';

    $stmt = $pdo->prepare("
        INSERT INTO support_tickets
        (ticket_id, user_id, customer_name, telegram_id, category, department, issue_type, description, status, created_at)
        VALUES
        (:ticket_id, :user_id, :customer_name, :telegram_id, :category, :department, :issue_type, :description, :status, NOW())
    ");
    $stmt->execute([
        ':ticket_id' => $ticketId,
        ':user_id' => $userId,
        ':customer_name' => $customerName,
        ':telegram_id' => $telegramId,
        ':category' => $category,
        ':department' => $department,
        ':issue_type' => $issueType . ' | Card Type: ' . $cardType,
        ':description' => $description,
        ':status' => $status
    ]);

    $messageStmt = $pdo->prepare("
        INSERT INTO ticket_messages (ticket_id, sender, message, created_at)
        VALUES (:ticket_id, 'customer', :message, NOW())
    ");
    $messageStmt->execute([
        ':ticket_id' => $ticketId,
        ':message' => $description
    ]);

    return $ticketId;
}

function getMainMenuButtons() {
    return [
        [
            ['text' => '📄 Latest Transfers', 'callback_data' => 'latest_wallet_transfers'],
            ['text' => '💸 Transfer Support', 'callback_data' => 'wallet_transfer']
        ],
        [
            ['text' => '🛡️ KYC & Verification', 'callback_data' => 'kyc_verification'],
            ['text' => '💳 Card Services', 'callback_data' => 'card_order']
        ],
        [
            ['text' => '🎫 My Support Tickets', 'callback_data' => 'my_support_tickets'],
            ['text' => '👨‍💼 Speak to an Officer', 'callback_data' => 'talk_to_agent']
        ],
        [
            ['text' => '📊 Account Review', 'callback_data' => 'account_status'],
            ['text' => '🚪 Secure Exit', 'callback_data' => 'exit_session']
        ]
    ];
}

function findUserByMobileDob($pdo, $mobile, $dob) {
    $sql = "
        SELECT *
        FROM users
        WHERE mobile = :mobile
          AND dob = :dob
        ORDER BY
            CASE WHEN LOWER(COALESCE(status, 'active')) = 'blocked' THEN 0 ELSE 1 END ASC,
            id DESC
        LIMIT 1
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':mobile' => $mobile,
        ':dob' => $dob
    ]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function findBlockedUserByMobileDob($pdo, $mobile, $dob) {
    $sql = "
        SELECT *
        FROM users
        WHERE mobile = :mobile
          AND dob = :dob
          AND LOWER(TRIM(COALESCE(status, 'active'))) = 'blocked'
        ORDER BY id DESC
        LIMIT 1
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':mobile' => $mobile,
        ':dob' => $dob
    ]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function debugUserMatchesByMobileDob($pdo, $mobile, $dob) {
    try {
        $stmt = $pdo->prepare("
            SELECT id, name, mobile, dob, status, block_reason_category, account_number
            FROM users
            WHERE mobile = :mobile AND dob = :dob
            ORDER BY id DESC
        ");
        $stmt->execute([
            ':mobile' => $mobile,
            ':dob' => $dob
        ]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) {
        return [];
    }
}


function findUserByMobile($pdo, $mobile) {
    $sql = "
        SELECT *
        FROM users
        WHERE mobile = :mobile
        ORDER BY
            CASE WHEN LOWER(COALESCE(status, 'active')) = 'blocked' THEN 0 ELSE 1 END ASC,
            id DESC
        LIMIT 1
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':mobile' => $mobile
    ]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}


function findUserByTelegramId($pdo, $telegramId) {
    try {
        $sql = "SELECT * FROM users WHERE telegram_id = :telegram_id LIMIT 1";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':telegram_id' => (string)$telegramId
        ]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        return false;
    }
}

function getBlockedUserRecord($pdo, $chat_id, $states) {
    try {
        $stateUser = $states[$chat_id]['user'] ?? $states[$chat_id]['verified_user'] ?? $states[$chat_id]['customer'] ?? null;

        if (is_array($stateUser) && !empty($stateUser['id'])) {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => (int)$stateUser['id']]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && trim(strtolower((string)($user['status'] ?? 'active'))) === 'blocked') {
                return $user;
            }
        }

        if (is_array($stateUser) && !empty($stateUser['mobile']) && !empty($stateUser['dob'])) {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE mobile = :mobile AND dob = :dob LIMIT 1");
            $stmt->execute([
                ':mobile' => trim((string)$stateUser['mobile']),
                ':dob' => trim((string)$stateUser['dob'])
            ]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && trim(strtolower((string)($user['status'] ?? 'active'))) === 'blocked') {
                return $user;
            }
        }
    } catch (Throwable $e) {
        return false;
    }

    return false;
}

function sendBlockedAccountNotice($pdo, $chat_id, $states) {
    $blockedUser = getBlockedUserRecord($pdo, $chat_id, $states);

    $message  = "🚫 <b>Account Access Restricted</b>

";
    $message .= "Dear Customer,

";
    $message .= "Your FinoviaPay digital banking account is currently restricted due to security or compliance related reasons.

";
    $message .= "As a result, access to automated banking services within this support assistant has been temporarily limited.

";
    $message .= "This restriction may be related to one or more of the following:
";
    $message .= "• Security verification requirements
";
    $message .= "• Compliance review
";
    $message .= "• Unresolved account verification matters
";
    $message .= "• Suspicious activity monitoring

";
    $message .= "For security and privacy reasons, detailed account information cannot be disclosed through automated channels.

";

    if ($blockedUser && !empty($blockedUser['block_reason_category'])) {
        $message .= "<b>Restriction Category</b>
" . htmlspecialchars((string)$blockedUser['block_reason_category'], ENT_QUOTES, 'UTF-8') . "

";
    }

    if ($blockedUser && !empty($blockedUser['block_reason_text'])) {
        $message .= "<b>Support Note</b>
" . htmlspecialchars((string)$blockedUser['block_reason_text'], ENT_QUOTES, 'UTF-8') . "

";
    }

    $message .= "If you believe this restriction has been applied in error or you would like to request a review of your account status, please contact our Customer Support Services through the secure support ticket option below.

";
    $message .= "Our banking operations team will carefully review your request and provide further guidance.

";
    $message .= "Thank you for your patience and cooperation.

";
    $message .= "— FinoviaPay Security & Compliance Department";

    $buttons = [
        [
            ['text' => '📩 Contact Customer Support', 'callback_data' => 'blocked_account_support']
        ]
    ];

    sendInlineKeyboard($chat_id, $message, $buttons);
}


function closeCustomerSession($pdo, $telegram_id, &$states, $state_file) {
    $openChat = getOpenSupportChat($pdo, $telegram_id);

    if ($openChat) {
        $stmt = $pdo->prepare("UPDATE support_chats SET status = 'closed', updated_at = NOW() WHERE id = :id");
        $stmt->execute([':id' => $openChat['id']]);
        insertSupportMessage($pdo, $openChat['id'], 'system', 'Customer exited the chat session and was logged out.');
    }

    unset($states[$telegram_id]);
    saveStates($states, $state_file);

    $exitMsg = "You have now exited your Finoviapay Customer Support session and have been securely logged out.\n\nTo speak with us again at any time, simply enter /start and you may continue using our Telegram digital banking support services whenever required.\n\nThank you for choosing Finoviapay.";
    sendMessage($telegram_id, $exitMsg);
}

function getOpenSupportChat($pdo, $telegram_id) {
    $stmt = $pdo->prepare("SELECT * FROM support_chats WHERE telegram_id = :tid AND status IN ('waiting','active','transferred') ORDER BY id DESC LIMIT 1");
    $stmt->execute([':tid' => $telegram_id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function getLatestSupportChatAnyStatus($pdo, $telegram_id) {
    $stmt = $pdo->prepare("SELECT * FROM support_chats WHERE telegram_id = :tid ORDER BY id DESC LIMIT 1");
    $stmt->execute([':tid' => $telegram_id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function createSupportChat($pdo, $telegram_id, $user = null) {
    $customer_name   = $user['name'] ?? null;
    $customer_mobile = $user['mobile'] ?? null;
    $customer_dob    = $user['dob'] ?? null;
    $customer_email  = $user['email'] ?? null;
    $user_id         = $user['id'] ?? null;
    $ticket_id       = generateTicketId();
    $queue_position  = getQueuePosition($pdo);
    $estimated_wait_minutes = estimateWaitMinutes($queue_position);

    $stmt = $pdo->prepare("
        INSERT INTO support_chats
        (ticket_id, telegram_id, user_id, customer_name, customer_mobile, customer_dob, customer_email, queue_position, estimated_wait_minutes, status, created_at, updated_at)
        VALUES
        (:ticket_id, :telegram_id, :user_id, :customer_name, :customer_mobile, :customer_dob, :customer_email, :queue_position, :estimated_wait_minutes, 'waiting', NOW(), NOW())
    ");

    $stmt->execute([
        ':ticket_id' => $ticket_id,
        ':telegram_id' => $telegram_id,
        ':user_id' => $user_id,
        ':customer_name' => $customer_name,
        ':customer_mobile' => $customer_mobile,
        ':customer_dob' => $customer_dob,
        ':customer_email' => $customer_email,
        ':queue_position' => $queue_position,
        ':estimated_wait_minutes' => $estimated_wait_minutes
    ]);

    return [
        'id' => $pdo->lastInsertId(),
        'ticket_id' => $ticket_id,
        'queue_position' => $queue_position,
        'estimated_wait_minutes' => $estimated_wait_minutes
    ];
}

function insertSupportMessage($pdo, $chat_id, $sender, $message) {
    $stmt = $pdo->prepare("
        INSERT INTO support_messages (chat_id, sender, message, created_at)
        VALUES (:chat_id, :sender, :message, NOW())
    ");
    $stmt->execute([
        ':chat_id' => $chat_id,
        ':sender' => $sender,
        ':message' => $message
    ]);
}

function notifyChatLifecycleUpdates($pdo, $telegram_id) {
    $chat = getLatestSupportChatAnyStatus($pdo, $telegram_id);
    if (!$chat) {
        return;
    }

    if ((int)($chat['agent_joined'] ?? 0) === 1 && (int)($chat['agent_joined_notified'] ?? 0) === 0) {
        $officerName = trim($chat['agent_name'] ?? 'FinoviaPay Support Officer');
        $officerId   = trim($chat['banker_officer_id'] ?? 'Not Available');
        $department  = trim($chat['department'] ?? 'Customer Support Department');

        $joinMsg = "Your live support request has now been accepted and joined by a FinoviaPay Support Officer.\n\nAssigned Support Officer: {$officerName}\nBanker Officer ID: {$officerId}\nDepartment: {$department}\n\nYour assigned officer is now reviewing your request and will continue assisting you through this secure conversation.\n\nFor your protection, please do not share your account password, card PIN, or one-time verification codes during this chat unless specifically instructed through an official and secure FinoviaPay verification process.\n\nYou may now continue your conversation with the assigned support officer.";

        sendMessage($telegram_id, $joinMsg);

        $upd = $pdo->prepare("UPDATE support_chats SET agent_joined_notified = 1, updated_at = NOW() WHERE id = :id");
        $upd->execute([':id' => $chat['id']]);

        insertSupportMessage($pdo, $chat['id'], 'system', 'Customer was notified that a support officer joined the conversation.');
    }

    if (!empty($chat['transferred_to_agent']) && (int)($chat['transfer_notified'] ?? 0) === 0) {
        $previousOfficer = trim($chat['agent_name'] ?? 'FinoviaPay Support Officer');
        $previousOfficerId = trim($chat['banker_officer_id'] ?? 'Not Available');
        $newDepartment = trim($chat['department'] ?? 'Customer Support Department');

        $transferMsg = "Your live support request is currently being transferred for further review and assistance.\n\nYour conversation was previously being handled by:\n\nSupport Officer: {$previousOfficer}\nBanker Officer ID: {$previousOfficerId}\n\nIn order to provide you with the most appropriate assistance, your request is now being redirected to another FinoviaPay Support Officer and/or the relevant department.\n\nNew Handling Department: {$newDepartment}\n\nPlease remain connected while we complete the transfer process. You will receive another confirmation message as soon as the newly assigned support officer joins your conversation.\n\nThank you for your patience and understanding.";

        sendMessage($telegram_id, $transferMsg);

        $upd = $pdo->prepare("UPDATE support_chats SET transfer_notified = 1, updated_at = NOW() WHERE id = :id");
        $upd->execute([':id' => $chat['id']]);

        insertSupportMessage($pdo, $chat['id'], 'system', 'Customer was notified that the chat was transferred.');
    }

    if ($chat['status'] === 'closed' && (int)($chat['closed_notified'] ?? 0) === 0) {
        $officerName = trim($chat['agent_name'] ?? 'FinoviaPay Support Officer');
        $officerId   = trim($chat['banker_officer_id'] ?? 'Not Available');
        $department  = trim($chat['department'] ?? 'Customer Support Department');

        $closeMsg = "Your live support session with FinoviaPay Customer Support has now been completed and formally closed.\n\nThis support conversation was handled by:\n\nSupport Officer: {$officerName}\nBanker Officer ID: {$officerId}\nDepartment: {$department}\n\nAccording to the assigned support officer, your request has been reviewed and the chat session has now been concluded.\n\nIf you require any further assistance regarding the same matter or a new request, you may contact FinoviaPay Customer Support again through the official support channel at any time.\n\nThank you for choosing FinoviaPay and for banking with us.\n\nPlease rate your support experience and, if required, request a chat transcript below.";

        $ratingButtons = [
            [
                ['text' => '⭐ 1', 'callback_data' => 'rate_chat_1'],
                ['text' => '⭐ 2', 'callback_data' => 'rate_chat_2'],
                ['text' => '⭐ 3', 'callback_data' => 'rate_chat_3']
            ],
            [
                ['text' => '⭐ 4', 'callback_data' => 'rate_chat_4'],
                ['text' => '⭐ 5', 'callback_data' => 'rate_chat_5']
            ],
            [
                ['text' => 'Send Chat Transcript', 'callback_data' => 'send_transcript']
            ]
        ];

        sendMessage($telegram_id, $closeMsg, ['inline_keyboard' => $ratingButtons]);

        $upd = $pdo->prepare("UPDATE support_chats SET closed_notified = 1, rating_requested = 1, updated_at = NOW() WHERE id = :id");
        $upd->execute([':id' => $chat['id']]);

        insertSupportMessage($pdo, $chat['id'], 'system', 'Customer was notified that the chat session was closed.');
    }
}

$message      = $update['message'] ?? null;
$callback     = $update['callback_query'] ?? null;
$chat_id      = null;
$text         = null;
$callbackData = null;
$callbackId   = null;

if ($message) {
    $chat_id = $message['chat']['id'] ?? null;
    $text    = trim($message['text'] ?? '');
}
if ($callback) {
    $chat_id      = $callback['message']['chat']['id'] ?? null;
    $callbackData = $callback['data'] ?? null;
    $callbackId   = $callback['id'] ?? null;
}

if (!$chat_id) {
    exit;
}

try {
    notifyChatLifecycleUpdates($pdo, $chat_id);

    $state = $states[$chat_id] ?? null;


    if ($text === '/start') {
        $welcome = "Welcome to <b>Finoviapay Customer Support</b>\n\nWelcome to the official FinoviaPay Digital Banking Support channel. This secure automated assistant allows verified customers to access support services, review transfer activity, submit verification documents, and connect with the relevant banking operations team.\n\n<b>Service Notice</b>\nFinoviaPay continuously expands its digital banking services. Certain modules are currently under development and will be introduced progressively as they become available.\n\n<b>Currently Available Services</b>\n• Latest Wallet Transfer Review\n• Wallet Transfer Support\n• KYC Identity Verification\n• Card Order Support\n• Account Status\n• Direct Support Agent Access\n\n<b>Upcoming Banking Features</b>\n• New Account Opening\n• Virtual Card Creation\n• Direct Wallet Transfer Initiation\n• Additional Digital Banking Services\n• Much More";

        $buttons = [
            [
                ['text' => '✅ Existing Customer', 'callback_data' => 'already_customer'],
                ['text' => '📝 New Customer', 'callback_data' => 'not_registered']
            ]
        ];

        $states[$chat_id] = ['step' => 'choose_customer_type'];
        saveStates($states, $state_file);
        sendInlineKeyboard($chat_id, $welcome, $buttons);
        exit;
    }


    // Priority route for separate Virtual Card module
    if (
        $callbackData === 'ticket_card_type_virtual' ||
        strpos((string)$callbackData, 'virtual_card_') === 0 ||
        (($states[$chat_id]['step'] ?? '') === 'virtual_card_menu') ||
        (($states[$chat_id]['step'] ?? '') === 'awaiting_eu_mobile' && $text !== '')
    ) {
        require __DIR__ . '/virtual_card_services.php';
        exit;
    }

    /* ===============================
       KYC VERIFICATION MODULE
    ================================ */

    if (
        ($callbackData ?? '') === 'kyc_pending_status' ||
        ($callbackData ?? '') === 'kyc_open_request' ||
        (($states[$chat_id]['kyc_verification']['active'] ?? false) === true)
    ) {
        if ($callbackId) {
            answerCallbackQuery($callbackId);
        }
        require __DIR__ . '/kyc_verification.php';
        exit;
    }

    if ($text === '/exit' || $callbackData === 'exit_session') {
        if ($callbackId) {
            answerCallbackQuery($callbackId);
        }
        closeCustomerSession($pdo, $chat_id, $states, $state_file);
        exit;
    }

    if ($text === '/start') {
        $welcome = "Welcome to <b>Finoviapay Customer Support</b>\n\nWelcome to the official FinoviaPay Digital Banking Support channel. This secure automated assistant allows verified customers to access support services, review transfer activity, submit verification documents, and connect with the relevant banking operations team.\n\n<b>Service Notice</b>\nFinoviaPay continuously expands its digital banking services. Certain modules are currently under development and will be introduced progressively as they become available.\n\n<b>Currently Available Services</b>\n• Latest Wallet Transfer Review\n• Wallet Transfer Support\n• KYC Identity Verification\n• Card Order Support\n• Account Status\n• Direct Support Agent Access\n\n<b>Upcoming Banking Features</b>\n• New Account Opening\n• Virtual Card Creation\n• Direct Wallet Transfer Initiation\n• Additional Digital Banking Services\n• Much More";

        $buttons = [
            [
                ['text' => '✅ Existing Customer', 'callback_data' => 'already_customer'],
                ['text' => '📝 New Customer', 'callback_data' => 'not_registered']
            ]
        ];

        sendInlineKeyboard($chat_id, $welcome, $buttons);
        $states[$chat_id] = ['step' => 'choose_customer_type'];
        saveStates($states, $state_file);
        exit;
    }


    /* ===============================
       LATEST WALLET TRANSFERS MODULE LINK
       =============================== */
    if (
        ($callbackData ?? '') === 'latest_wallet_transfers' ||
        str_starts_with((string)($callbackData ?? ''), 'lwt_') ||
        (($states[$chat_id]['latest_wallet_transfers']['active'] ?? false) === true)
    ) {
        require __DIR__ . '/latest_wallet_transfers.php';
        exit;
    }


    /* ===============================
       WALLET TRANSFER VERIFICATION UPLOAD MODULE
       =============================== */
    if (
        str_starts_with((string)($callbackData ?? ''), 'wtvr_upload_') ||
        (($states[$chat_id]['wallet_transfer_verification_request']['step'] ?? '') === 'await_upload')
    ) {
        require __DIR__ . '/wallet_transfer_verification_request.php';
        exit;
    }

    /* ===============================
       BLOCKED ACCOUNT SUPPORT MODULE
       =============================== */
    if (
        ($callbackData ?? '') === 'blocked_account_support' ||
        (($states[$chat_id]['blocked_account_ticket']['active'] ?? false) === true)
    ) {
        require __DIR__ . '/blocked_account_ticket.php';
        exit;
    }

    /* ===============================
       WALLET TRANSFER MODULE LINK
       =============================== */
    if (
        ($callbackData ?? '') === 'wallet_transfer' ||
        str_starts_with((string)($callbackData ?? ''), 'wt_') ||
        (($states[$chat_id]['wallet_transfer']['active'] ?? false) === true)
    ) {
        require __DIR__ . '/wallet_transfer.php';
        exit;
    }

    if ($callbackData === 'main_menu') {
        $state = $states[$chat_id] ?? [];
        if (isset($state['user']) && is_array($state['user'])) {
            $name = htmlspecialchars($state['user']['name'] ?? 'Customer', ENT_QUOTES, 'UTF-8');
            $greeting = "🏦 <b>Welcome back to FinoviaPay Digital Banking Support</b>

<b>Customer Name</b>
{$name}

<b>Account Status</b>
Verified

You may continue by selecting one of the banking support categories below.";
            sendInlineKeyboard($chat_id, $greeting, getMainMenuButtons());
        } else {
            $welcome = "🏦 <b>Welcome to FinoviaPay Digital Banking Support</b>

Please choose one of the secure banking support options below to continue.";
            $buttons = [
                [['text' => '✅ Existing Customer', 'callback_data' => 'already_customer']],
                [['text' => '📝 New Customer', 'callback_data' => 'not_registered']]
            ];
            sendInlineKeyboard($chat_id, $welcome, $buttons);
        }
        exit;
    }

    if ($callback) {
        answerCallbackQuery($callbackId);

        if ($callbackData === 'already_customer') {
            $states[$chat_id] = ['step' => 'await_mobile'];

            sendMessage(
                $chat_id,
                "For account identification, please enter your <b>registered mobile number</b> exactly as it appears on your Finoviapay profile.\n\nExample:\n+34600000000"
            );

            saveStates($states, $state_file);
            exit;
        }

        if ($callbackData === 'not_registered') {
            unset($states[$chat_id]);
            saveStates($states, $state_file);

            sendMessage(
                $chat_id,
                "Thank you for contacting FinoviaPay.\n\nOur records indicate that you have selected the non-registered customer option.\n\nTo access full banking support services, please complete your registration through our official platform.\n\nRegistration Link:\nhttps://finoviapay.com/register"
            );
            exit;
        }

        if ($callbackData === 'retry_mobile') {
            $states[$chat_id] = ['step' => 'await_mobile'];
            saveStates($states, $state_file);

            sendMessage(
                $chat_id,
                "Please re-enter your registered mobile number exactly as it appears on your Finoviapay profile.\n\nExample:\n+34600000000"
            );
            exit;
        }

        if ($callbackData === 'talk_to_agent_unverified') {
            $enteredMobile = $states[$chat_id]['entered_mobile'] ?? null;
            $existingChat = getOpenSupportChat($pdo, $chat_id);

            if ($existingChat) {
                sendMessage(
                    $chat_id,
                    "Your live support request is already active in our secure support system.\n\nPlease remain connected while the assigned or next available FinoviaPay Support Officer continues handling your request."
                );
                exit;
            }

            $chat = createSupportChat($pdo, $chat_id, null);

            if ($enteredMobile) {
                $upd = $pdo->prepare("UPDATE support_chats SET customer_mobile = :mobile, updated_at = NOW() WHERE id = :id");
                $upd->execute([
                    ':mobile' => $enteredMobile,
                    ':id' => $chat['id']
                ]);
            }

            $waitingMsg = "Thank you for contacting FinoviaPay Customer Support.\n\nYour request to speak with a FinoviaPay Support Officer has been successfully received and securely registered in our customer support system.\n\nSupport Ticket ID: {$chat['ticket_id']}\nCurrent Queue Position: #{$chat['queue_position']}\nEstimated Waiting Time: {$chat['estimated_wait_minutes']} minutes\n\nAt this time, your mobile number could not be matched against our registered database records. However, your request may still be reviewed by a support officer. Verified customers may be prioritized where applicable.\n\nSecurity Notice\nFinoviaPay support officers will NEVER ask for your account password, card PIN, or one-time verification codes (OTP). If anyone requests this information, please report the incident immediately.\n\nPlease remain connected while we assign the next available banking support officer to your request.\n\nOnce an officer joins your conversation, you will receive a confirmation message together with the officer’s name, Banker Officer ID, and department details.\n\nWe appreciate your patience and thank you for choosing FinoviaPay.";

            sendMessage($chat_id, $waitingMsg);
            insertSupportMessage($pdo, $chat['id'], 'system', 'Unverified customer requested live agent support after mobile number did not match. Waiting notice with ticket details and security notice sent to customer.');
            exit;
        }



        if (strpos((string)$callbackData, 'rate_chat_') === 0) {
            $rating = (int) str_replace('rate_chat_', '', (string)$callbackData);
            if ($rating >= 1 && $rating <= 5) {
                $latestChat = getLatestSupportChatAnyStatus($pdo, $chat_id);
                if ($latestChat) {
                    $stmt = $pdo->prepare("INSERT INTO chat_ratings (chat_id, rating, created_at) VALUES (:chat_id, :rating, NOW())");
                    $stmt->execute([
                        ':chat_id' => $latestChat['id'],
                        ':rating' => $rating
                    ]);

                    $upd = $pdo->prepare("UPDATE support_chats SET rating_received = 1, updated_at = NOW() WHERE id = :id");
                    $upd->execute([':id' => $latestChat['id']]);
                }

                sendMessage($chat_id, "Thank you for rating your recent FinoviaPay support experience. Your feedback has been securely recorded and will help us improve our digital banking support services.");
            }
            exit;
        }

        if ($callbackData === 'send_transcript') {
            $latestChat = getLatestSupportChatAnyStatus($pdo, $chat_id);

            if (!$latestChat) {
                sendMessage($chat_id, "We were unable to locate a completed support session for transcript processing at this time. Please contact FinoviaPay Customer Support again if you require further assistance.");
                exit;
            }

            $transcriptText = buildTranscriptText($pdo, (int)$latestChat['id']);
            $customerEmail = $latestChat['customer_email'] ?? null;

            $stmt = $pdo->prepare("
                INSERT INTO chat_transcripts (chat_id, customer_email, transcript_text, sent_status, created_at)
                VALUES (:chat_id, :customer_email, :transcript_text, 0, NOW())
            ");
            $stmt->execute([
                ':chat_id' => $latestChat['id'],
                ':customer_email' => $customerEmail,
                ':transcript_text' => $transcriptText
            ]);

            $upd = $pdo->prepare("UPDATE support_chats SET transcript_sent = 1, updated_at = NOW() WHERE id = :id");
            $upd->execute([':id' => $latestChat['id']]);

            if (!empty($customerEmail)) {
                sendMessage($chat_id, "Your chat transcript request has been successfully registered. A copy of your completed support conversation has been queued for delivery to your registered email address: {$customerEmail}.");
            } else {
                sendMessage($chat_id, "Your chat transcript request has been successfully registered. However, no verified email address is currently available in our records for this support session.");
            }
            exit;
        }

        if ($callbackData === 'wallet_transfer') {
            sendMessage($chat_id, "You have selected <b>Wallet Transfer Support</b>.\n\nPlease send a brief description of your issue, and a support officer will review it accordingly.");
            exit;
        }

        if ($callbackData === 'kyc_verification') {
            sendMessage($chat_id, "You have selected <b>KYC Verification Support</b>.\n\nPlease provide a brief explanation of your query, and our compliance support team will review your request.");
            exit;
        }

        if (
            $callbackData === 'card_order' ||
            strpos((string)$callbackData, 'ticket_card_type_') === 0 ||
            strpos((string)$callbackData, 'ticket_issue_') === 0 ||
            strpos((string)$callbackData, 'physical_card_') === 0 ||
            strpos((string)$callbackData, 'physical_card_view_') === 0 ||
            in_array(($states[$chat_id]['step'] ?? ''), ['ticket_card_type', 'ticket_issue_type', 'physical_card_menu'], true)
        ) {
            require __DIR__ . '/card_services.php';
            exit;
        }

        if (
            $callbackData === 'my_support_tickets' ||
            strpos((string)$callbackData, 'my_tickets_') === 0
        ) {
            require __DIR__ . '/my_support_tickets.php';
            exit;
        }


        if ($callbackData === 'create_card_ticket') {
            $states[$chat_id]['step'] = 'ticket_card_type';
            saveStates($states, $state_file);

            $buttons = [
                [
                    ['text' => '💳 Physical Card Support', 'callback_data' => 'ticket_card_type_physical'],
                    ['text' => '🪪 Virtual Card Support', 'callback_data' => 'ticket_card_type_virtual']
                ],
                [
                    ['text' => '🔐 One-Time Card Support', 'callback_data' => 'ticket_card_type_onetime']
                ],
                [
                    ['text' => '↩️ Back to Main Menu', 'callback_data' => 'main_menu']
                ]
            ];

            sendInlineKeyboard($chat_id, "💳 <b>Manage a Card</b>

Please select your card type to continue with secure card support.", $buttons);
            exit;
        }

        if (strpos((string)$callbackData, 'ticket_card_type_') === 0) {
            $cardTypeMap = [
                'ticket_card_type_virtual' => 'Virtual Card',
                'ticket_card_type_physical' => 'Physical Card',
                'ticket_card_type_onetime' => 'One-Time Card'
            ];
            $selectedCardType = $cardTypeMap[$callbackData] ?? 'Card';

            $states[$chat_id]['step'] = 'ticket_issue_type';
            $states[$chat_id]['ticket_flow']['card_type'] = $selectedCardType;
            saveStates($states, $state_file);

            $buttons = [
                [
                    ['text' => 'Card Declined', 'callback_data' => 'ticket_issue_declined'],
                    ['text' => 'Online Payment Failed', 'callback_data' => 'ticket_issue_online_failed']
                ],
                [
                    ['text' => 'Card Not Activated', 'callback_data' => 'ticket_issue_not_activated'],
                    ['text' => 'Card Blocked', 'callback_data' => 'ticket_issue_blocked']
                ],
                [
                    ['text' => 'Other Issue', 'callback_data' => 'ticket_issue_other']
                ]
            ];

            sendInlineKeyboard($chat_id, "Please select the issue you are experiencing.", $buttons);
            exit;
        }

        if (strpos((string)$callbackData, 'ticket_issue_') === 0) {
            $issueMap = [
                'ticket_issue_declined' => 'Card Declined',
                'ticket_issue_online_failed' => 'Online Payment Failed',
                'ticket_issue_not_activated' => 'Card Not Activated',
                'ticket_issue_blocked' => 'Card Blocked',
                'ticket_issue_other' => 'Other Issue'
            ];
            $selectedIssue = $issueMap[$callbackData] ?? 'Other Issue';

            $states[$chat_id]['step'] = 'ticket_description';
            $states[$chat_id]['ticket_flow']['issue_type'] = $selectedIssue;
            saveStates($states, $state_file);

            sendMessage(
                $chat_id,
                "Please briefly describe the issue you are experiencing with your card.\n\nOur Card Operations Department will review your request once your ticket is submitted."
            );
            exit;
        }

        if ($callbackData === 'account_status') {
            sendMessage($chat_id, "You have selected <b>Account Status Support</b>.\n\nPlease send your request in detail for further review.");
            exit;
        }

        if ($callbackData === 'talk_to_agent') {
            $verifiedUser = $states[$chat_id]['user'] ?? null;
            $existingChat = getOpenSupportChat($pdo, $chat_id);

            if ($existingChat) {
                sendMessage(
                    $chat_id,
                    "Your live support request is already active in our secure support system.\n\nPlease remain connected while the assigned or next available FinoviaPay Support Officer continues handling your request."
                );
                exit;
            }

            $chat = createSupportChat($pdo, $chat_id, $verifiedUser);

            $waitingMsg = "Thank you for contacting FinoviaPay Customer Support.\n\nYour request to speak with a FinoviaPay Support Officer has been successfully received and securely registered in our customer support system.\n\nSupport Ticket ID: {$chat['ticket_id']}\nCurrent Queue Position: #{$chat['queue_position']}\nEstimated Waiting Time: {$chat['estimated_wait_minutes']} minutes\n\nSecurity Notice\nFinoviaPay support officers will NEVER ask for your account password, card PIN, or one-time verification codes (OTP). If anyone requests this information, please report the incident immediately.\n\nPlease remain connected while we assign the next available banking support officer to your request.\n\nOnce an officer joins your conversation, you will receive a confirmation message together with the officer’s name, Banker Officer ID, and department details.\n\nIn the meantime, you may continue to type your message here. Your information will remain securely available for review by the assigned support officer.\n\nWe appreciate your patience and thank you for choosing FinoviaPay.";

            sendMessage($chat_id, $waitingMsg);
            insertSupportMessage($pdo, $chat['id'], 'system', 'Customer requested live agent support. Waiting notice with ticket details and security notice sent to customer.');
            exit;
        }
    }

    if (is_array($state) && ($state['step'] ?? '') === 'await_mobile' && $text !== '') {
        $mobile = normalizeMobile($text);
        $mobileUser = findUserByMobile($pdo, $mobile);

        if ($mobileUser) {
            $states[$chat_id] = [
                'step' => 'await_dob',
                'mobile' => $mobile
            ];
            saveStates($states, $state_file);

            sendMessage(
                $chat_id,
                "Thank you.\n\nNow please enter your <b>Date of Birth</b> for secure verification.\n\nAccepted format:\nYYYY-MM-DD\n\nExample:\n1996-08-12"
            );
            exit;
        }

        $states[$chat_id] = [
            'step' => 'mobile_not_found',
            'entered_mobile' => $mobile
        ];
        saveStates($states, $state_file);

        $buttons = [
            [
                ['text' => 'Try Again', 'callback_data' => 'retry_mobile'],
                ['text' => 'Talk to Banker Officer', 'callback_data' => 'talk_to_agent_unverified']
            ]
        ];

        sendInlineKeyboard(
            $chat_id,
            "The mobile number you entered could not be matched with our registered system records.\n\nPlease review your number carefully and try again.\n\nIf you would still like to speak with one of our banker officers, please select the option below.",
            $buttons
        );
        exit;
    }

    if (is_array($state) && ($state['step'] ?? '') === 'await_dob' && $text !== '') {
        $mobile = $state['mobile'] ?? '';
        $dob = normalizeDob($text);

        if (!$dob) {
            sendMessage($chat_id, "The Date of Birth format could not be recognized.\n\nPlease enter it in the following format:\nYYYY-MM-DD\n\nExample:\n1996-08-12");
            exit;
        }

        $matchedRows = debugUserMatchesByMobileDob($pdo, $mobile, $dob);
        if (function_exists('bot_debug_log')) {
            bot_debug_log('DOB verification full matches=' . json_encode($matchedRows, JSON_UNESCAPED_UNICODE));
        }
        blocked_debug_log('DOB verification full matches=' . json_encode($matchedRows, JSON_UNESCAPED_UNICODE));

        $blockedUser = findBlockedUserByMobileDob($pdo, $mobile, $dob);
        if (function_exists('bot_debug_log')) {
            bot_debug_log('DOB verification blocked match=' . (is_array($blockedUser) ? ('yes user_id=' . ($blockedUser['id'] ?? '') . ' status=' . ($blockedUser['status'] ?? '')) : 'no'));
        }
        blocked_debug_log('DOB verification blocked match=' . (is_array($blockedUser) ? ('yes user_id=' . ($blockedUser['id'] ?? '') . ' status=' . ($blockedUser['status'] ?? '')) : 'no'));

        if ($blockedUser) {
            $states[$chat_id] = [
                'step' => 'blocked',
                'identified_user_id' => (int)($blockedUser['id'] ?? 0),
                'user' => [
                    'id' => $blockedUser['id'] ?? null,
                    'name' => $blockedUser['name'] ?? 'Customer',
                    'mobile' => $blockedUser['mobile'] ?? $mobile,
                    'dob' => $blockedUser['dob'] ?? $dob,
                    'email' => $blockedUser['email'] ?? '',
                    'account_number' => $blockedUser['account_number'] ?? ''
                ]
            ];
            saveStates($states, $state_file);

            sendBlockedAccountNotice($pdo, $chat_id, $states);
            exit;
        }

        $user = findUserByMobileDob($pdo, $mobile, $dob);
        if (function_exists('bot_debug_log')) {
            bot_debug_log('DOB verification active/general match=' . (is_array($user) ? ('yes user_id=' . ($user['id'] ?? '') . ' status=' . ($user['status'] ?? '')) : 'no'));
        }
        blocked_debug_log('DOB verification active/general match=' . (is_array($user) ? ('yes user_id=' . ($user['id'] ?? '') . ' status=' . ($user['status'] ?? '')) : 'no'));

        if ($user) {
            $states[$chat_id] = [
                'step' => 'verified',
                'identified_user_id' => (int)($user['id'] ?? 0),
                'user' => [
                    'id' => $user['id'] ?? null,
                    'name' => $user['name'] ?? 'Customer',
                    'mobile' => $user['mobile'] ?? $mobile,
                    'dob' => $user['dob'] ?? $dob,
                    'email' => $user['email'] ?? '',
                    'account_number' => $user['account_number'] ?? ''
                ]
            ];
            saveStates($states, $state_file);

            $name = htmlspecialchars($user['name'] ?? 'Customer', ENT_QUOTES, 'UTF-8');
            $greeting = "Welcome back to FinoviaPay Digital Banking Support.\n\nCustomer Name: <b>{$name}</b>\nAccount Status: Verified\n\nHow may we assist you today?\n\nPlease select the support category you wish to continue with.";

            sendInlineKeyboard($chat_id, $greeting, getMainMenuButtons());

            $userId = (int)($user['id'] ?? 0);
            if ($userId > 0) {
                $pendingKyc = getPendingKycRequestByUserId($pdo, $userId);
                if ($pendingKyc) {
                    $department = $pendingKyc['department'] ?? 'Verification Department';
                    $itemsText = formatKycRequestedItems($pdo, $pendingKyc);

                    sendInlineKeyboard(
                        $chat_id,
                        "⚠️ FinoviaPay Verification Notice

A verification request is currently pending for your account.

Department: {$department}

Required Verification Items:
{$itemsText}

Please complete the requested verification through the secure upload option below.",
                        [
                            [
                                ['text' => 'Open Verification Upload', 'callback_data' => 'kyc_open_request']
                            ]
                        ]
                    );
                }
            }

            exit;
        } else {
            sendMessage($chat_id, "We were unable to verify your details against our registered records.\n\nPlease review your mobile number and date of birth carefully, then type /start to begin the identification process again.");
            unset($states[$chat_id]);
            saveStates($states, $state_file);
            exit;
        }
    }

    if (is_array($state) && ($state['step'] ?? '') === 'ticket_description' && $text !== '') {
        $cardType = $states[$chat_id]['ticket_flow']['card_type'] ?? 'Card';
        $issueType = $states[$chat_id]['ticket_flow']['issue_type'] ?? 'Other Issue';
        $ticketId = createSupportTicketRecord($pdo, $states[$chat_id], $cardType, $issueType, $text, $chat_id);

        unset($states[$chat_id]['ticket_flow']);
        if (isset($states[$chat_id]['user'])) {
            $states[$chat_id]['step'] = 'verified';
        } else {
            $states[$chat_id]['step'] = 'choose_customer_type';
        }
        saveStates($states, $state_file);

        sendMessage(
            $chat_id,
            "Your support ticket has been successfully created.\n\nTicket ID: {$ticketId}\nDepartment: Card Operations Department\n\nYour request has been forwarded to the FinoviaPay Card Operations Department for review.\n\nOur support team will examine the information you provided and will respond to your ticket as soon as possible.\n\nIf additional information is required, you may be contacted by a FinoviaPay Support Officer.\n\nThank you for choosing FinoviaPay."
        );
        exit;
    }

    if ($message && $text !== '' && $text !== '/start') {
        $openChat = getOpenSupportChat($pdo, $chat_id);

        if ($openChat) {
            $lowerText = strtolower($text);
            $ignoreTexts = [
                'already a customer',
                'not registered yet',
                'wallet transfer',
                'kyc verification',
                'card order',
                'talk to agent',
                'account status'
            ];

            if (!in_array($lowerText, $ignoreTexts, true)) {
                insertSupportMessage($pdo, $openChat['id'], 'user', $text);
                $upd = $pdo->prepare("UPDATE support_chats SET updated_at = NOW() WHERE id = :id");
                $upd->execute([':id' => $openChat['id']]);
            }
        }
    }

} catch (Throwable $e) {
    error_log("BOT ERROR: " . $e->getMessage());
}

exit;
?>
