<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Request as HttpRequest;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use App\Services\SmscodeService;
use App\Models\Deposit;
use App\Models\Order;
use App\Models\ReferralCommission;
use App\Http\Controllers\OrderV2Controller;
use App\Http\Controllers\DepositController;

class TelegramWebhookController extends Controller
{
    private function isJoinedChannel($telegramId)
    {
        $tokenBot = env('TELEGRAM_BOT_TOKEN');
        $channel = '@nusaotp_official';

        try {

            $response = Http::get(
                "https://api.telegram.org/bot{$tokenBot}/getChatMember",
                [
                    'chat_id' => $channel,
                    'user_id' => $telegramId
                ]
            );

            if (!$response->successful()) {
                return false;
            }

            $data = $response->json();

            if (!($data['ok'] ?? false)) {
                return false;
            }

            return in_array(
                $data['result']['status'],
                [
                    'creator',
                    'administrator',
                    'member'
                ]
            );

        } catch (\Exception $e) {
            return false;
        }
    }
    public function handle(Request $request)
    {
        $update = $request->all();
        $tokenBot = env('TELEGRAM_BOT_TOKEN');
        $data = null;


        /*
        |--------------------------------------------------------------------------
        | CALLBACK BUTTON
        |--------------------------------------------------------------------------
        */

        if (isset($update['callback_query'])) {

            $callback = $update['callback_query'];

            $callbackId = $callback['id'];

            $chatId = $callback['message']['chat']['id'];

            $data = $callback['data'];

            // auto loading selesai
            if (
                !str_starts_with($data, 'cancel_order_') &&
                !str_starts_with($data, 'check_') &&
                $data != 'login_website'
            ) {
                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/answerCallbackQuery",
                    [
                        'callback_query_id' => $callbackId
                    ]
                );
            }
            $telegramId = $callback['from']['id'];
            if (
                $data != 'check_join_channel' &&
                !$this->isJoinedChannel($telegramId)
            ) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' =>
                            "━━━━━━━━━━━━━━━
❌ Akses Anda Ditolak!
━━━━━━━━━━━━━━━
Silahkan Bergabung Ke Dalam
Channel Terlebih Dahulu.
━━━━━━━━━━━━━━━",

                        'reply_markup' => json_encode([
                            'inline_keyboard' => [

                                [
                                    [
                                        'text' => '📢 Gabung Ke Channel',
                                        'url' => 'https://t.me/nusaotp_official'
                                    ]
                                ],

                                [
                                    [
                                        'text' => '✅ Sudah Bergabung? Klik Disini.',
                                        'url' => 'https://t.me/' . env('TELEGRAM_BOT_USERNAME') . '?start=checkjoin'
                                    ]
                                ]

                            ]
                        ])
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            $user = User::where(
                'telegram_id',
                $telegramId
            )->first();
            /*
            |--------------------------------------------------------------------------
            | FORCE JOIN CHANNEL
            |--------------------------------------------------------------------------
            */

            if (
                $user &&
                !$this->isJoinedChannel($telegramId)
            ) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' =>
                            "━━━━━━━━━━━━━━━
❌ Akses Anda Ditolak! 
━━━━━━━━━━━━━━━
Silahkan Bergabung Ke Dalam
Channel Terlebih Dahulu.
━━━━━━━━━━━━━━━",

                        'reply_markup' => json_encode([
                            'inline_keyboard' => [

                                [
                                    [
                                        'text' => '📢 Gabung Ke Channel',
                                        'url' => 'https://t.me/nusaotp_official'
                                    ]
                                ],

                                [
                                    [
                                        'text' => '✅ Sudah Bergabung? Klik Disini.',
                                        'url' => 'https://t.me/' . env('TELEGRAM_BOT_USERNAME') . '?start=checkjoin'
                                    ]
                                ]

                            ]
                        ])
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            if (
                !$user &&
                !in_array($data, ['has_account', 'new_account'])
            ) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' =>
                            "━━━━━━━━━━━━━━━
❌ Akun belum terhubung.
━━━━━━━━━━━━━━━
Silahkan ketik /start
terlebih dahulu.
━━━━━━━━━━━━━━━"
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            /*
            |--------------------------------------------------------------------------
            | LINK ACCOUNT EXISTING
            |--------------------------------------------------------------------------
            */

            if ($data == 'has_account') {
                // hapus tombol setelah diklik
                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/editMessageReplyMarkup",
                    [
                        'chat_id' => $chatId,
                        'message_id' => $callback['message']['message_id'],
                        'reply_markup' => json_encode([
                            'inline_keyboard' => []
                        ])
                    ]
                );
                Cache::put(
                    'telegram_state_' . $telegramId,
                    'waiting_email_link',
                    now()->addMinutes(10)
                );

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,

                        'text' =>
                            "━━━━━━━━━━━━━━━
📧 Silahkan kirim email akun
website yang terdaftar.
━━━━━━━━━━━━━━━"
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            /*
            |--------------------------------------------------------------------------
            | CREATE NEW ACCOUNT
            |--------------------------------------------------------------------------
            */

            if ($data == 'new_account') {

                $refCode = Cache::get(
                    'telegram_ref_' . $telegramId
                );

                $referrerId = null;

                if ($refCode) {

                    $referrer = User::where(
                        'referral_code',
                        $refCode
                    )->first();

                    if ($referrer) {
                        $referrerId = $referrer->id;
                    }
                }
                // cek apakah telegram sudah terhubung
                $existingUser = User::where(
                    'telegram_id',
                    $telegramId
                )->first();

                if ($existingUser) {

                    // hapus tombol lama
                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/editMessageReplyMarkup",
                        [
                            'chat_id' => $chatId,
                            'message_id' => $callback['message']['message_id'],
                            'reply_markup' => json_encode([
                                'inline_keyboard' => []
                            ])
                        ]
                    );

                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                        [
                            'chat_id' => $chatId,
                            'text' =>
                                "━━━━━━━━━━━━━━━
✅ Akun sudah terhubung.
━━━━━━━━━━━━━━━
Kini akun anda telah 
sinkron sepenuhnya.
━━━━━━━━━━━━━━━
Ketik /start untuk masuk.
━━━━━━━━━━━━━━━"
                        ]
                    );

                    return response()->json([
                        'success' => true
                    ]);
                }
                $user = User::create([

                    'name' => $callback['from']['first_name']
                        ?? 'Telegram User',

                    'telegram_id' => $telegramId,

                    'telegram_username' =>
                        $callback['from']['username']
                        ?? null,

                    'email' =>
                        'telegram_' . $telegramId . '@telegram.local',

                    'password' => bcrypt(Str::random(40)),

                    'register_source' => 'telegram',

                    'referrer_id' => $referrerId,
                ]);

