<?php

namespace App\Services;

use App\Models\BotUser;
use App\Models\Mod;
use App\Models\LicenseKey;
use App\Models\PendingPurchase;
use App\Models\Transaction;
use App\Models\SpinLog;
use App\Models\Setting;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class TelegramBotService
{
    protected $botToken;
    protected $apiUrl;
    protected $adminChatId;

    public function __construct()
    {
        $this->botToken = config('bot.telegram_token');
        $this->apiUrl = "https://api.telegram.org/bot{$this->botToken}/";
        $this->adminChatId = config('bot.admin_chat_id');
    }

    public function handleWebhook($update)
    {
        try {
            if (isset($update['callback_query'])) {
                return $this->handleCallbackQuery($update['callback_query']);
            }

            if (isset($update['message'])) {
                return $this->handleMessage($update['message']);
            }
        } catch (\Exception $e) {
            Log::build([
                'driver' => 'single',
                'path' => storage_path('logs/bot_errors.log'),
            ])->error('Bot Error: ' . $e->getMessage(), [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'update' => $update
            ]);
        }
    }

    protected function handleMessage($message)
    {
        $chatId = $message['chat']['id'];
        $text = $message['text'] ?? '';
        $username = $message['from']['username'] ?? null;

        // Delete user's message to keep chat clean
        if (isset($message['message_id'])) {
            Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'deleteMessage', [
                'chat_id' => $chatId,
                'message_id' => $message['message_id']
            ]);
        }

        // Register or retrieve user
        $user = $this->getOrCreateUser($chatId, $username);

        // Process referral link click if exists e.g. /start ref_12345
        if (str_starts_with($text, '/start')) {
            $parts = explode(' ', $text);
            if (count($parts) > 1 && str_starts_with($parts[1], 'ref_')) {
                $refChatId = str_replace('ref_', '', $parts[1]);
                $this->processReferral($user, $refChatId);
            }
            return $this->sendStartMenu($chatId);
        }

        switch ($text) {
            case '🛒 Shop Now':
                return $this->sendShopCategories($chatId);
            case '🛍️ My Orders':
                return $this->sendMyOrders($chatId);
            case '☄️ Profile':
                return $this->sendProfile($chatId);
            case '💠 Pay Proof':
                return $this->sendPayProof($chatId);
            case '💠 How To Use':
                return $this->sendHowToUse($chatId);
            case '💠 Support':
                return $this->sendSupport($chatId);
            case '💠 Spin & Win':
                return $this->sendSpinMenu($chatId);
            case '🟢 Referral':
                return $this->sendReferral($chatId);
            default:
                return $this->sendStartMenu($chatId);
        }
    }

    protected function handleCallbackQuery($callback)
    {
        $chatId = $callback['message']['chat']['id'];
        $data = $callback['data'];

        // Acknowledge callback
        Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'answerCallbackQuery', [
            'callback_query_id' => $callback['id']
        ]);

        switch ($data) {
            case 'back_to_start':
            case 'back_to_main':
                return $this->sendStartMenu($chatId, $callback['message']['message_id']);
            case 'shop':
                return $this->sendShopCategories($chatId, $callback['message']['message_id']);
            case 'orders':
                return $this->sendMyOrders($chatId, $callback['message']['message_id']);
            case 'profile':
                return $this->sendProfile($chatId, $callback['message']['message_id']);
            case 'pay_proof':
                return $this->sendPayProof($chatId, $callback['message']['message_id']);
            case 'how_to_use':
                return $this->sendHowToUse($chatId, $callback['message']['message_id']);
            case 'support':
                return $this->sendSupport($chatId, $callback['message']['message_id']);
            case 'spin_win':
                return $this->sendSpinMenu($chatId, $callback['message']['message_id']);
            case 'referral':
                return $this->sendReferral($chatId, $callback['message']['message_id']);
        }

        // Handling Categories
        if (str_starts_with($data, 'cat_')) {
            $category = str_replace('cat_', '', $data);
            return $this->sendCategoryMods($chatId, $category, $callback['message']['message_id']);
        }

        // Fallback for old buttons
        if (in_array($data, ['Android', 'iPhone', 'PC'])) {
            return $this->sendCategoryMods($chatId, $data, $callback['message']['message_id']);
        }

        if ($data === 'spin_now') {
            return $this->processSpin($chatId, $callback['message']['message_id']);
        }

        // Handling Shop Mods
        if (str_starts_with($data, 'mod_')) {
            $modId = str_replace('mod_', '', $data);
            return $this->sendModDurations($chatId, $modId, $callback['message']['message_id']);
        }

        // Handling Duration Selection
        if (str_starts_with($data, 'duration_')) {
            list(, $modId, $durationDays, $price) = explode('_', $data);
            return $this->processDurationSelection($chatId, $modId, $durationDays, $price, $callback['message']['message_id']);
        }

        // Handling Payment PAID button (Format: orderID,chatId)
        if (strpos($data, ',') !== false) {
            list($orderID, $payerChatId) = explode(',', $data);
            if ($payerChatId == $chatId) {
                return $this->processPaymentCallback($chatId, $orderID, $callback['message']['message_id'], $callback['from']['username'] ?? '');
            }
        }

        return true;
    }

    protected function getOrCreateUser($chatId, $username)
    {
        $user = BotUser::firstOrCreate(
            ['chat_id' => $chatId],
            [
                'username' => $username,
                'referral_code' => Str::upper(Str::random(8)),
            ]
        );
        return $user;
    }

    protected function processReferral($newUser, $referrerChatId)
    {
        if ($newUser->chat_id == $referrerChatId) return; // Self referral check
        if ($newUser->referred_by != null) return; // Already referred

        $referrer = BotUser::where('chat_id', $referrerChatId)->first();
        if ($referrer) {
            $newUser->referred_by = $referrerChatId;
            $newUser->save();
        }
    }

    protected function sendStartMenu($chatId, $messageId = null)
    {
        $settings = \App\Models\Setting::all()->pluck('value', 'key');

        $payProofBtn = !empty($settings['pay_proof_link'])
            ? ['text' => '📩 Pay Proof', 'url' => $settings['pay_proof_link'], 'style' => 'primary']
            : ['text' => '📩 Pay Proof', 'callback_data' => 'pay_proof', 'style' => 'primary'];

        $howToUseBtn = !empty($settings['how_to_use_link'])
            ? ['text' => '📌 How to Use', 'url' => $settings['how_to_use_link'], 'style' => 'primary']
            : ['text' => '📌 How to Use', 'callback_data' => 'how_to_use', 'style' => 'primary'];

        $supportBtn = !empty($settings['support_link'])
            ? ['text' => '📌 Support', 'url' => $settings['support_link'], 'style' => 'primary']
            : ['text' => '📌 Support', 'callback_data' => 'support', 'style' => 'primary'];

        $keyboard = [
            'inline_keyboard' => [
                [
                    ['text' => '🛒 Shop Now', 'callback_data' => 'shop', 'style' => 'primary']
                ],
                [
                    ['text' => '📦 My Orders', 'callback_data' => 'orders', 'style' => 'primary'],
                    ['text' => '🪄 Profile', 'callback_data' => 'profile', 'style' => 'primary']
                ],
                [
                    $payProofBtn,
                    $howToUseBtn
                ],
                [
                    $supportBtn,
                    ['text' => '🎰 Spin & Win', 'callback_data' => 'spin_win', 'style' => 'primary']
                ],
                [
                    ['text' => '🎁 Referral — Invite & Earn Spins', 'callback_data' => 'referral', 'style' => 'success']
                ]
            ]
        ];

        $user = BotUser::where('chat_id', $chatId)->first();
        $name = $user->username ?? 'User';

        $text = "🔥 —— PANEL STORE FREE FIRE —— 🔥\nPowered by Ravan\n\n🎉 Yo {$name} 🌐, Welcome Back!!\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n📌 Why our store is trusted?\n↪ Direct deals with every mod developer\n↪ Instant delivery after payment\n↪ 5% discount on your 2nd & every extra purchase\n↪ Guaranteed discounted prices";

        if ($messageId) {
            return Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', [
                'chat_id' => $chatId,
                'message_id' => $messageId,
                'text' => $text,
                'parse_mode' => 'HTML',
                'reply_markup' => json_encode($keyboard)
            ]);
        }

        return $this->sendCleanMessage('sendMessage', [
            'chat_id' => $chatId,
            'text' => $text,
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode($keyboard)
        ]);
    }

    protected function sendShopCategories($chatId, $messageId = null)
    {
        $keyboard = [
            'inline_keyboard' => [
                [
                    ['text' => '📱 Android Mods', 'callback_data' => 'cat_Android', 'style' => 'primary'],
                    ['text' => '💠iPhone Mods', 'callback_data' => 'cat_iPhone', 'style' => 'primary']
                ],
                [
                    ['text' => '💻 PC Mods', 'callback_data' => 'cat_PC', 'style' => 'primary']
                ],
                [
                    ['text' => '🔙 Back to Menu', 'callback_data' => 'back_to_main', 'style' => 'primary']
                ]
            ]
        ];

        if ($messageId) {
            return Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', [
                'chat_id' => $chatId,
                'message_id' => $messageId,
                'text' => '🛒 <b>Please Select a Device Category:</b>',
                'parse_mode' => 'HTML',
                'reply_markup' => json_encode($keyboard)
            ]);
        }

        return $this->sendCleanMessage('sendMessage', [
            'chat_id' => $chatId,
            'text' => '🛒 <b>Please Select a Device Category:</b>',
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode($keyboard)
        ]);
    }

    protected function sendCategoryMods($chatId, $category, $messageId)
    {
        $mods = Mod::where('status', 'active')->where('category', $category)->get();

        if ($mods->isEmpty()) {
            return Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', [
                'chat_id' => $chatId,
                'message_id' => $messageId,
                'text' => '❌ No active mods found in this category.',
                'reply_markup' => json_encode(['inline_keyboard' => [[['text' => '💠 Back', 'callback_data' => 'shop', 'style' => 'primary']]]])
            ]);
        }

        $keyboard = ['inline_keyboard' => []];
        foreach ($mods as $mod) {
            $keyboard['inline_keyboard'][] = [
                ['text' => '💠 ' . $mod->name, 'callback_data' => 'mod_' . $mod->id, 'style' => 'primary']
            ];
        }
        $keyboard['inline_keyboard'][] = [['text' => '🔙 Back to Categories', 'callback_data' => 'shop', 'style' => 'primary']];

        return Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', [
            'chat_id' => $chatId,
            'message_id' => $messageId,
            'text' => '🛒 <b>Select a ' . $category . ' Mod:</b>',
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode($keyboard)
        ]);
    }

    protected function sendMyOrders($chatId, $messageId = null)
    {
        $orders = \App\Models\Transaction::where('user_id', $chatId)->orderBy('id', 'desc')->take(10)->get();
        $text = "━━━━━━━━━━━━━━━━━━━━━━━━━━\n📦 <b>MY ORDERS</b>\n━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n";

        if ($orders->isEmpty()) {
            $text .= "You haven't placed any orders yet.\n🔥 Tap Shop Now to get started!";
        } else {
            foreach ($orders as $order) {
                $text .= "<b>ID:</b> " . $order->transaction_id . "\n";
                $text .= "<b>Amount:</b> ₹" . $order->amount . "\n";
                $text .= "<b>Status:</b> " . $order->status . "\n";

                $keys = \App\Models\LicenseKey::where('locked_purchase_id', $order->transaction_id)->get();
                if ($keys->count() > 0) {
                    $text .= "<b>License Keys:</b>\n";
                    foreach ($keys as $key) {
                        $text .= "<code>" . $key->license_key . "</code>\n";
                    }
                }

                $text .= "<b>Date:</b> " . $order->created_at . "\n\n";
            }
        }

        $keyboard = [
            'inline_keyboard' => [
                [['text' => '🛒 Shop Now', 'callback_data' => 'shop', 'style' => 'primary']],
                [['text' => '🔙 Back to Menu', 'callback_data' => 'back_to_start', 'style' => 'primary']]
            ]
        ];

        if ($messageId) {
            return \Illuminate\Support\Facades\Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', [
                'chat_id' => $chatId,
                'message_id' => $messageId,
                'text' => $text,
                'parse_mode' => 'HTML',
                'reply_markup' => json_encode($keyboard)
            ]);
        }
        return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
    }

    protected function sendProfile($chatId, $messageId = null)
    {
        $user = \App\Models\BotUser::where('chat_id', $chatId)->first();
        if (!$user) return;
        $referralLink = "https://t.me/" . env('BOT_USERNAME', 'freefiretestsusingbot') . "?start=ref_" . $chatId;
        $referralsCount = \App\Models\BotUser::where('referred_by', $chatId)->count();
        $text = "🪄 <b>Your Profile</b>\n\n<b>Name:</b> " . ($user->username ?? 'Unknown') . "\n<b>Telegram ID:</b> " . $chatId . "\n<b>Join Date:</b> " . $user->created_at->format('Y-m-d') . "\n\n<b>📊 Statistics</b>\n• Total Orders: " . $user->total_orders . "\n• Completed: " . $user->completed_orders . "\n• Pending: " . $user->pending_orders . "\n• Cancelled: " . $user->cancelled_orders . "\n\n<b>🎁 Rewards & Referrals</b>\n• Bonus Spins: " . $user->bonus_spins . "\n• Current Discount: " . $user->current_discount . "%\n• Total Saved: ₹" . $user->total_saved . "\n• Total Referrals: " . $referralsCount . " / 2 (Rewarded)\n• Referral Link: \n<code>" . $referralLink . "</code>";
        $keyboard = ['inline_keyboard' => [[['text' => '🛒 Shop Now', 'callback_data' => 'shop', 'style' => 'primary']], [['text' => '🔙 Back to Menu', 'callback_data' => 'back_to_start', 'style' => 'primary']]]];
        if ($messageId) return \Illuminate\Support\Facades\Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', ['chat_id' => $chatId, 'message_id' => $messageId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
        return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
    }

    protected function sendPayProof($chatId, $messageId = null)
    {
        $settings = \App\Models\Setting::all()->pluck('value', 'key');
        $link = $settings['pay_proof_link'] ?? null;
        $text = $link ? "📤 Pay Proof Channel:\n$link" : "📤 Pay Proof coming soon...";

        $keyboard = [
            'inline_keyboard' => [
                [['text' => '🔙 Back to Menu', 'callback_data' => 'back_to_start', 'style' => 'primary']]
            ]
        ];
        if ($link) {
            array_unshift($keyboard['inline_keyboard'], [['text' => '👉 View Pay Proof', 'url' => $link, 'style' => 'primary']]);
        }

        if ($messageId) return \Illuminate\Support\Facades\Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', ['chat_id' => $chatId, 'message_id' => $messageId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
        return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
    }

    protected function sendHowToUse($chatId, $messageId = null)
    {
        $settings = \App\Models\Setting::all()->pluck('value', 'key');
        $link = $settings['how_to_use_link'] ?? null;
        $text = $link ? "📌 How to Use:\n$link" : "📌 How to Use coming soon...";

        $keyboard = [
            'inline_keyboard' => [
                [['text' => '🔙 Back to Menu', 'callback_data' => 'back_to_start', 'style' => 'primary']]
            ]
        ];
        if ($link) {
            array_unshift($keyboard['inline_keyboard'], [['text' => '👉 View Tutorial', 'url' => $link, 'style' => 'primary']]);
        }

        if ($messageId) return \Illuminate\Support\Facades\Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', ['chat_id' => $chatId, 'message_id' => $messageId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
        return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
    }

    protected function sendSupport($chatId, $messageId = null)
    {
        $settings = \App\Models\Setting::all()->pluck('value', 'key');
        $link = $settings['support_link'] ?? null;
        $text = $link ? "📌 Support:\nContact our admin here: $link" : "📌 Support coming soon...";

        $keyboard = [
            'inline_keyboard' => [
                [['text' => '🔙 Back to Menu', 'callback_data' => 'back_to_start', 'style' => 'primary']]
            ]
        ];
        if ($link) {
            array_unshift($keyboard['inline_keyboard'], [['text' => '👉 Contact Support', 'url' => $link, 'style' => 'primary']]);
        }

        if ($messageId) return \Illuminate\Support\Facades\Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', ['chat_id' => $chatId, 'message_id' => $messageId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
        return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
    }

    protected function sendSpinMenu($chatId, $messageId = null)
    {
        $user = \App\Models\BotUser::where('chat_id', $chatId)->first();
        $spins = $user->bonus_spins ?? 0;
        $text = "🎰 <b>Spin & Win — Daily Discount!</b>\n\nPossible prizes:\n🎯 0% — No luck\n🏷 1% off\n🏷 2% off\n🔥 50% off <i>(extremely rare)</i>\n\n📅 <b>Daily limit: 1 spin(s)</b>\n💡 Refer a friend → they buy → you get +1 bonus spin (max 2 referrals)\nDiscounts apply automatically on your next purchase.\n\n<b>Spins available today: {$spins}</b>";

        $keyboard = ['inline_keyboard' => []];
        if ($spins > 0) {
            $keyboard['inline_keyboard'][] = [['text' => '🎰 SPIN NOW!', 'callback_data' => 'spin_now', 'style' => 'primary']];
        }
        $keyboard['inline_keyboard'][] = [['text' => '↩ Back', 'callback_data' => 'back_to_start', 'style' => 'primary']];

        if ($messageId) return \Illuminate\Support\Facades\Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', ['chat_id' => $chatId, 'message_id' => $messageId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
        return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
    }

    protected function sendReferral($chatId, $messageId = null)
    {
        $user = \App\Models\BotUser::where('chat_id', $chatId)->first();
        $referralLink = "https://t.me/" . env('BOT_USERNAME', 'freefiretestsusingbot') . "?start=ref_" . $chatId;
        $referralsCount = \App\Models\BotUser::where('referred_by', $chatId)->count();
        $text = "🎁 <b>Referral System</b>\n\nInvite friends and earn <b>1 Bonus Spin</b> after their first successful purchase!\n\n<b>Your Referral Link:</b>\n<code>" . $referralLink . "</code>\n\n<b>Stats:</b>\n• Total Referrals: " . $referralsCount . " / 2 (Rewarded)";
        $keyboard = ['inline_keyboard' => [[['text' => '🔙 Back to Menu', 'callback_data' => 'back_to_start', 'style' => 'primary']]]];
        if ($messageId) return \Illuminate\Support\Facades\Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', ['chat_id' => $chatId, 'message_id' => $messageId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
        return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($keyboard)]);
    }

    protected function sendModDurations($chatId, $modId, $messageId)
    {
        $this->releaseExpiredLocks();

        $durations = LicenseKey::selectRaw('duration_days, price, count(*) as available_keys')
            ->where('mod_id', $modId)
            ->where('status', 'available')
            ->groupBy('duration_days', 'price')
            ->having('available_keys', '>', 0)
            ->orderBy('duration_days')->orderBy('price')
            ->get();

        if ($durations->isEmpty()) {
            return Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', [
                'chat_id' => $chatId,
                'message_id' => $messageId,
                'text' => '❌ No license keys available for this mod at the moment.'
            ]);
        }

        $keyboard = ['inline_keyboard' => []];
        foreach ($durations as $duration) {
            $keyText = "💠 " . $duration->duration_days . " Days - ₹" . $duration->price . " (" . $duration->available_keys . " available)";
            $keyboard['inline_keyboard'][] = [
                ['text' => $keyText, 'callback_data' => 'duration_' . $modId . '_' . $duration->duration_days . '_' . $duration->price, 'style' => 'primary']
            ];
        }
        $keyboard['inline_keyboard'][] = [['text' => '💠 Back to Mods', 'callback_data' => 'shop', 'style' => 'primary']];

        return Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', [
            'chat_id' => $chatId,
            'message_id' => $messageId,
            'text' => '🎮 Please Select Your Loader Keys:',
            'reply_markup' => json_encode($keyboard)
        ]);
    }

    protected function processSpin($chatId, $messageId)
    {
        $user = BotUser::where('chat_id', $chatId)->first();
        if ($user->bonus_spins <= 0) {
            return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => '❌ You do not have any bonus spins.']);
        }

        // Rewards: 1%, 2%, 5%, 10%, 20%, 50%
        $rand = mt_rand(1, 1000);
        if ($rand <= 5) $reward = 50; // 0.5% chance
        elseif ($rand <= 30) $reward = 20; // 2.5% chance
        elseif ($rand <= 100) $reward = 10; // 7% chance
        elseif ($rand <= 300) $reward = 5; // 20% chance
        elseif ($rand <= 600) $reward = 2; // 30% chance
        else $reward = 1; // 40% chance

        $user->bonus_spins -= 1;

        // If current discount is lower, update it
        if ($user->current_discount < $reward) {
            $user->current_discount = $reward;
        }
        $user->save();

        SpinLog::create([
            'chat_id' => $chatId,
            'reward_percentage' => $reward,
            'expires_at' => now()->addDays(7)
        ]);

        $text = "🎉 <b>Congratulations!</b> 🎉\n\n";
        $text .= "You spun the wheel and won a <b>" . $reward . "% discount</b> on your next purchase!\n\n";
        $text .= "<i>Discount has been applied to your account automatically.</i>";

        return Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'editMessageText', [
            'chat_id' => $chatId,
            'message_id' => $messageId,
            'text' => $text,
            'parse_mode' => 'HTML'
        ]);
    }

    protected function releaseExpiredLocks()
    {
        LicenseKey::where('status', 'locked')
            ->where('locked_at', '<', now()->subMinutes(4))
            ->update([
                'status' => 'available',
                'locked_at' => null,
                'locked_purchase_id' => null,
                'purchased_by' => null
            ]);
    }

    protected function processDurationSelection($chatId, $modId, $durationDays, $price, $messageId)
    {
        $this->releaseExpiredLocks();

        // Release any previously locked keys by this user so they can only hold one at a time
        LicenseKey::where('status', 'locked')
            ->where('purchased_by', $chatId)
            ->update([
                'status' => 'available',
                'locked_at' => null,
                'locked_purchase_id' => null,
                'purchased_by' => null
            ]);

        // Clean up their previous pending purchases
        PendingPurchase::where('chat_id', $chatId)->delete();

        $purchaseId = uniqid();
        $quantity = 1;
        $total = $price * $quantity;

        $user = BotUser::where('chat_id', $chatId)->first();
        if ($user && $user->current_discount > 0) {
            $discountAmount = ($total * $user->current_discount) / 100;
            $total = max(0, $total - $discountAmount);
        }

        $lockedCount = LicenseKey::where('mod_id', $modId)
            ->where('duration_days', $durationDays)
            ->where('status', 'available')
            ->take($quantity)
            ->update([
                'status' => 'locked',
                'locked_at' => now(),
                'locked_purchase_id' => $purchaseId,
                'purchased_by' => $chatId
            ]);

        if ($lockedCount < $quantity) {
            return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => '❌ Sorry, the key you selected is currently locked by another user or out of stock.']);
        }

        PendingPurchase::create([
            'purchase_id' => $purchaseId,
            'chat_id' => $chatId,
            'mod_id' => $modId,
            'duration_days' => $durationDays,
            'quantity' => $quantity,
            'total_price' => $total,
            'created_at' => now()
        ]);

        $modName = Mod::find($modId)->name ?? 'Unknown Mod';
        $upi = config('bot.upi_id');
        $qrData = "upi://pay?pa=$upi&pn=SafeLoader&tr=$purchaseId&tn=Purchase of $modName for $durationDays days&am=$total";

        $qrApiUrl = "https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=" . urlencode($qrData);

        $caption = "<b>PAY ₹$total FOR $modName - $durationDays Days</b>\n\nSCAN THIS QR CODE TO PAY THEN CLICK PAID BUTTON\n\nNOTE: DONT MAKE PAYMENT ON SAME QR CODE AGAIN!\n1 QR CODE = 1 PAYMENT";

        $keyboard = ['inline_keyboard' => [[['text' => '💠 PAID', 'callback_data' => $purchaseId . ',' . $chatId, 'style' => 'primary']]]];

        $this->sendCleanMessage('sendPhoto', [
            'chat_id' => $chatId,
            'photo' => $qrApiUrl,
            'caption' => $caption,
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode($keyboard)
        ]);
        return true;
    }

    protected function processPaymentCallback($chatId, $purchaseId, $messageId, $username)
    {
        $purchase = PendingPurchase::where('purchase_id', $purchaseId)->first();
        if (!$purchase) {
            return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => 'Invalid or expired purchase request.']);
        }

        $merchantId = config('bot.paytm_merchant_id');
        $merchantKey = config('bot.paytm_merchant_key');

        $data = [
            'MID' => $merchantId,
            'ORDERID' => $purchaseId,
        ];
        $jsonData = json_encode($data);
        $checksum = hash_hmac('sha256', $jsonData, $merchantKey);
        $url = "https://securegw.paytm.in/merchant-status/getTxnStatus?JsonData=" . urlencode($jsonData) . "&CHECKSUMHASH=" . $checksum;

        try {
            $response = Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->get($url);
            $responseData = $response->json();

            $paymentVerified = (
                isset($responseData['STATUS']) &&
                $responseData['STATUS'] === 'TXN_SUCCESS' &&
                $responseData['ORDERID'] === $purchaseId &&
                $responseData['MID'] === $merchantId &&
                isset($responseData['TXNAMOUNT']) &&
                $responseData['TXNAMOUNT'] == $purchase->total_price
            );

            if ($paymentVerified) {
                if (Transaction::where('transaction_id', $purchaseId)->exists()) {
                    return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => '❌ PAYMENT ALREADY PROCESSED']);
                }

                Transaction::create([
                    'transaction_id' => $purchaseId,
                    'user_id' => $chatId,
                    'amount' => $purchase->total_price,
                    'type' => 'purchase',
                    'reference' => 'Paytm',
                    'status' => 'completed',
                    'created_at' => now()
                ]);

                $user = BotUser::where('chat_id', $chatId)->first();
                $user->total_orders += 1;
                $user->completed_orders += 1;
                if ($user->current_discount > 0) {
                    $saved = ($purchase->total_price / (1 - ($user->current_discount / 100))) - $purchase->total_price;
                    $user->total_saved += $saved;
                    $user->current_discount = 0;
                }

                if ($user->completed_orders == 1 && $user->referred_by) {
                    $referrer = BotUser::where('chat_id', $user->referred_by)->first();
                    if ($referrer) {
                        $referrer->bonus_spins += 1;
                        $referrer->save();
                        $this->sendCleanMessage('sendMessage', ['chat_id' => $referrer->chat_id, 'text' => '🎉 <b>Referral Bonus!</b> You earned 1 Bonus Spin because your referral completed a purchase!']);
                    }
                }
                $user->save();

                $keys = LicenseKey::where('locked_purchase_id', $purchaseId)
                    ->where('status', 'locked')
                    ->take($purchase->quantity)
                    ->get();

                $mod = Mod::find($purchase->mod_id);
                $modName = $mod->name ?? 'Unknown';
                $modCategory = $mod->category ?? 'Unknown';
                $modLink = $mod->mod_link ? "\nMod Link: {$mod->mod_link}" : "";

                $deliveryMessage = "<b>❤️ ENJOY YOUR KEYS! THANK YOU ❤️</b>\n\n<b>MOD: $modName\nCategory: $modCategory\nTransaction ID: <code>$purchaseId</code>$modLink\n--------------------------------------</b>\n";

                $keysList = "";
                foreach ($keys as $key) {
                    $key->status = 'sold';
                    $key->save();
                    $deliveryMessage .= "<b>License Key :- </b><code>{$key->license_key}</code>\n<b>Duration: {$purchase->duration_days} Days</b>\n<b>--------------------------------------</b>\n";
                    $keysList .= $key->license_key . "\n";
                }

                $this->sendCleanMessage('sendMessage', [
                    'chat_id' => $chatId,
                    'text' => $deliveryMessage,
                    'parse_mode' => 'HTML'
                ]);

                $purchase->delete();

                $currentTime = now()->format('Y-m-d H:i:s');
                $adminMsg = "<b>🔑 NEW KEY SOLD</b>\n\n<b>User:</b> @$username\n<b>User ID:</b> $chatId\n<b>Transaction ID:</b> $purchaseId\n<b>Category:</b> $modCategory\n<b>Amount:</b> ₹{$purchase->total_price}\n<b>Mod:</b> $modName\n<b>Duration:</b> {$purchase->duration_days} days\n<b>Quantity:</b> {$purchase->quantity}\n<b>Keys delivered:</b>\n<code>$keysList</code><b>Time:</b> $currentTime";
                $this->sendCleanMessage('sendMessage', ['chat_id' => $this->adminChatId, 'text' => $adminMsg, 'parse_mode' => 'HTML']);

                return true;
            } else {
                return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => '❌ PAYMENT VERIFICATION FAILED. STATUS: ' . ($responseData['STATUS'] ?? 'UNKNOWN')]);
            }
        } catch (\Exception $e) {
            return $this->sendCleanMessage('sendMessage', ['chat_id' => $chatId, 'text' => '❌ Payment verification error: ' . $e->getMessage()]);
        }
    }

    protected function sendCleanMessage($endpoint, $params)
    {
        $chatId = $params['chat_id'] ?? null;
        $isAdmin = ($chatId == $this->adminChatId);

        if ($chatId && !$isAdmin) {
            $lastMsgId = \Illuminate\Support\Facades\Cache::get('last_bot_msg_' . $chatId);
            if ($lastMsgId) {
                Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . 'deleteMessage', [
                    'chat_id' => $chatId,
                    'message_id' => $lastMsgId
                ]);
            }
        }

        $response = Http::timeout(30)->withOptions(['curl' => [CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4]])->post($this->apiUrl . $endpoint, $params);

        if ($chatId && !$isAdmin && $response->successful()) {
            $data = $response->json();
            if (isset($data['result']['message_id'])) {
                \Illuminate\Support\Facades\Cache::put(
                    'last_bot_msg_' . $chatId,
                    $data['result']['message_id'],
                    now()->addDays(7)
                );
            }
        }

        return $response;
    }
}