                // insert referrals
                if ($referrerId) {

                    \DB::table('referrals')->insert([
                        'user_id' => $referrerId,
                        'referred_user_id' => $user->id,
                        'deposit_amount' => 0,
                        'bonus' => 0,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
                // sembunyikan tombol lama
                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/editMessageReplyMarkup",
                    [
                        'chat_id' => $chatId,
                        'message_id' => $callback['message']['message_id'],
                        'reply_markup' => json_encode([
                            'inline_keyboard' => []
                        ])
                    ]
                );
                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,

                        'text' =>
                            "━━━━━━━━━━━━━━━
✅ Akun berhasil dibuat.
━━━━━━━━━━━━━━━
Jika anda ingin menggunakan versi
website, anda cukup klik tombol
Login Webiste atau pada halaman
login website, anda dapat
menggunakan Login Via Telegram
ini dilakukan agar akun anda
tidak double dan saldo anda sinkron.
━━━━━━━━━━━━━━━
Ketik /start untuk masuk ke menu utama."
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            /*
            |--------------------------------------------------------------------------
            | LOGIN WEBSITE CALLBACK
            |--------------------------------------------------------------------------
            */

            if ($data == 'login_website') {

                $loginToken = Str::random(64);

                Cache::put(
                    'telegram_login_' . $loginToken,
                    [
                        'telegram_id' => $telegramId,
                        'name' => $user->name,
                        'username' => $user->telegram_username,
                    ],
                    now()->addMinutes(5)
                );

                $loginUrl = url('/telegram/login/' . $loginToken);

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/answerCallbackQuery",
                    [
                        'callback_query_id' => $callbackId,
                        'url' => $loginUrl
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            /*
            |--------------------------------------------------------------------------
            | COUNTRY PAGE
            |--------------------------------------------------------------------------
            */

            if (str_starts_with($data, 'country_page_')) {

                $page = (int) str_replace(
                    'country_page_',
                    '',
                    $data
                );

                $svc = app(SmscodeService::class);

                $favorites = [
                    'indonesia',
                    'malaysia',
                    'philippines',
                    'kenya',
                    'thailand',
                    'china',
                    'usa'
                ];

                $countries = collect(
                    $svc->getCountries()['data'] ?? []
                );

                $priority = $countries->filter(function ($c) use ($favorites) {

                    return in_array(
                        strtolower($c['name']),
                        $favorites
                    );
                });

                $others = $countries->reject(function ($c) use ($favorites) {

                    return in_array(
                        strtolower($c['name']),
                        $favorites
                    );
                });

                $countries = $priority
                    ->concat($others)
                    ->values();

                $perPage = 7;

                $currentCountries = $countries->slice(
                    ($page - 1) * $perPage,
                    $perPage
                );

                $buttons = [];

                foreach ($currentCountries as $country) {

                    $buttons[] = [
                        [
                            'text' => $country['name'],
                            'callback_data' => 'country_' . $country['id']
                        ]
                    ];
                }

                $nav = [];

                if ($page > 1) {

                    $nav[] = [
                        'text' => '⬅️ Prev',
                        'callback_data' =>
                            'country_page_' . ($page - 1)
                    ];
                }

                if ($countries->count() > ($page * $perPage)) {

                    $nav[] = [
                        'text' => '➡️ Next',
                        'callback_data' =>
                            'country_page_' . ($page + 1)
                    ];
                }

                if (!empty($nav)) {
                    $buttons[] = $nav;
                }

                $buttons[] = [
                    [
                        'text' => '🔍 Cari Negara',
                        'callback_data' => 'search_country'
                    ]
                ];

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/editMessageText",
                    [
                        'chat_id' => $chatId,
                        'message_id' => $callback['message']['message_id'],
                        'text' => "━━━━━━━━━━━━━━━
🌍 Pilih Negara
━━━━━━━━━━━━━━━",
                        'reply_markup' => json_encode([
                            'inline_keyboard' => $buttons
                        ])
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            /*
            |--------------------------------------------------------------------------
            | SEARCH COUNTRY
            |--------------------------------------------------------------------------
            */

            if ($data == 'search_country') {

                Cache::put(
                    'telegram_state_' . $telegramId,
                    'search_country',
                    now()->addMinutes(5)
                );

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' => '━━━━━━━━━━━━━━━
🔍 Kirim nama negara
━━━━━━━━━━━━━━━'
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            if (
                str_starts_with($data, 'country_') &&
                !str_starts_with($data, 'country_page_')
            ) {

                $countryId = str_replace('country_', '', $data);

                $svc = app(SmscodeService::class);

                $services = $svc->getServices($countryId)['data'] ?? [];
                $favorites = [
                    'whatsapp',
                    'gmail',
                    'telegram',
                    'shopee',
                    'facebook',
                    'discord',
                    'dana',
                    'tiktok'
                ];

                $services = collect($services);

                $priority = $services->filter(function ($s) use ($favorites) {

                    return collect($favorites)->contains(function ($fav) use ($s) {

                        return str_contains(
                            strtolower($s['name'] ?? ''),
                            $fav
                        );
                    });
                });

                $others = $services->reject(function ($s) use ($favorites) {

                    return collect($favorites)->contains(function ($fav) use ($s) {

                        return str_contains(
                            strtolower($s['name'] ?? ''),
                            $fav
                        );
                    });
                });

                $services = $priority
                    ->concat($others)
                    ->values();

                if ($services->isEmpty()) {

                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/answerCallbackQuery",
                        [
                            'callback_query_id' => $callbackId,
                            'text' => 'Service kosong'
                        ]
                    );

                    return response()->json([
                        'success' => true
                    ]);
                }

                $buttons = [];

                $page = 1;
                $perPage = 8;

                $currentServices = $services->slice(
                    ($page - 1) * $perPage,
                    $perPage
                );

                foreach ($currentServices as $service) {

                    $buttons[] = [
                        [
                            'text' => $service['name'],
                            'callback_data' => 'service_' . $countryId . '_' . $service['id']
                        ]
                    ];
                }

                $nav = [];

                if ($services->count() > ($page * $perPage)) {

                    $nav[] = [
                        'text' => '➡️ Next',
                        'callback_data' =>
                            'service_page_' . $countryId . '_2'
                    ];
                }

                if (!empty($nav)) {
                    $buttons[] = $nav;
                }
                $buttons[] = [
                    [
                        'text' => '🔍 Cari Layanan',
                        'callback_data' =>
                            'search_service_' . $countryId
                    ]
                ];

                $buttons[] = [
                    [
                        'text' => '⬅️ Kembali',
                        'callback_data' => 'country_page_1'
                    ]
                ];
                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/editMessageText",
                    [
                        'chat_id' => $chatId,

                        'text' => "━━━━━━━━━━━━━━━
📱 Pilih Layanan
━━━━━━━━━━━━━━━",
                        'message_id' => $callback['message']['message_id'],

                        'reply_markup' => json_encode([
                            'inline_keyboard' => $buttons
                        ])
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            /*
            |--------------------------------------------------------------------------
            | SEARCH SERVICE
            |--------------------------------------------------------------------------
            */

            if (str_starts_with($data, 'search_service_')) {

                $countryId = str_replace(
                    'search_service_',
                    '',
                    $data
                );

                Cache::put(
                    'telegram_state_' . $telegramId,
                    'search_service_' . $countryId,
                    now()->addMinutes(5)
                );

                Http::timeout(10)->post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' => '🔍 Kirim nama layanan'
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            /*
            |--------------------------------------------------------------------------
            | SERVICE PAGE
            |--------------------------------------------------------------------------
            */

            if (str_starts_with($data, 'service_page_')) {

                $explode = explode('_', $data);

                $countryId = $explode[2];
                $page = (int) $explode[3];

                $svc = app(SmscodeService::class);

                $favorites = [
                    'whatsapp',
                    'gmail',
                    'telegram',
                    'shopee',
                    'facebook',
                    'discord',
                    'dana',
                    'tiktok'
                ];

                $services = collect(
                    $svc->getServices($countryId)['data'] ?? []
                );

                $priority = $services->filter(function ($s) use ($favorites) {

                    return collect($favorites)->contains(function ($fav) use ($s) {

                        return str_contains(
                            strtolower($s['name'] ?? ''),
                            $fav
                        );
                    });
                });

                $others = $services->reject(function ($s) use ($favorites) {

                    return collect($favorites)->contains(function ($fav) use ($s) {

                        return str_contains(
                            strtolower($s['name'] ?? ''),
                            $fav
                        );
                    });
                });

                $services = $priority
                    ->concat($others)
                    ->values();

                $perPage = 8;

                $currentServices = $services->slice(
                    ($page - 1) * $perPage,
                    $perPage
                );

                $buttons = [];

                foreach ($currentServices as $service) {

                    $buttons[] = [
                        [
                            'text' => $service['name'],
                            'callback_data' =>
                                'service_' . $countryId . '_' . $service['id']
                        ]
                    ];
                }

                $nav = [];

                if ($page > 1) {

                    $nav[] = [
                        'text' => '⬅️ Prev',
                        'callback_data' =>
                            'service_page_' . $countryId . '_' .
                            ($page - 1)
                    ];
                }

                if ($services->count() > ($page * $perPage)) {

                    $nav[] = [
                        'text' => '➡️ Next',
                        'callback_data' =>
                            'service_page_' . $countryId . '_' .
                            ($page + 1)
                    ];
                }

                if (!empty($nav)) {
                    $buttons[] = $nav;
                }
                $buttons[] = [
                    [
                        'text' => '🔍 Cari Layanan',
                        'callback_data' =>
                            'search_service_' . $countryId
                    ]
                ];

                $buttons[] = [
                    [
                        'text' => '⬅️ Kembali',
                        'callback_data' => 'country_page_1'
                    ]
                ];
                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/editMessageText",
                    [
                        'chat_id' => $chatId,
                        'message_id' => $callback['message']['message_id'],
                        'text' => "━━━━━━━━━━━━━━━
📱 Pilih Layanan
━━━━━━━━━━━━━━━",
                        'reply_markup' => json_encode([
                            'inline_keyboard' => $buttons
                        ])
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            /*
            |--------------------------------------------------------------------------
            | SELECT SERVICE
            |--------------------------------------------------------------------------
            */

            if (
                str_starts_with($data, 'service_') &&
                !str_starts_with($data, 'service_page_')
            ) {

                $explode = explode('_', $data);

                $countryId = $explode[1];
                $serviceId = $explode[2];

                $svc = app(SmscodeService::class);

                $products = $svc->getProducts($countryId, $serviceId)['data'] ?? [];

                if (collect($products)->isEmpty()) {

                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/answerCallbackQuery",
                        [
                            'callback_query_id' => $callbackId,
                            'text' => 'Server kosong'
                        ]
                    );

                    return response()->json([
                        'success' => true
                    ]);
                }


                $products = collect($products);
                $buttons = [];

                $page = 1;
                $perPage = 8;

                $currentProducts = $products->slice(
                    ($page - 1) * $perPage,
                    $perPage
                );

                foreach ($currentProducts as $index => $product) {

                    $buttons[] = [
                        [
                            'text' => 'Server ' . ($index + 1) . ' - Rp ' . number_format($product['harga'], 0, ',', '.'),
                            'callback_data' =>
                                'confirm_' . $countryId . '_' . $serviceId . '_' . $product['id'] . '_' . $product['harga']
                        ]
                    ];
                }

                if ($products->count() > ($page * $perPage)) {

                    $buttons[] = [
                        [
                            'text' => '➡️ Selanjutnya',
                            'callback_data' =>
                                'server_page_' . $countryId . '_' . $serviceId . '_2'
                        ]
                    ];
                }

                $buttons[] = [
                    [
                        'text' => '⬅️ Kembali',
                        'callback_data' => 'country_' . $countryId
                    ]
                ];

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/editMessageText",
                    [
                        'chat_id' => $chatId,
                        'message_id' => $callback['message']['message_id'],

                        'text' => "━━━━━━━━━━━━━━━
🖥 Pilih Server
━━━━━━━━━━━━━━━",

                        'reply_markup' => json_encode([
                            'inline_keyboard' => $buttons
                        ])
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }



            /*
            |--------------------------------------------------------------------------
            | SERVER PAGE
            |--------------------------------------------------------------------------
            */

            if (str_starts_with($data, 'server_page_')) {

                $explode = explode('_', $data);

                $countryId = $explode[2];
                $serviceId = $explode[3];
                $page = (int) $explode[4];

                $svc = app(SmscodeService::class);

                $products = collect(
                    $svc->getProducts($countryId, $serviceId)['data'] ?? []
                );

                $perPage = 8;

                $currentProducts = $products->slice(
                    ($page - 1) * $perPage,
                    $perPage
                );

                $buttons = [];

                foreach ($currentProducts as $index => $product) {

                    $buttons[] = [
                        [
                            'text' =>
                                'Server ' . (($page - 1) * $perPage + $index + 1) .
                                ' - Rp ' . number_format($product['harga'], 0, ',', '.'),
                            'callback_data' =>
                                'confirm_' . $countryId . '_' .
                                $serviceId . '_' .
                                $product['id'] . '_' .
                                $product['harga']
                        ]
                    ];
                }

                $nav = [];

                if ($page > 1) {

                    $nav[] = [
                        'text' => '⬅️ Prev',
                        'callback_data' =>
                            'server_page_' . $countryId . '_' .
                            $serviceId . '_' .
                            ($page - 1)
                    ];
                }

                if ($products->count() > ($page * $perPage)) {

                    $nav[] = [
                        'text' => '➡️ Next',
                        'callback_data' =>
                            'server_page_' . $countryId . '_' .
                            $serviceId . '_' .
                            ($page + 1)
                    ];
                }

                if (!empty($nav)) {
                    $buttons[] = $nav;
                }
                $buttons[] = [
                    [
                        'text' => '⬅️ Kembali',
                        'callback_data' =>
                            'country_' . $countryId
                    ]
                ];
                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/editMessageText",
                    [
                        'chat_id' => $chatId,
                        'message_id' => $callback['message']['message_id'],
                        'text' => "━━━━━━━━━━━━━━━
🖥 Pilih Server
━━━━━━━━━━━━━━━",
                        'reply_markup' => json_encode([
                            'inline_keyboard' => $buttons
                        ])
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            if (str_starts_with($data, 'confirm_')) {

                $explode = explode('_', $data);

                $countryId = $explode[1];
                $serviceId = $explode[2];
                $productId = $explode[3];
                $productPrice = $explode[4] ?? 0;

                $svc = app(SmscodeService::class);

                $country = collect(
                    $svc->getCountries()['data'] ?? []
                )->firstWhere('id', (int) $countryId);

                $service = collect(
                    $svc->getServices($countryId)['data'] ?? []
                )->firstWhere('id', (int) $serviceId);

                $products = collect(
    $svc->getProducts($countryId, $serviceId)['data'] ?? []
);

$product = $products->firstWhere('id', (int) $productId);

$serverName = 'Server';

if ($product) {
    $serverIndex = $products->search(function ($item) use ($productId) {
        return $item['id'] == $productId;
    });

    $serverName = 'Server ' . ($serverIndex + 1);
}

Http::post(
    "https://api.telegram.org/bot{$tokenBot}/editMessageText",
    [
        'chat_id' => $chatId,
        'message_id' => $callback['message']['message_id'],

        'text' =>
            "⚠️ Konfirmasi Pembelian
━━━━━━━━━━━━━━━
🌍 Negara : " . ($country['name'] ?? 'Unknown') . "
📱 Layanan : " . ($service['name'] ?? 'Unknown') . "
🖥 Server : {$serverName}
💰 Harga : Rp " . number_format($productPrice, 0, ',', '.') . "
━━━━━━━━━━━━━━━
Apakah anda yakin ingin
melanjutkan pembelian?
━━━━━━━━━━━━━━━",

        'reply_markup' => json_encode([
            'inline_keyboard' => [

                [
                    [
                        'text' => '✅ Ya Buat Order',
                        'callback_data' =>
                            'product_' . $countryId . '_' . $serviceId . '_' . $productId
                    ]
                ],

                [
                    [
                        'text' => '⬅️ Kembali',
                        'callback_data' =>
                            'service_' . $countryId . '_' . $serviceId
                    ]
                ]

            ]
        ])
    ]
);

                return response()->json([
                    'success' => true
                ]);
            }

            if (str_starts_with($data, 'cancel_order_')) {

                $orderId = str_replace(
                    'cancel_order_',
                    '',
                    $data
                );

                $order = Order::find($orderId);

                if (!$order || $order->user_id != $user->id) {

                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/answerCallbackQuery",
                        [
                            'callback_query_id' => $callbackId,
                            'text' => 'Order tidak ditemukan'
                        ]
                    );

                    return response()->json([
                        'success' => true
                    ]);
                }

                $meta = Cache::get('telegram_cancel_' . $orderId);

                // 🔥 tombol expired setelah 20 menit
                if (!$meta || now()->timestamp >= $meta['expired_at']) {

                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/editMessageReplyMarkup",
                        [
                            'chat_id' => $chatId,
                            'message_id' => $callback['message']['message_id'],
                            'reply_markup' => json_encode([
                                'inline_keyboard' => []
                            ])
                        ]
                    );

                    return response()->json([
                        'success' => true
                    ]);
                }

                // ⏳ belum 3 menit
                if (now()->timestamp < $meta['cancel_at']) {

                    $wait = $meta['cancel_at'] - now()->timestamp;

                    $minutes = floor($wait / 60);
                    $seconds = $wait % 60;

                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/answerCallbackQuery",
                        [
                            'callback_query_id' => $callbackId,

                            'text' =>
                                "⏳ Order belum bisa dibatalkan.
Silakan tunggu {$minutes} menit {$seconds} detik lagi.",

                            'show_alert' => true
                        ]
                    );

                    return response()->json([
                        'success' => true
                    ]);
                }

                Auth::login($user);

                $fakeRequest = HttpRequest::create(
                    '/api/v2/cancel',
                    'POST',
                    [
                        'order_id' => $orderId
                    ]
                );

                $fakeRequest->headers->set(
                    'Accept',
                    'application/json'
                );

                app()->instance('request', $fakeRequest);

                $response = app(OrderV2Controller::class)
                    ->apiCancel($fakeRequest);

                $result = $response->getData(true);
                \Log::info('TELEGRAM CANCEL RESULT', $result);

                Auth::logout();

                if (!($result['success'] ?? false)) {

                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/answerCallbackQuery",
                        [
                            'callback_query_id' => $callbackId,
                            'text' => $result['message'] ?? 'Gagal cancel',
                            'show_alert' => true
                        ]
                    );

                    return response()->json([
                        'success' => true
                    ]);
                }

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/editMessageText",
                    [
                        'chat_id' => $chatId,
                        'message_id' => $callback['message']['message_id'],

                        'text' =>
                            "❌ Pembelian Dibatalkan
━━━━━━━━━━━━━━━
🆔 Order ID : {$order->id}
💰 Refund : Rp " . number_format($order->harga, 0, ',', '.') . "
━━━━━━━━━━━━━━━
Saldo telah dikembalikan.
━━━━━━━━━━━━━━━"
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            /*
            |--------------------------------------------------------------------------
            | CREATE ORDER
            |--------------------------------------------------------------------------
            */

            if (str_starts_with($data, 'product_')) {

                $explode = explode('_', $data);

                $countryId = $explode[1];
                $serviceId = $explode[2];
                $productId = $explode[3];

                $svc = app(SmscodeService::class);

// Negara
$country = collect(
    $svc->getCountries()['data'] ?? []
)->firstWhere('id', (int) $countryId);

// Layanan
$service = collect(
    $svc->getServices($countryId)['data'] ?? []
)->firstWhere('id', (int) $serviceId);

// Server
$products = collect(
    $svc->getProducts($countryId, $serviceId)['data'] ?? []
);

$product = $products->firstWhere('id', (int) $productId);

$serverName = 'Server';

if ($product) {
    $serverIndex = $products->search(function ($item) use ($productId) {
        return $item['id'] == $productId;
    });

    $serverName = 'Server ' . ($serverIndex + 1);
}

                Auth::login($user);

                $fakeRequest = HttpRequest::create(
                    '/api/order',
                    'POST',
                    [
                        'country_id' => $countryId,
                        'service_id' => $serviceId,
                        'product_id' => $productId,
                    ]
                );

                $fakeRequest->headers->set(
                    'Accept',
                    'application/json'
                );

                app()->instance('request', $fakeRequest);

                $response = app(OrderV2Controller::class)
                    ->apiOrder($fakeRequest);

                $result = $response->getData(true);

                if (!($result['success'] ?? false)) {

                    Auth::logout();

                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/editMessageText",
                        [
                            'chat_id' => $chatId,
                            'message_id' => $callback['message']['message_id'],
                            'text' => '❌ ' . $result['message']
                        ]
                    );

                    return response()->json([
                        'success' => true
                    ]);
                }

                $order = $result['data'];

                $cancelAllowed = now()->addMinutes(3)->timestamp;
                $expiredAt = now()->addMinutes(20)->timestamp;

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/editMessageText",
                    [
                        'chat_id' => $chatId,
                        'message_id' => $callback['message']['message_id'],

                        'text' =>
"✅ Pembelian Berhasil
━━━━━━━━━━━━━━━
🆔 Order ID : {$order['order_id']}
🌍 Negara : " . ($country['name'] ?? '-') . "
📱 Layanan : " . ($service['name'] ?? '-') . "
🖥 Server : {$serverName}
☎️ Nomor : {$order['number']}
📌 Status : {$order['status']}
━━━━━━━━━━━━━━━
⏳ Menunggu OTP...
⚠️ Pembatalan tersedia setelah
3 menit pembelian.
━━━━━━━━━━━━━━━",

                        'reply_markup' => json_encode([
                            'inline_keyboard' => [

                                [
                                    [
                                        'text' => '📋 Salin Nomor',
                                        'copy_text' => [
                                            'text' => $order['number']
                                        ]
                                    ]
                                ],

                                [
                                    [
                                        'text' => '❌ Batalkan Pembelian',
                                        'callback_data' => 'cancel_order_' . $order['order_id']
                                    ]
                                ]

                            ]
                        ])
                    ]
                );

                Cache::put(
                    'telegram_cancel_' . $order['order_id'],
                    [
                        'cancel_at' => $cancelAllowed,
                        'expired_at' => $expiredAt,
                    ],
                    now()->addMinutes(20)
                );

                Auth::logout();

                return response()->json([
                    'success' => true
                ]);
            }

            /*
            |--------------------------------------------------------------------------
            | DEPOSIT PAGE
            |--------------------------------------------------------------------------
            */

            if (str_starts_with($data, 'deposit_page_')) {

                $page = (int) str_replace(
                    'deposit_page_',
                    '',
                    $data
                );

                $perPage = 4;

                $deposits = Deposit::where('user_id', $user->id)
                    ->latest()
                    ->skip(($page - 1) * $perPage)
                    ->take($perPage)
                    ->get();

                if ($deposits->isEmpty()) {

                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/answerCallbackQuery",
                        [
                            'callback_query_id' => $callbackId,
                            'text' => 'Data tidak ditemukan'
                        ]
                    );

                    return response()->json([
                        'success' => true
                    ]);
                }

                $caption = "━━━━━━━━━━━━━━━
💰 Riwayat Deposit
━━━━━━━━━━━━━━━
(Page {$page})\n\n";

                foreach ($deposits as $deposit) {

                    $caption .=
                        "━━━━━━━━━━━━━━━
🧾 Trx ID : {$deposit->trx_id}
💵 Nominal : Rp " . number_format($deposit->amount, 0, ',', '.') . "
📌 Status : {$deposit->status}
🕒 Waktu : " . $deposit->created_at->format('d/m/Y H:i') . "
";
                }

                $buttons = [];

                $total = Deposit::where('user_id', $user->id)->count();

                $nav = [];

                if ($page > 1) {

                    $nav[] = [
                        'text' => '⬅️ Prev',
                        'callback_data' =>
                            'deposit_page_' . ($page - 1)
                    ];
                }

                if ($total > ($page * $perPage)) {

                    $nav[] = [
                        'text' => '➡️ Next',
                        'callback_data' =>
                            'deposit_page_' . ($page + 1)
                    ];
                }

                if (!empty($nav)) {
                    $buttons[] = $nav;
                }

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/editMessageText",
                    [
                        'chat_id' => $chatId,
                        'message_id' => $callback['message']['message_id'],
                        'text' => $caption,

                        'reply_markup' => json_encode([
                            'inline_keyboard' => $buttons
                        ])
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            /*

            |--------------------------------------------------------------------------
            | ORDER PAGE
            |--------------------------------------------------------------------------
            */
            if (str_starts_with($data, 'order_page_')) {
                $page = (int) str_replace(
                    'order_page_',
                    '',
                    $data
                );
                $perPage = 4;
                $orders = Order::where('user_id', $user->id)
                    ->latest()
                    ->skip(($page - 1) * $perPage)
                    ->take($perPage)
                    ->get();
                if ($orders->isEmpty()) {
                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/answerCallbackQuery",
                        [
                            'callback_query_id' => $callbackId,
                            'text' => 'Data tidak ditemukan'
                        ]
                    );
                    return response()->json([
                        'success' => true
                    ]);
                }
                $caption = "━━━━━━━━━━━━━━━
🛒 Riwayat Order OTP
━━━━━━━━━━━━━━━
(Page {$page})\n\n";

                $buttons = [];

                foreach ($orders as $order) {

                    $statusEmoji = match ($order->status) {
                        'SUCCESS' => '✅',
                        'PENDING' => '⏳',
                        'FAILED' => '❌',
                        'CANCELED' => '🚫',
                        default => '📌'
                    };

                    $caption .=
                        "━━━━━━━━━━━━━━━
🆔 Order : {$order->id}
━━━━━━━━━━━━━━━
📱 Layanan : {$order->layanan_nama}
☎️ Nomor : {$order->number}" .
                        ($order->status === 'SUCCESS'
                            ? "\n🔑 OTP: " . ($order->otp ?: '-')
                            : '') . "
💰 Harga : Rp " . number_format($order->harga, 0, ',', '.') . "
{$statusEmoji} Status : {$order->status}
🕒 Waktu : " . $order->created_at->format('d/m/Y H:i') . "

";

                    if (
                        $order->status === 'PENDING' &&
                        Cache::has('telegram_cancel_' . $order->id)
                    ) {

                        $buttons[] = [
                            [
                                'text' => '❌ Cancel #' . $order->id,
                                'callback_data' => 'cancel_order_' . $order->id
                            ]
                        ];
                    }
                }
                $total = Order::where('user_id', $user->id)->count();
                $nav = [];
                if ($page > 1) {
                    $nav[] = [
                        'text' => '⬅️ Prev',
                        'callback_data' =>
                            'order_page_' . ($page - 1)
                    ];
                }
                if ($total > ($page * $perPage)) {
                    $nav[] = [
                        'text' => '➡️ Next',
                        'callback_data' =>
                            'order_page_' . ($page + 1)
                    ];
                }
                if (!empty($nav)) {
                    $buttons[] = $nav;
                }
                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/editMessageText",
                    [
                        'chat_id' => $chatId,
                        'message_id' => $callback['message']['message_id'],
                        'text' => $caption,
                        'reply_markup' => json_encode([
                            'inline_keyboard' => $buttons
                        ])
                    ]
                );
                return response()->json([
                    'success' => true
                ]);
            }
            /*
            |--------------------------------------------------------------------------
            | BACK HOME
            |--------------------------------------------------------------------------
            */

            if ($data == 'back_home') {

                $caption =
                "𝙷𝚊𝚕𝚕𝚘 {$user->name}, 𝚂𝚎𝚕𝚊𝚖𝚊𝚝 𝙳𝚊𝚝𝚊𝚗𝚐 𝚍𝚒 𝙽𝚞𝚜𝚊 𝙾𝚃𝙿👋
━━━━━━━━━━━━━━━
👤 ɴᴀᴍᴀ : {$user->name}
💰 ꜱᴀʟᴅᴏ : ʀᴘ " . number_format($user->balance ?? 0, 0, ',', '.') . "
🆔 ᴜꜱᴇʀ ɪᴅ : {$user->id}
━━━━━━━━━━━━━━━
ᴘɪʟɪʜ ᴍᴇɴᴜ ᴘᴀᴅᴀ ᴛᴏᴍʙᴏʟ ᴋᴇʏʙᴏᴀʀᴅ
━━━━━━━━━━━━━━━
𝐈𝐍𝐅𝐎𝐑𝐌𝐀𝐒𝐈:
ᴀɴᴅᴀ ᴅᴀᴘᴀᴛ ᴍᴇɴɢᴀᴋꜱᴇꜱ ᴠᴇʀꜱɪ ᴡᴇʙꜱɪᴛᴇ
ꜱᴇᴄᴀʀᴀ ᴄᴇᴘᴀᴛ ᴅᴇɴɢᴀɴ ᴋʟɪᴋ ᴛᴏᴍʙᴏʟ
ʟᴏɢɪɴ ᴡᴇʙꜱɪᴛᴇ ʙᴇʀɢᴀʙᴜɴɢ ᴋᴇ ᴅᴀʟᴀᴍ
ᴄʜᴀɴɴᴇʟ ᴋᴀᴍɪ ᴜɴᴛᴜᴋ ᴍᴇɴᴇʀɪᴍᴀ
ɪɴꜰᴏʀᴍᴀꜱɪ ᴛᴇʀʙᴀʀᴜ. ꜱᴇᴍᴜᴀ ᴛʀᴀɴꜱᴀᴋꜱɪ
ᴀɴᴅᴀ ᴛᴇʀᴊᴀᴍɪɴ ᴋᴇᴀᴍᴀɴᴀɴɴʏᴀ.
━━━━━━━━━━━━━━━";

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/editMessageText",
                    [
                        'chat_id' => $chatId,
                        'message_id' => $callback['message']['message_id'],

                        'text' => $caption
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            /*
        |--------------------------------------------------------------------------
        | CHECK STATUS DEPOSIT
        |--------------------------------------------------------------------------
        */

            if (str_starts_with($data, 'check_')) {

                $trxId = str_replace('check_', '', $data);

                $deposit = Deposit::where('trx_id', $trxId)->first();

                if (!$deposit) {

                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/answerCallbackQuery",
                        [
                            'callback_query_id' => $callbackId,
                            'text' => 'Deposit tidak ditemukan.',
                            'show_alert' => true
                        ]
                    );

                    return response()->json([
                        'success' => true
                    ]);
                }

                // =========================
                // SUDAH PAID
                // =========================
                if ($deposit->status == 'PAID') {

                    // hapus QRIS lama
                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/deleteMessage",
                        [
                            'chat_id' => $chatId,
                            'message_id' => $callback['message']['message_id']
                        ]
                    );

                    // kirim pesan sukses baru
                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                        [
                            'chat_id' => $chatId,

                            'text' =>
                                "✅ Deposit Berhasil
━━━━━━━━━━━━━━━
🧾 Invoice:
{$deposit->trx_id}

💰 Nominal: Rp " . number_format($deposit->amount, 0, ',', '.') . "
📌 Status: PAID
━━━━━━━━━━━━━━━
Saldo berhasil ditambahkan.",

                            'reply_markup' => json_encode([
                                'inline_keyboard' => [

                                    [
                                        [
                                            'text' => '🏠 Home',
                                            'callback_data' => 'back_home'
                                        ]
                                    ]

                                ]
                            ])
                        ]
                    );

                } else {

                    // popup kecil
                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/answerCallbackQuery",
                        [
                            'callback_query_id' => $callbackId,
                            'text' => '⏳ Pembayaran belum diterima.',
                            'show_alert' => false
                        ]
                    );
                }

                return response()->json([
                    'success' => true
                ]);
            }
        }

        if (!isset($update['message'])) {
            return response()->json([
                'ok' => true
            ]);
        }

        $message = $update['message'];

        $chatId = $message['chat']['id'];

        $text = trim($message['text'] ?? '');

        /*
        |--------------------------------------------------------------------------
        | DATA USER TELEGRAM
        |--------------------------------------------------------------------------
        */

        $telegramId = $message['from']['id'];

        $telegramName =
            $message['from']['first_name']
            ?? $message['from']['username']
            ?? 'Telegram User';

        $telegramUsername =
            $message['from']['username']
            ?? null;
        $user = User::where(
            'telegram_id',
            $telegramId
        )->first();
        /*
        |--------------------------------------------------------------------------
        | FORCE JOIN CHANNEL
        |--------------------------------------------------------------------------
        */

        if (
            $user &&
            !$this->isJoinedChannel($telegramId)
        ) {

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,
                    'text' =>
                        "━━━━━━━━━━━━━━━
❌ Akses Anda Ditolak!
━━━━━━━━━━━━━━━
Silahkan Bergabung Ke Dalam
Channel Terlebih Dahulu.
━━━━━━━━━━━━━━━",

                    'reply_markup' => json_encode([
                        'inline_keyboard' => [

                            [
                                [
                                    'text' => '📢 Gabung Ke Channel',
                                    'url' => 'https://t.me/nusaotp_official'
                                ]
                            ],

                            [
                                [
                                    'text' => '✅ Sudah Bergabung? Klik Disini.',
                                    'url' => 'https://t.me/' . env('TELEGRAM_BOT_USERNAME') . '?start=checkjoin'
                                ]
                            ]

                        ]
                    ])
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }
        /*
        |--------------------------------------------------------------------------
        | BLOCK UNREGISTERED USER
        |--------------------------------------------------------------------------
        */

        if (
            !$user &&
            $text !== '/start' &&
            $text !== '/start checkjoin' &&
            !str_starts_with($text, '/start ref_') &&
            !preg_match('/^\/start login_(.+)$/', $text)
        ) {

            \Log::warning('Telegram user not found', [
                'telegram_id' => $telegramId,
                'text' => $text,
            ]);

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,
                    'text' =>
                        "━━━━━━━━━━━━━━━
❌ Akun Belum Terhubung.
━━━━━━━━━━━━━━━
Silahkan Ketik /start
Terlebih Dahulu.
━━━━━━━━━━━━━━━"
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }
        /*
        |--------------------------------------------------------------------------
        | FIRST START VALIDATION
        |--------------------------------------------------------------------------
        */

        if (
            !$user &&
            (
                $text == '/start' ||
                str_starts_with($text, '/start ref_')
            )
        ) {
            if (!$this->isJoinedChannel($telegramId)) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' =>
                            "━━━━━━━━━━━━━━━
❌ Akses Anda Ditolak! 
━━━━━━━━━━━━━━━
Silahkan Bergabung Ke Dalam
Channel Terlebih Dahulu.
━━━━━━━━━━━━━━━",

                        'reply_markup' => json_encode([
                            'inline_keyboard' => [

                                [
                                    [
                                        'text' => '📢 Gabung Ke Channel',
                                        'url' => 'https://t.me/nusaotp_official'
                                    ]
                                ],

                                [
                                    [
                                        'text' => '✅ Sudah Bergabung? Klik Disini.',
                                        'url' => 'https://t.me/' . env('TELEGRAM_BOT_USERNAME') . '?start=checkjoin'
                                    ]
                                ]

                            ]
                        ])
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            // ambil referral code jika ada
            $refCode = null;

            if (
                preg_match('/^\/start ref_(.+)$/', $text, $match)
            ) {
                $refCode = trim($match[1]);

                Cache::put(
                    'telegram_ref_' . $telegramId,
                    $refCode,
                    now()->addDays(1)
                );
            }

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' =>
                        "Hallo {$telegramName}, Selamat Datang Di Nusa OTP 👋
━━━━━━━━━━━━━━━
Apakah kamu sudah memiliki
akun di website NusaOTP?
━━━━━━━━━━━━━━━",

                    'reply_markup' => json_encode([
                        'inline_keyboard' => [

                            [
                                [
                                    'text' => '✅ Sudah Pernah Daftar',
                                    'callback_data' => 'has_account'
                                ]
                            ],

                            [
                                [
                                    'text' => '🆕 Belum Pernah Daftar',
                                    'callback_data' => 'new_account'
                                ]
                            ]

                        ]
                    ])
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }
        /*
        |--------------------------------------------------------------------------
        | RESET STATE MENU UTAMA
        |--------------------------------------------------------------------------
        */

        $mainMenus = [
            '🏠 Home',
            '🛒 Order',
            '💰 Deposit',
            '👥 Referral',
            '📜 Riwayat',
            '💰 Riwayat Deposit',
            '🛒 Riwayat Order',
            '🌐 Login Website',
        ];

        if (in_array($text, $mainMenus)) {

            Cache::forget(
                'telegram_state_' . $telegramId
            );
        }


        /*
        |--------------------------------------------------------------------------
        | DATA USER TELEGRAM
        |--------------------------------------------------------------------------
        */


        $user = User::where(
            'telegram_id',
            $telegramId
        )->first();
        /*
        |--------------------------------------------------------------------------
        | FORCE JOIN CHANNEL
        |--------------------------------------------------------------------------
        */

        if (
            $user &&
            !$this->isJoinedChannel($telegramId)
        ) {

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,
                    'text' =>
                        "━━━━━━━━━━━━━━━
❌ Akses Anda Ditolak! 
━━━━━━━━━━━━━━━
Silahkan Bergabung Ke Dalam
Channel Terlebih Dahulu.
━━━━━━━━━━━━━━━",

                    'reply_markup' => json_encode([
                        'inline_keyboard' => [

                            [
                                [
                                    'text' => '📢 Gabung Ke Channel',
                                    'url' => 'https://t.me/nusaotp_official'
                                ]
                            ],

                            [
                                [
                                    'text' => '✅ Sudah Bergabung? Klik Disini.',
                                    'url' => 'https://t.me/' . env('TELEGRAM_BOT_USERNAME') . '?start=checkjoin'
                                ]
                            ]

                        ]
                    ])
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }
        /*
        |--------------------------------------------------------------------------
        | FIRST START VALIDATION
        |--------------------------------------------------------------------------
        */

        if (
            !$user &&
            (
                $text == '/start' ||
                str_starts_with($text, '/start ref_')
            )
        ) {
            if (!$this->isJoinedChannel($telegramId)) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' =>
                            "━━━━━━━━━━━━━━━
❌ Akses Anda Ditolak! 
━━━━━━━━━━━━━━━
Silahkan Bergabung Ke Dalam
Channel Terlebih Dahulu.
━━━━━━━━━━━━━━━",

                        'reply_markup' => json_encode([
                            'inline_keyboard' => [

                                [
                                    [
                                        'text' => '📢 Gabung Ke Channel',
                                        'url' => 'https://t.me/nusaotp_official'
                                    ]
                                ],

                                [
                                    [
                                        'text' => '✅ Sudah Bergabung? Klik Disini.',
                                        'url' => 'https://t.me/' . env('TELEGRAM_BOT_USERNAME') . '?start=checkjoin'
                                    ]
                                ]

                            ]
                        ])
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }
            // ambil referral code jika ada
            $refCode = null;

            if (
                preg_match('/^\/start ref_(.+)$/', $text, $match)
            ) {
                $refCode = trim($match[1]);

                Cache::put(
                    'telegram_ref_' . $telegramId,
                    $refCode,
                    now()->addDays(1)
                );
            }

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' =>
                        "Hallo {$telegramName}, Selamat Datang DI Nusa OTP 👋
━━━━━━━━━━━━━━━
Apakah kamu sudah memiliki
akun di website NusaOTP?
━━━━━━━━━━━━━━━",

                    'reply_markup' => json_encode([
                        'inline_keyboard' => [

                            [
                                [
                                    'text' => '✅ Sudah Pernah Daftar',
                                    'callback_data' => 'has_account'
                                ]
                            ],

                            [
                                [
                                    'text' => '🆕 Belum Pernah Daftar',
                                    'callback_data' => 'new_account'
                                ]
                            ]

                        ]
                    ])
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }

        /*
        |--------------------------------------------------------------------------
        | CHECK JOIN CHANNEL
        |--------------------------------------------------------------------------
        */

        if ($text == '/start checkjoin') {

            if ($this->isJoinedChannel($telegramId)) {

                // kalau belum punya akun
                if (!$user) {

                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                        [
                            'chat_id' => $chatId,
                            'text' =>
                                "━━━━━━━━━━━━━━━✅ Terima kasih sudah bergabung.
━━━━━━━━━━━━━━━
Apakah kamu sudah memiliki
akun di website NusaOTP?
━━━━━━━━━━━━━━━",

                            'reply_markup' => json_encode([
                                'inline_keyboard' => [

                                    [
                                        [
                                            'text' => '✅ Sudah Pernah Daftar',
                                            'callback_data' => 'has_account'
                                        ]
                                    ],

                                    [
                                        [
                                            'text' => '🆕 Belum Pernah Daftar',
                                            'callback_data' => 'new_account'
                                        ]
                                    ]

                                ]
                            ])
                        ]
                    );

                } else {

                    Http::post(
                        "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                        [
                            'chat_id' => $chatId,

                            'text' =>
                                "━━━━━━━━━━━━━━━
✅ Terima kasih sudah bergabung.
Silahkan klik tombol Home
untuk melanjutkan.
━━━━━━━━━━━━━━━",

                            'reply_markup' => [
                                'keyboard' => [

                                    [
                                        ['text' => '🏠 Home']
                                    ]

                                ],

                                'resize_keyboard' => true,
                                'one_time_keyboard' => false
                            ]
                        ]
                    );
                }
            } else {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' => "❌ Anda masih belum bergabung ke channel."
                    ]
                );

            }

            return response()->json([
                'success' => true
            ]);
        }

        /*
        |--------------------------------------------------------------------------
        | LOGIN WEBSITE
        |--------------------------------------------------------------------------
        */

        if (preg_match('/^\/start login_(.+)$/', $text, $match)) {

            $loginToken = $match[1];

            Cache::put(
                'telegram_login_' . $loginToken,
                [
                    'telegram_id' => $telegramId,
                    'name' => $telegramName,
                    'username' => $telegramUsername,
                ],
                now()->addMinutes(5)
            );

            $loginUrl = url('/telegram/login/' . $loginToken);

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' =>
                        "━━━━━━━━━━━━━━━
🔐 Login NusaOTP
━━━━━━━━━━━━━━━
Klik tombol dibawah untuk
masuk ke akun anda.
━━━━━━━━━━━━━━━",

                    'reply_markup' => [
                        'inline_keyboard' => [

                            [
                                [
                                    'text' => '🔐 Masuk ke Web NusaOTP',
                                    'url' => $loginUrl
                                ]
                            ],

                            [
                                [
                                    'text' => '📋 Copy Link Login',
                                    'copy_text' => [
                                        'text' => $loginUrl
                                    ]
                                ]
                            ]

                        ]
                    ]
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }

        /*
        |--------------------------------------------------------------------------
        | HOME MENU
        |--------------------------------------------------------------------------
        */

        if (
            $text == '/start' ||
            $text == '🏠 Home'
        ) {

            $caption =
                "𝙷𝚊𝚕𝚕𝚘 {$user->name}, 𝚂𝚎𝚕𝚊𝚖𝚊𝚝 𝙳𝚊𝚝𝚊𝚗𝚐 𝚍𝚒 𝙽𝚞𝚜𝚊 𝙾𝚃𝙿👋
━━━━━━━━━━━━━━━
👤 ɴᴀᴍᴀ : {$user->name}
💰 ꜱᴀʟᴅᴏ : ʀᴘ " . number_format($user->balance ?? 0, 0, ',', '.') . "
🆔 ᴜꜱᴇʀ ɪᴅ : {$user->id}
━━━━━━━━━━━━━━━
ᴘɪʟɪʜ ᴍᴇɴᴜ ᴘᴀᴅᴀ ᴛᴏᴍʙᴏʟ ᴋᴇʏʙᴏᴀʀᴅ
━━━━━━━━━━━━━━━
𝐈𝐍𝐅𝐎𝐑𝐌𝐀𝐒𝐈:
ᴀɴᴅᴀ ᴅᴀᴘᴀᴛ ᴍᴇɴɢᴀᴋꜱᴇꜱ ᴠᴇʀꜱɪ ᴡᴇʙꜱɪᴛᴇ
ꜱᴇᴄᴀʀᴀ ᴄᴇᴘᴀᴛ ᴅᴇɴɢᴀɴ ᴋʟɪᴋ ᴛᴏᴍʙᴏʟ
ʟᴏɢɪɴ ᴡᴇʙꜱɪᴛᴇ ʙᴇʀɢᴀʙᴜɴɢ ᴋᴇ ᴅᴀʟᴀᴍ
ᴄʜᴀɴɴᴇʟ ᴋᴀᴍɪ ᴜɴᴛᴜᴋ ᴍᴇɴᴇʀɪᴍᴀ
ɪɴꜰᴏʀᴍᴀꜱɪ ᴛᴇʀʙᴀʀᴜ. ꜱᴇᴍᴜᴀ ᴛʀᴀɴꜱᴀᴋꜱɪ
ᴀɴᴅᴀ ᴛᴇʀᴊᴀᴍɪɴ ᴋᴇᴀᴍᴀɴᴀɴɴʏᴀ.
━━━━━━━━━━━━━━━";

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' => $caption,

                    'reply_markup' => [
                        'keyboard' => [

                            [
                                ['text' => '🛒 Order'],
                                ['text' => '💰 Deposit'],
                                ['text' => '📜 Riwayat']
                            ],

                            [
                                ['text' => '👥 Referral'],
                                ['text' => '🌐 Login Web'],
                                ['text' => '🖥️ Monitoring']
                            ],

                            [
                                ['text' => '📢 Channel'],
                                ['text' => '👨‍💻 Admin']
                            ],
                            [
                                ['text' => 'ℹ️ Media Sosial'],
                                ['text' => '🚀 Daftar Reseller']
                            ]

                        ],

                        'resize_keyboard' => true
                    ]
                ]
            );
            return response()->json([
                'success' => true
            ]);
        }


        /*
 |--------------------------------------------------------------------------
 | ORDER OTP
 |--------------------------------------------------------------------------
 */

        if ($text == '🛒 Order') {

            $svc = app(SmscodeService::class);

            $favorites = [
                'indonesia',
                'malaysia',
                'philippines',
                'kenya',
                'thailand',
                'china',
                'usa'
            ];

            $countries = collect(
                $svc->getCountries()['data'] ?? []
            );

            $priority = $countries->filter(function ($c) use ($favorites) {
                return in_array(
                    strtolower($c['name']),
                    $favorites
                );
            });

            $others = $countries->reject(function ($c) use ($favorites) {
                return in_array(
                    strtolower($c['name']),
                    $favorites
                );
            });

            $countries = $priority
                ->concat($others)
                ->values();

            if ($countries->isEmpty()) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' => '❌ Gagal mengambil negara.'
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            $buttons = [];

            $page = 1;
            $perPage = 7;

            $currentCountries = $countries->slice(
                ($page - 1) * $perPage,
                $perPage
            );

            foreach ($currentCountries as $country) {

                $buttons[] = [
                    [
                        'text' => $country['name'],
                        'callback_data' => 'country_' . $country['id']
                    ]
                ];
            }

            $buttons[] = [
                [
                    'text' => '🔍 Cari Negara',
                    'callback_data' => 'search_country'
                ]
            ];

            $buttons[] = [
                [
                    'text' => '➡️ Selanjutnya',
                    'callback_data' => 'country_page_2'
                ]
            ];

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' => "━━━━━━━━━━━━━━━
🌍 Pilih Negara
━━━━━━━━━━━━━━━",

                    'reply_markup' => json_encode([
                        'inline_keyboard' => $buttons
                    ])
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }
        $state = Cache::get(
            'telegram_state_' . $telegramId
        );

        /*
        |--------------------------------------------------------------------------
        | LINK EXISTING ACCOUNT VIA EMAIL
        |--------------------------------------------------------------------------
        */

        if ($state == 'waiting_email_link') {

            Cache::forget(
                'telegram_state_' . $telegramId
            );

            $findUser = User::where(
                'email',
                trim($text)
            )->first();

            if (!$findUser) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,

                        'text' =>
                            "❌ Email tidak ditemukan."
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            // akun sudah dipakai telegram lain
            if (
                $findUser->telegram_id &&
                $findUser->telegram_id != $telegramId
            ) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,

                        'text' =>
                            "❌ Akun sudah terhubung ke Telegram lain."
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            // sync telegram
            $findUser->update([

                'telegram_id' => $telegramId,

                'telegram_username' => $telegramUsername,
            ]);

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' =>
                        "✅ Akun website berhasil dihubungkan ke Telegram.

Ketik /start untuk memulai."
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }
        /*
        |--------------------------------------------------------------------------
        | SEARCH COUNTRY INPUT
        |--------------------------------------------------------------------------
        */

        if ($state == 'search_country') {

            Cache::forget(
                'telegram_state_' . $telegramId
            );

            $svc = app(SmscodeService::class);

            $countries = collect(
                $svc->getCountries()['data'] ?? []
            )->filter(function ($c) use ($text) {

                return str_contains(
                    strtolower($c['name']),
                    strtolower($text)
                );
            });

            if ($countries->isEmpty()) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' => '❌ Negara tidak ditemukan'
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            $buttons = [];

            foreach ($countries->take(20) as $country) {

                $buttons[] = [
                    [
                        'text' => $country['name'],
                        'callback_data' =>
                            'country_' . $country['id']
                    ]
                ];
            }

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,
                    'text' => '🌍 Hasil pencarian negara',
                    'reply_markup' => json_encode([
                        'inline_keyboard' => $buttons
                    ])
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }
        /*
        |--------------------------------------------------------------------------
        | SEARCH SERVICE INPUT
        |--------------------------------------------------------------------------
        */

        if (str_starts_with($state, 'search_service_')) {

            $countryId = str_replace(
                'search_service_',
                '',
                $state
            );

            Cache::forget(
                'telegram_state_' . $telegramId
            );

            $svc = app(SmscodeService::class);

            $services = collect(
                $svc->getServices($countryId)['data'] ?? []
            )->filter(function ($s) use ($text) {

                return str_contains(
                    strtolower($s['name'] ?? ''),
                    strtolower($text)
                );
            });

            if ($services->isEmpty()) {

                Http::timeout(10)->post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' => '❌ Layanan tidak ditemukan'
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            $buttons = [];

            foreach ($services->take(20) as $service) {

                $buttons[] = [
                    [
                        'text' => $service['name'],
                        'callback_data' =>
                            'service_' . $countryId . '_' . $service['id']
                    ]
                ];
            }

            $buttons[] = [
                [
                    'text' => '⬅️ Kembali',
                    'callback_data' =>
                        'country_' . $countryId
                ]
            ];

            Http::timeout(10)->post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,
                    'text' => '📱 Hasil pencarian layanan',
                    'reply_markup' => json_encode([
                        'inline_keyboard' => $buttons
                    ])
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }

        /*
  |--------------------------------------------------------------------------
  | DEPOSIT
  |--------------------------------------------------------------------------
  */

        if ($text == '💰 Deposit') {

            Cache::put(
                'telegram_state_' . $telegramId,
                'waiting_deposit_amount',
                now()->addMinutes(10)
            );

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' =>
                        "━━━━━━━━━━━━━━━
💰 Isi Saldo
━━━━━━━━━━━━━━━
💳 Saldo Saat Ini : Rp " . number_format($user->balance ?? 0, 0, ',', '.') . "
━━━━━━━━━━━━━━━
Masukkan nominal deposit.
Contoh: 5000
━━━━━━━━━━━━━━━",

                    'reply_markup' => [
                        'keyboard' => [


                            [
                                ['text' => '🏠 Home']
                            ]

                        ],

                        'resize_keyboard' => true
                    ]
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }

        /*
        |--------------------------------------------------------------------------
        | INPUT NOMINAL DEPOSIT
        |--------------------------------------------------------------------------
        */

        $state = Cache::get('telegram_state_' . $telegramId);

        if ($state == 'waiting_deposit_amount') {

            if (!is_numeric($text)) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' => '❌ Nominal tidak valid.'
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            $amount = (int) $text;

            if ($amount < 5000) {
                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' => '❌ Minimal deposit Rp 5.000'
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            Cache::forget('telegram_state_' . $telegramId);

            /*
          |--------------------------------------------------------------------------
          | GENERATE PAYMENT
          |--------------------------------------------------------------------------
          */

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' =>
                        "━━━━━━━━━━━━━━━
✅ Nominal deposit: Rp " . number_format($amount, 0, ',', '.') . "
━━━━━━━━━━━━━━━
⏳ Sedang membuat pembayaran...
━━━━━━━━━━━━━━━"
                ]
            );

            /*
            |--------------------------------------------------------------------------
            | CREATE DEPOSIT VIA CONTROLLER
            |--------------------------------------------------------------------------
            */

            Auth::login($user);

            $fakeRequest = HttpRequest::create(
                '/deposit',
                'POST',
                [
                    'amount' => $amount
                ]
            );

            $fakeRequest->headers->set(
                'X-Requested-With',
                'XMLHttpRequest'
            );

            app()->instance('request', $fakeRequest);

            $response = app(DepositController::class)
                ->store($fakeRequest);

            $data = $response->getData(true);

            if (
                !isset($data['success']) ||
                !$data['success']
            ) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,

                        'text' =>
                            "❌ Gagal membuat deposit."
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            /*
            |--------------------------------------------------------------------------
            | KIRIM QRIS
            |--------------------------------------------------------------------------
            */

            $caption =
                "━━━━━━━━━━━━━━━
💰 Deposit Berhasil Dibuat
━━━━━━━━━━━━━━━
🧾 Invoice : {$data['trxId']}
💵 Nominal : Rp " . number_format($data['amount'], 0, ',', '.') . "
━━━━━━━━━━━━━━━
⏳ Menunggu pembayaran.
━━━━━━━━━━━━━━━";

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendPhoto",
                [
                    'chat_id' => $chatId,

                    'photo' => $data['qrisData']['image'],

                    'caption' => $caption,

                    'reply_markup' => json_encode([
                        'inline_keyboard' => [
                            [
                                [
                                    'text' => '🔄 Check Status',
                                    'callback_data' => 'check_' . $data['trxId']
                                ]
                            ]
                        ]
                    ])
                ]
            );
            Auth::logout();
            return response()->json([
                'success' => true
            ]);
        }


        /*
        |--------------------------------------------------------------------------
        | REFERRAL
        |--------------------------------------------------------------------------
        */

        if ($text == '👥 Referral') {

            $refLink = url('/register?ref=' . $user->referral_code);

            $botUsername = env('TELEGRAM_BOT_USERNAME');

            $botReferral =

                "https://t.me/{$botUsername}?start=ref_" . $user->referral_code;

            $loginToken = Str::random(64);

            Cache::put(

                'telegram_login_' . $loginToken,

                [

                    'telegram_id' => $telegramId,

                    'name' => $user->name,

                    'username' => $user->telegram_username,

                ],

                now()->addMinutes(5)

            );

            $loginUrl = url('/telegram/login/' . $loginToken);
            // link bot telegram

            $botReferral =
                "https://t.me/{$botUsername}?start=ref_" . $user->referral_code;

            // total referral
            $totalReferral = User::where(
                'referrer_id',
                $user->id
            )->count();

            // total komisi
            $totalKomisi = ReferralCommission::where(
                'referrer_id',
                $user->id
            )->sum('amount');

            // total komisi ditarik
            $totalKomisiDitarik = ReferralCommission::where(
                'referrer_id',
                $user->id
            )->where('status', 'WITHDRAWN')
                ->sum('amount');

            // saldo komisi pending
            $totalPending = ReferralCommission::where(
                'referrer_id',
                $user->id
            )->where('status', 'PENDING')
                ->sum('amount');

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' =>
                        "━━━━━━━━━━━━━━━
👥 Referral NusaOTP
━━━━━━━━━━━━━━━
🎟 Kode Referral : {$user->referral_code}
🌐 Link Referral Web : {$refLink}
🤖 Link Referral Bot : {$botReferral}
━━━━━━━━━━━━━━━
👤 Total Yang Diundang : {$totalReferral} Orang
💰 Total Komisi : Rp " . number_format($totalKomisi, 0, ',', '.') . "
💸 Sudah Ditarik : Rp " . number_format($totalKomisiDitarik, 0, ',', '.') . "
🪙 Komisi Pending : Rp " . number_format($totalPending, 0, ',', '.') . "
━━━━━━━━━━━━━━━
Penarikan komisi referral
dilakukan melalui website
(Minimal Rp 5.000)
━━━━━━━━━━━━━━━",

                    'reply_markup' => json_encode([
                        'inline_keyboard' => [

                            [
                                [
                                    'text' => '🌐 Login Web',
                                    'url' => $loginUrl
                                ]
                            ],

                            [
                                [
                                    'text' => '⬅️ Kembali',
                                    'callback_data' => 'back_home'
                                ]
                            ]

                        ]
                    ])
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }

        /*
        |--------------------------------------------------------------------------
        | RIWAYAT MENU
        |--------------------------------------------------------------------------
        */

        if ($text == '📜 Riwayat') {

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' =>
                        "━━━━━━━━━━━━━━━
📜 Menu Riwayat
━━━━━━━━━━━━━━━
Silahkan pilih jenis riwayat.
━━━━━━━━━━━━━━━",

                    'reply_markup' => [
                        'keyboard' => [

                            [
                                ['text' => '💰 Riwayat Deposit'],
                                ['text' => '🛒 Riwayat Order']
                            ],

                            [
                                ['text' => '🏠 Home']
                            ]

                        ],

                        'resize_keyboard' => true
                    ]
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }


        /*
        |--------------------------------------------------------------------------
        | RIWAYAT DEPOSIT
        |--------------------------------------------------------------------------
        */

        /*
        |--------------------------------------------------------------------------
        | RIWAYAT DEPOSIT
        |--------------------------------------------------------------------------
        */

        if ($text == '💰 Riwayat Deposit') {

            $page = 1;
            $perPage = 4;

            $deposits = Deposit::where('user_id', $user->id)
                ->latest()
                ->skip(($page - 1) * $perPage)
                ->take($perPage)
                ->get();

            if ($deposits->isEmpty()) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' => '❌ Belum ada riwayat deposit.'
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            $caption = "━━━━━━━━━━━━━━━
💰 Riwayat Deposit
━━━━━━━━━━━━━━━
(Page {$page})\n\n";

            foreach ($deposits as $deposit) {

                $caption .=
                    "━━━━━━━━━━━━━━━
🧾 Trx ID : {$deposit->trx_id}
💵 Nominal : Rp " . number_format($deposit->amount, 0, ',', '.') . "
📌 Status : {$deposit->status}
🕒 Waktu : " . $deposit->created_at->format('d/m/Y H:i') . "
";
            }

            $buttons = [];

            $total = Deposit::where('user_id', $user->id)->count();

            if ($total > ($page * $perPage)) {

                $buttons[] = [
                    [
                        'text' => '➡️ Next',
                        'callback_data' => 'deposit_page_2'
                    ]
                ];
            }

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,
                    'text' => $caption,

                    'reply_markup' => json_encode([
                        'inline_keyboard' => $buttons
                    ])
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }
        /*
        |--------------------------------------------------------------------------
        | RIWAYAT ORDER
        |--------------------------------------------------------------------------
        */

        if ($text == '🛒 Riwayat Order') {

            $page = 1;
            $perPage = 4;

            $orders = Order::where('user_id', $user->id)
                ->latest()
                ->skip(($page - 1) * $perPage)
                ->take($perPage)
                ->get();

            if ($orders->isEmpty()) {

                Http::post(
                    "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                    [
                        'chat_id' => $chatId,
                        'text' => '❌ Belum ada riwayat order.'
                    ]
                );

                return response()->json([
                    'success' => true
                ]);
            }

            $caption = "━━━━━━━━━━━━━━━
🛒 Riwayat Order OTP
━━━━━━━━━━━━━━━
(Page {$page})\n\n";

            $buttons = [];

            foreach ($orders as $order) {

                $statusEmoji = match ($order->status) {
                    'SUCCESS' => '✅',
                    'PENDING' => '⏳',
                    'FAILED' => '❌',
                    'CANCELED' => '🚫',
                    default => '📌'
                };

                $caption .=
                    "━━━━━━━━━━━━━━━
🆔 Order : {$order->id}
━━━━━━━━━━━━━━━
📱 Layanan : {$order->layanan_nama}
☎️ Nomor : {$order->number}" .
                    ($order->status === 'SUCCESS'
                        ? "\n🔑 OTP : " . ($order->otp ?: '-')
                        : '') . "
💰 Harga : Rp " . number_format($order->harga, 0, ',', '.') . "
{$statusEmoji} Status : {$order->status}
🕒 Waktu : " . $order->created_at->format('d/m/Y H:i') . "

";

                if (
                    $order->status === 'PENDING' &&
                    Cache::has('telegram_cancel_' . $order->id)
                ) {

                    $buttons[] = [
                        [
                            'text' => '❌ Cancel #' . $order->id,
                            'callback_data' => 'cancel_order_' . $order->id
                        ]
                    ];
                }
            }

            $total = Order::where('user_id', $user->id)->count();

            if ($total > ($page * $perPage)) {

                $buttons[] = [
                    [
                        'text' => '➡️ Next',
                        'callback_data' => 'order_page_2'
                    ]
                ];
            }

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,
                    'text' => $caption,

                    'reply_markup' => json_encode([
                        'inline_keyboard' => $buttons
                    ])
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }
        if ($text == '📢 Channel') {

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' => '━━━━━━━━━━━━━━━
Silahkan bergabung kedalam channel
untuk mengetahui update & pemberitahuan
tentang platform Nusa OTP
━━━━━━━━━━━━━━━',

                    'reply_markup' => [
                        'inline_keyboard' => [
                            [
                                [
                                    'text' => '📢 Join Channel',
                                    'url' => env('TELEGRAM_CHANNEL')
                                ]
                            ]
                        ]
                    ]
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }

        if ($text == '👨‍💻 Admin') {

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' => '━━━━━━━━━━━━━━━
👨‍💻 Kontak Layanan Pelanggan
━━━━━━━━━━━━━━━
Chat admin jika ada pertanyaan
atau kendala yang anda alami.
━━━━━━━━━━━━━━━',

                    'reply_markup' => [
                        'inline_keyboard' => [
                            [
                                [
                                    'text' => '👨‍💻 Chat Admin',
                                    'url' => env('TELEGRAM_ADMIN')
                                ]
                            ]
                        ]
                    ]
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }
        if ($text == '🚀 Daftar Reseller') {

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' => '━━━━━━━━━━━━━━━
🚀 Daftar Reseller
━━━━━━━━━━━━━━━
Ingin Punya Bot Nokos Seperti
@nusaotp_bot sendiri???
Gabung Reseller NusaOTP
━━━━━━━━━━━━━━━
Bennefit:
✅ Markup bebas (by Persen [%]
atau Flat [+profit]
✅ Tanpa modal ke penyedia nomor
✅ Bebas atur Nama Brand
✅ Logo brand bisa bawa sendiri
atau kami bantu buatkan
✅ Tarik profit ke Rekening Kamu
mulai Rp10.000
✅ Pantau penjualan real-time
di dashboard
✅ Gratis biaya Maintenance
✅ Jika sda update, gratis update
━━━━━━━━━━━━━━━
Jualan Tanpa Ribet. Full Otomatis
Aktif 24/7 !!
━━━━━━━━━━━━━━━',

                    'reply_markup' => [
                        'inline_keyboard' => [
                            [
                                [
                                    'text' => '🚀 Daftar',
                                    'url' => env('JOINRESELLER')
                                ]
                            ]
                        ]
                    ]
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }
        if ($text == '🖥️ Monitoring') {

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' => '━━━━━━━━━━━━━━━
🖥️ Channel Monitoring Nusa OTP
━━━━━━━━━━━━━━━
Live transaksi yang sedang
berlangsung di Nusa OTP
━━━━━━━━━━━━━━━',

                    'reply_markup' => [
                        'inline_keyboard' => [
                            [
                                [
                                    'text' => '🖥️ Channel Monitoring',
                                    'url' => env('CH_MONITORING')
                                ]
                            ]
                        ]
                    ]
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }

        if ($text == 'ℹ️ Media Sosial') {

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' => '━━━━━━━━━━━━━━━
ℹ️ Media Sosial Official Nusa OTP
━━━━━━━━━━━━━━━
Ikuti Media Sosial Kami.
━━━━━━━━━━━━━━━',

                    'reply_markup' => [
                        'inline_keyboard' => [

                            [
                                [
                                    'text' => 'Instagram',
                                    'url' => env('INSTAGRAM')
                                ]
                            ],

                            [
                                [
                                    'text' => 'Tiktok',
                                    'url' => env('TIKTOK')
                                ]
                            ],

                            [
                                [
                                    'text' => 'Facebook',
                                    'url' => env('FACEBOOK')
                                ]
                            ],

                            [
                                [
                                    'text' => 'Youtube',
                                    'url' => env('YOUTUBE')
                                ]
                            ]

                        ]
                    ]
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }


        /*
        |--------------------------------------------------------------------------
        | LOGIN WEBSITE
        |--------------------------------------------------------------------------
        */

        if ($text == '🌐 Login Web') {

            $loginToken = Str::random(64);

            Cache::put(
                'telegram_login_' . $loginToken,
                [
                    'telegram_id' => $telegramId,
                    'name' => $telegramName,
                    'username' => $telegramUsername,
                ],
                now()->addMinutes(5)
            );

            $loginUrl = url('/telegram/login/' . $loginToken);

            Http::post(
                "https://api.telegram.org/bot{$tokenBot}/sendMessage",
                [
                    'chat_id' => $chatId,

                    'text' =>
                        "━━━━━━━━━━━━━━━
🔐 Login Website
━━━━━━━━━━━━━━━
Klik tombol dibawah untuk
login ke Website.
━━━━━━━━━━━━━━━",

                    'reply_markup' => [
                        'inline_keyboard' => [
                            [
                                [
                                    'text' => '🌐 Login',
                                    'url' => $loginUrl
                                ]
                            ]
                        ]
                    ]
                ]
            );

            return response()->json([
                'success' => true
            ]);
        }

        return response()->json([
            'success' => true
        ]);
    }
}