<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Models\Story;
use App\Models\Commission;
use App\Models\Raffle;
use App\Models\ResellerProfile;
use App\Models\Ticket;
use App\Models\Transaction;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class WincarApiController extends Controller
{
    /**
     * Registro de nuevo usuario
     */
    public function register(Request $request)
    {
        // 1. Trampa Honeypot para Bots Automatizados
        if ($request->filled('hp_trap') || $request->filled('website')) {
            return response()->json([
                'message' => 'Registro no permitido (Detección antispam activa)',
            ], 422);
        }

        // 2. Validación de Dominios de Correo Desechables / Temporales
        $disposableDomains = [
            'mailinator.com', 'tempmail.com', '10minutemail.com', 'guerrillamail.com',
            'yopmail.com', 'trashmail.com', 'dispostable.com', 'temp-mail.org',
            'fakeinbox.com', 'sharklasers.com', 'getairmail.com', 'maildrop.cc'
        ];

        $emailParts = explode('@', strtolower(trim($request->email ?? '')));
        $emailDomain = end($emailParts);

        if (in_array($emailDomain, $disposableDomains)) {
            return response()->json([
                'errors' => ['email' => ['No se permiten correos temporales o desechables para registrarse.']]
            ], 422);
        }

        $validator = Validator::make($request->all(), [
            'name' => [
                'required',
                'string',
                'max:255',
                function ($attribute, $value, $fail) {
                    $parts = array_filter(explode(' ', trim($value)));
                    if (count($parts) < 2) {
                        $fail('Por favor ingresa tu nombre y al menos un apellido completo.');
                    }
                },
            ],
            'email' => 'required|string|email|max:255|unique:users',
            'cedula' => 'required|string|min:7|max:30|unique:users',
            'phone' => 'required|string|min:8|max:50',
            'password' => 'required|string|min:8',
            'referred_by_code' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $referredById = null;
        if ($request->filled('referred_by_code')) {
            $code = $request->referred_by_code;
            $reseller = ResellerProfile::where('reseller_code', $code)->first();
            if ($reseller) {
                $referredById = $reseller->user_id;
            } else {
                $referrer = User::where('referral_code', $code)->first();
                if ($referrer) {
                    $referredById = $referrer->id;
                }
            }
        }

        // Obtener el rol por defecto de 'Cliente' (ID 3 en nuestro DatabaseSeeder)
        $clientRoleId = DB::table('roles')->where('name', 'customer')->value('id') ?? 3;

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'cedula' => $request->cedula,
            'phone' => $request->phone,
            'password' => Hash::make($request->password),
            'role_id' => $clientRoleId,
            'vip_level_id' => null, // Inicia sin VIP
            'referred_by_id' => $referredById,
            'status' => 'active',
            'wallet_balance' => 0.00,
            'points_balance' => 0,
        ]);

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'message' => 'Usuario registrado con éxito',
            'access_token' => $token,
            'token_type' => 'Bearer',
            'user' => $user->load('role'),
        ], 201);
    }

    /**
     * Inicio de sesión
     */
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $user = User::where('email', $request->email)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            return response()->json(['message' => 'Credenciales inválidas'], 401);
        }

        if ($user->status === 'suspended') {
            return response()->json(['message' => 'Esta cuenta se encuentra suspendida temporalmente'], 403);
        }

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'user' => $user->load(['role', 'vipLevel']),
        ]);
    }

    /**
     * Perfil del usuario autenticado
     */
    public function profile(Request $request)
    {
        $user = $request->user()->load(['role', 'vipLevel']);

        // 1. Obtener tiquetes de acción (Sorteo Mayor)
        $actionTickets = \App\Models\ActionTicket::where('user_id', $user->id)
            ->with('raffle')
            ->get()
            ->map(function ($ticket) {
                return [
                    'id' => $ticket->id,
                    'raffle_id' => $ticket->raffle_id,
                    'ticket_number' => $ticket->ticket_number,
                    'status' => 'sold',
                    'raffle_title' => $ticket->raffle->title,
                    'draw_date' => $ticket->raffle->draw_date,
                    'sold_at' => $ticket->created_at,
                    'expires_at' => null,
                    'rarity' => $ticket->rarity,
                    'raffle_image' => ($ticket->raffle->images_json && count($ticket->raffle->images_json) > 0)
                        ? ((str_starts_with($ticket->raffle->images_json[0], 'http') || str_starts_with($ticket->raffle->images_json[0], 'https'))
                            ? $ticket->raffle->images_json[0]
                            : asset('storage/' . $ticket->raffle->images_json[0]))
                        : null,
                ];
            });

        // 2. Obtener otras aperturas de cofre (premios que no son tiquetes de acción)
        $otherOpenings = \App\Models\ChestOpening::where('user_id', $user->id)
            ->with(['raffle', 'chestPrize'])
            ->whereHas('chestPrize', function ($query) {
                $query->where('type', '!=', 'action');
            })
            ->get()
            ->map(function ($opening) {
                $prize = $opening->chestPrize;
                $prefix = '';
                if ($prize) {
                    if ($prize->type === 'wallet_credit') {
                        $prefix = '💰 ₡' . number_format($prize->value, 0, ',', '.') . ' Wallet';
                    } elseif ($prize->type === 'extra_key') {
                        $prefix = '🔑 Llave Extra';
                    } else {
                        $prefix = '🎁 ' . $prize->name;
                    }
                } else {
                    $prefix = '🎁 Premio';
                }

                return [
                    'id' => $opening->id + 100000, // Evitar colisión de IDs
                    'raffle_id' => $opening->raffle_id,
                    'ticket_number' => $prefix,
                    'status' => 'sold',
                    'raffle_title' => $opening->raffle ? $opening->raffle->title : 'Sorteo',
                    'draw_date' => $opening->raffle ? $opening->raffle->draw_date : null,
                    'sold_at' => $opening->created_at,
                    'expires_at' => null,
                    'rarity' => null,
                    'raffle_image' => ($opening->raffle && $opening->raffle->images_json && count($opening->raffle->images_json) > 0)
                        ? ((str_starts_with($opening->raffle->images_json[0], 'http') || str_starts_with($opening->raffle->images_json[0], 'https'))
                            ? $opening->raffle->images_json[0]
                            : asset('storage/' . $opening->raffle->images_json[0]))
                        : null,
                ];
            });

        // 3. Fusionar y ordenar por fecha de obtención descendente
        $tickets = $actionTickets->concat($otherOpenings)->sortByDesc('sold_at')->values();

        return response()->json([
            'user' => $user,
            'tickets' => $tickets,
        ]);
    }

    /**
     * Actualizar perfil del usuario autenticado
     */
    public function updateProfile(Request $request)
    {
        $user = $request->user();

        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|required|string|max:255',
            'cedula' => 'nullable|string|max:50',
            'phone' => 'nullable|string|max:30',
            'current_password' => 'nullable|string',
            'new_password' => 'nullable|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Error de validación',
                'errors' => $validator->errors()
            ], 422);
        }

        // Si se envió new_password, validar current_password
        if ($request->filled('new_password')) {
            if (!$request->filled('current_password') || !Hash::check($request->current_password, $user->password)) {
                return response()->json([
                    'message' => 'La contraseña actual es incorrecta.',
                    'errors' => ['current_password' => ['La contraseña actual es incorrecta.']]
                ], 422);
            }
            $user->password = Hash::make($request->new_password);
        }

        if ($request->has('name')) {
            $user->name = $request->name;
        }
        if ($request->has('cedula')) {
            $user->cedula = $request->cedula;
        }
        if ($request->has('phone')) {
            $user->phone = $request->phone;
        }

        $user->save();

        return response()->json([
            'message' => 'Perfil actualizado correctamente',
            'user' => $user->load(['role', 'vipLevel']),
        ]);
    }

    /**
     * Listar sorteos activos
     */
    public function listRaffles()
    {
        $raffles = Raffle::where('status', 'active')
            ->orderBy('draw_date', 'asc')
            ->get()
            ->map(function ($raffle) {
                // Calcular porcentaje vendido basado en acciones emitidas
                $sold = \App\Models\ActionTicket::where('raffle_id', $raffle->id)->count();
                $percentage = $raffle->total_tickets > 0 ? round(($sold / $raffle->total_tickets) * 100) : 0;

                return [
                    'id' => $raffle->id,
                    'title' => $raffle->title,
                    'description' => $raffle->description,
                    'commercial_value' => $raffle->commercial_value,
                    'ticket_price' => $raffle->ticket_price,
                    'draw_date' => $raffle->draw_date,
                    'total_tickets' => $raffle->total_tickets,
                    'sold_tickets' => $sold,
                    'percentage_sold' => $percentage,
                    'type' => $raffle->type,
                    'image' => ($raffle->images_json && count($raffle->images_json) > 0)
                        ? ((str_starts_with($raffle->images_json[0], 'http') || str_starts_with($raffle->images_json[0], 'https'))
                            ? $raffle->images_json[0]
                            : asset('storage/'.$raffle->images_json[0]))
                        : null,
                ];
            });

        return response()->json($raffles);
    }

    /**
     * Listar banners promocionales activos
     */
    public function listBanners()
    {
        $banners = Banner::where('is_active', true)
            ->where(function ($query) {
                $query->whereNull('start_date')
                    ->orWhere('start_date', '<=', now());
            })
            ->where(function ($query) {
                $query->whereNull('end_date')
                    ->orWhere('end_date', '>=', now());
            })
            ->orderBy('sort_order', 'asc')
            ->get()
            ->map(function ($banner) {
                return [
                    'id' => $banner->id,
                    'title' => $banner->title,
                    'subtitle' => $banner->subtitle,
                    'image' => (str_starts_with($banner->image_path, 'http') || str_starts_with($banner->image_path, 'https'))
                        ? $banner->image_path
                        : asset('storage/'.$banner->image_path),
                    'action_type' => $banner->action_type,
                    'action_value' => $banner->action_value,
                ];
            });

        return response()->json($banners);
    }

    /**
     * Listar historias / reels activos
     */
    public function listStories()
    {
        $stories = Story::where('is_active', true)
            ->where(function ($query) {
                $query->whereNull('expires_at')
                    ->orWhere('expires_at', '>=', now());
            })
            ->orderBy('sort_order', 'asc')
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($story) {
                return [
                    'id' => $story->id,
                    'title' => $story->title,
                    'media_url' => (str_starts_with($story->media_path, 'http') || str_starts_with($story->media_path, 'https'))
                        ? $story->media_path
                        : asset('storage/' . $story->media_path),
                    'media_type' => $story->media_type,
                    'button_text' => $story->button_text,
                    'action_type' => $story->action_type,
                    'action_value' => $story->action_value,
                ];
            });

        return response()->json($stories);
    }

    /**
     * Obtener detalle de un sorteo y el mapa de sus boletos
     */
    public function showRaffle(Raffle $raffle)
    {
        $raffle->load(['winnerUser:id,name', 'winnerActionTicket:id,ticket_number']);
        $user = auth('sanctum')->user();
        $userKeysCount = 0;
        $userActionsCount = 0;

        if ($user) {
            $userKeysCount = \App\Models\UserKey::where('user_id', $user->id)
                ->where('raffle_id', $raffle->id)
                ->value('quantity') ?? 0;

            $userActionsCount = \App\Models\ActionTicket::where('user_id', $user->id)
                ->where('raffle_id', $raffle->id)
                ->count();
        }

        $chestPrizes = \App\Models\ChestPrize::where('raffle_id', $raffle->id)
            ->get()
            ->map(function ($prize) {
                return [
                    'id' => $prize->id,
                    'name' => $prize->name,
                    'type' => $prize->type,
                    'value' => (double)$prize->value,
                    'probability' => (double)$prize->probability,
                    'total_quantity' => $prize->total_quantity,
                    'remaining_quantity' => $prize->remaining_quantity,
                    'image_path' => $prize->image_path ? (str_starts_with($prize->image_path, 'http') ? $prize->image_path : asset('storage/'.$prize->image_path)) : null,
                ];
            });

        $sold = \App\Models\ActionTicket::where('raffle_id', $raffle->id)->count();
        $total = $raffle->total_tickets;
        $percentage = $total > 0 ? round(($sold / $total) * 100) : 0;

        return response()->json([
            'raffle' => [
                'id' => $raffle->id,
                'title' => $raffle->title,
                'description' => $raffle->description,
                'commercial_value' => $raffle->commercial_value,
                'fiscal_value' => $raffle->fiscal_value,
                'ticket_price' => $raffle->ticket_price,
                'draw_date' => $raffle->draw_date,
                'total_tickets' => $total,
                'sold_tickets' => $sold,
                'percentage_sold' => $percentage,
                'type' => $raffle->type,
                'status' => $raffle->status ?? 'active',
                'winner_name' => $raffle->winnerUser ? $raffle->winnerUser->name : null,
                'winner_ticket_number' => $raffle->winnerActionTicket ? $raffle->winnerActionTicket->ticket_number : null,
                'rules' => $raffle->rules ? explode("\n", $raffle->rules) : [],
                'images' => $raffle->images_json ? array_map(fn ($img) => (str_starts_with($img, 'http') || str_starts_with($img, 'https')) ? $img : asset('storage/'.$img), $raffle->images_json) : [],
                'video_url' => $raffle->video_url,
                'transparency_docs' => [
                    'invoice' => $raffle->invoice_path ? asset('storage/'.$raffle->invoice_path) : null,
                    'vehicle_docs' => $raffle->vehicle_docs_path ? asset('storage/'.$raffle->vehicle_docs_path) : null,
                    'marchamo' => $raffle->marchamo_path ? asset('storage/'.$raffle->marchamo_path) : null,
                    'inspection' => $raffle->inspection_path ? asset('storage/'.$raffle->inspection_path) : null,
                ],
            ],
            'chest_prizes' => $chestPrizes,
            'rarity_config' => $raffle->effectiveRarityConfig(),
            'discount_tiers' => $raffle->effectiveDiscountTiers(),
            'user_keys' => $userKeysCount,
            'user_actions' => $userActionsCount,
        ]);
    }

    /**
     * Cotización de compra: precio con descuento por volumen (configurable por sorteo)
     */
    public function quotePurchase(Request $request, \App\Services\CardShopService $shop)
    {
        $validator = Validator::make($request->all(), [
            'raffle_id' => 'required|exists:raffles,id',
            'quantity' => 'required|integer|min:1|max:100',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $raffle = Raffle::find($request->raffle_id);

        return response()->json([
            'quote' => $shop->quote($raffle, (int) $request->quantity),
            'discount_tiers' => $raffle->effectiveDiscountTiers(),
        ]);
    }

    /**
     * Reserva de tarjetas coleccionables: el usuario elige números únicos
     * (0 .. total_tickets - 1) que quedan retenidos mientras paga.
     */
    public function reserveTickets(Request $request, \App\Services\CardShopService $shop)
    {
        $validator = Validator::make($request->all(), [
            'raffle_id' => 'required|exists:raffles,id',
            'card_numbers' => 'required|array|min:1|max:100',
            'card_numbers.*' => 'required|string',
            'reseller_code' => 'nullable|string', // Si lo hace a través de un revendedor
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $user = $request->user();
        $raffle = Raffle::find($request->raffle_id);

        if ($raffle->status !== 'active') {
            return response()->json(['message' => 'Este sorteo no está disponible para compras.'], 422);
        }

        // Validar formato, rango y disponibilidad de los números elegidos
        try {
            $cardNumbers = $shop->validateNumbers($raffle, $request->card_numbers);
        } catch (\InvalidArgumentException $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }

        // Buscar el revendedor si se provee código
        $resellerId = null;
        if ($request->filled('reseller_code')) {
            $reseller = ResellerProfile::where('reseller_code', $request->reseller_code)->first();
            if ($reseller) {
                $resellerId = $reseller->id;
            }
        }

        $quote = $shop->quote($raffle, count($cardNumbers));

        return DB::transaction(function () use ($user, $raffle, $cardNumbers, $quote, $resellerId, $shop) {
            // Re-validar dentro de la transacción para evitar carreras
            $taken = $shop->takenNumbers($raffle, $cardNumbers);
            if (count($taken) > 0) {
                return response()->json([
                    'message' => 'Estos números ya no están disponibles: ' . implode(', ', $taken) . '. Por favor elige otros.',
                ], 422);
            }

            $transaction = Transaction::create([
                'user_id' => $user->id,
                'raffle_id' => $raffle->id,
                'reseller_id' => $resellerId,
                'quantity' => count($cardNumbers),
                'card_numbers' => $cardNumbers,
                'amount' => $quote['total'],
                'type' => 'purchase',
                'payment_method' => 'sinpe', // Default inicial
                'status' => 'pending',
            ]);

            return response()->json([
                'message' => 'Tarjetas reservadas con éxito',
                'transaction_id' => $transaction->id,
                'card_numbers' => $cardNumbers,
                'quote' => $quote,
                'amount_to_pay' => $quote['total'],
                'quantity' => count($cardNumbers),
                'expires_at' => now()->addMinutes(\App\Services\CardShopService::HOLD_MINUTES)->toIso8601String(),
            ], 201);
        });
    }

    /**
     * Tarjetas emitidas de una compra (para la pantalla de revelación).
     * Al consultarlas quedan marcadas como reveladas.
     */
    public function transactionCards(Request $request, Transaction $transaction)
    {
        if ($transaction->user_id !== $request->user()->id) {
            return response()->json(['message' => 'Transacción no encontrada'], 404);
        }

        $cards = \App\Models\ActionTicket::where('transaction_id', $transaction->id)
            ->get()
            ->map(fn ($card) => $this->cardPayload($card, $transaction->raffle));

        \App\Models\ActionTicket::where('transaction_id', $transaction->id)
            ->whereNull('revealed_at')
            ->update(['revealed_at' => now()]);

        return response()->json([
            'status' => $transaction->status,
            'cards' => $cards,
        ]);
    }

    /**
     * Tarjetas del usuario pendientes de revelar (compras aprobadas por
     * el administrador que aún no se han descubierto en la app).
     */
    public function pendingCards(Request $request)
    {
        $cards = \App\Models\ActionTicket::where('user_id', $request->user()->id)
            ->whereNull('revealed_at')
            ->with('raffle')
            ->orderBy('created_at')
            ->get()
            ->map(fn ($card) => $this->cardPayload($card));

        return response()->json([
            'cards' => $cards,
            'count' => $cards->count(),
        ]);
    }

    /**
     * Marcar tarjetas como reveladas (cuando el usuario las descubre).
     */
    public function revealCards(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'card_ids' => 'required|array|min:1',
            'card_ids.*' => 'integer',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $updated = \App\Models\ActionTicket::where('user_id', $request->user()->id)
            ->whereIn('id', $request->card_ids)
            ->whereNull('revealed_at')
            ->update(['revealed_at' => now()]);

        return response()->json(['revealed' => $updated]);
    }

    /**
     * Resumen de álbumes del usuario: un álbum por cada sorteo donde
     * tiene tarjetas, con conteos y pendientes de revelar.
     */
    public function myAlbums(Request $request)
    {
        $user = $request->user();

        $raffleIds = \App\Models\ActionTicket::where('user_id', $user->id)
            ->distinct()
            ->pluck('raffle_id');

        $albums = Raffle::whereIn('id', $raffleIds)
            ->orderBy('draw_date', 'desc')
            ->get()
            ->map(function ($raffle) use ($user) {
                $cards = \App\Models\ActionTicket::where('user_id', $user->id)
                    ->where('raffle_id', $raffle->id);

                $total = (clone $cards)->count();
                $pending = (clone $cards)->whereNull('revealed_at')->count();
                $userKeys = \App\Models\UserKey::where('user_id', $user->id)
                    ->where('raffle_id', $raffle->id)
                    ->value('quantity') ?? 0;

                return [
                    'raffle_id' => $raffle->id,
                    'raffle_title' => $raffle->title,
                    'raffle_status' => $raffle->status,
                    'draw_date' => $raffle->draw_date,
                    'raffle_image' => ($raffle->images_json && count($raffle->images_json) > 0)
                        ? ((str_starts_with($raffle->images_json[0], 'http') || str_starts_with($raffle->images_json[0], 'https'))
                            ? $raffle->images_json[0]
                            : asset('storage/' . $raffle->images_json[0]))
                        : null,
                    'cards_count' => $total,
                    'pending_count' => $pending,
                    'user_keys' => $userKeys,
                ];
            });

        return response()->json(['albums' => $albums]);
    }

    /**
     * Pagar la compra de tarjetas. Las tarjetas solo pueden pagarse con el
     * saldo de la billetera (la billetera se recarga por SINPE/Tilopay).
     */
    public function submitPurchasePayment(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'transaction_id' => 'required|exists:transactions,id',
            'payment_method' => 'required|in:wallet,sinpe',
            'payment_reference' => 'required_if:payment_method,sinpe|string|nullable',
            'payment_screenshot' => 'required_if:payment_method,sinpe|file|image|max:4096|nullable',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $user = $request->user();
        $transaction = Transaction::where('id', $request->transaction_id)
            ->where('user_id', $user->id)
            ->where('status', 'pending')
            ->first();

        if (! $transaction) {
            return response()->json(['message' => 'Transacción inválida o ya procesada'], 404);
        }

        if ($request->payment_method === 'wallet') {
            if ($user->wallet_balance < $transaction->amount) {
                return response()->json(['message' => 'Saldo de wallet insuficiente para completar la compra'], 422);
            }

            return DB::transaction(function () use ($user, $transaction) {
                $user->decrement('wallet_balance', $transaction->amount);

                $transaction->update([
                    'payment_method' => 'wallet',
                    'payment_reference' => 'WALLET-DEBIT',
                    'status' => 'approved',
                    'approved_at' => now(),
                ]);

                return response()->json([
                    'message' => 'Pago realizado con éxito usando el saldo de tu billetera',
                    'transaction' => $transaction->refresh(),
                ]);
            });
        } else {
            $screenshotPath = null;
            if ($request->hasFile('payment_screenshot')) {
                $screenshotPath = $request->file('payment_screenshot')->store('payments', 'public');
            }

            $transaction->update([
                'payment_method' => 'sinpe',
                'payment_reference' => $request->payment_reference,
                'payment_screenshot' => $screenshotPath,
                'status' => 'pending',
            ]);

            return response()->json([
                'message' => 'Comprobante de SINPE registrado con éxito. Esperando aprobación del administrador.',
                'transaction' => $transaction->refresh(),
            ]);
        }
    }
    /**
     * Abrir cofres con llaves: cada llave abre un cofre y entrega un premio
     * de la tabla de premios del sorteo según su % de probabilidad.
     */
    public function openChest(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'raffle_id' => 'required|exists:raffles,id',
            'keys_to_open' => 'nullable|integer|min:1|max:20',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $user = $request->user();
        $raffle = Raffle::find($request->raffle_id);
        $keysToOpen = (int) $request->input('keys_to_open', 1);

        // Balance de llaves del usuario para este sorteo
        $userKey = \App\Models\UserKey::where('user_id', $user->id)
            ->where('raffle_id', $raffle->id)
            ->first();

        if (! $userKey || $userKey->quantity < $keysToOpen) {
            return response()->json(['message' => 'No cuentas con suficientes llaves para abrir cofres.'], 422);
        }

        return DB::transaction(function () use ($user, $raffle, $userKey, $keysToOpen) {
            $wonPrizes = [];

            for ($i = 0; $i < $keysToOpen; $i++) {
                // 1. Consumir la llave
                $userKey->decrement('quantity');

                // 2. Sortear premio del cofre por probabilidad (solo premios con stock)
                $prize = $this->rollChestPrize($raffle);

                // 3. Entregar el premio
                $prizeName = 'Cofre vacío';
                $prizeType = 'empty';
                $prizeValue = 0.0;
                $prizeImage = null;

                if ($prize) {
                    $prizeName = $prize->name;
                    $prizeType = $prize->type;
                    $prizeValue = (float) $prize->value;
                    $prizeImage = $prize->image_path
                        ? (str_starts_with($prize->image_path, 'http') ? $prize->image_path : asset('storage/' . $prize->image_path))
                        : null;

                    if ($prize->total_quantity > 0) {
                        $prize->decrement('remaining_quantity');
                    }

                    if ($prize->type === 'wallet_credit') {
                        $user->increment('wallet_balance', $prize->value);
                    } elseif ($prize->type === 'extra_key') {
                        $extraKeys = max(1, (int) $prize->value);
                        $userKey->increment('quantity', $extraKeys);
                    }
                    // physical_prize: queda registrado en chest_openings para coordinación manual

                    \App\Models\ChestOpening::create([
                        'user_id' => $user->id,
                        'raffle_id' => $raffle->id,
                        'chest_prize_id' => $prize->id,
                    ]);
                }

                $wonPrizes[] = [
                    'id' => $prize?->id,
                    'name' => $prizeName,
                    'type' => $prizeType,
                    'value' => $prizeValue,
                    'image_path' => $prizeImage,
                ];
            }

            // Enviar notificación push de resumen
            try {
                \App\Services\FcmService::sendNotification(
                    $user,
                    '¡Cofres Abiertos! 🗝️',
                    'Abriste ' . count($wonPrizes) . ' cofre(s). Revisa tus premios en la app.'
                );
            } catch (\Exception $e) {
                // Ignorar error de FCM para no revertir la transacción
            }

            return response()->json([
                'message' => '¡Cofre(s) abierto(s) con éxito!',
                'prizes' => $wonPrizes,
                'user_keys' => $userKey->fresh()->quantity,
                'wallet_balance' => $user->fresh()->wallet_balance,
            ]);
        });
    }

    /**
     * Sortea un premio de cofre por probabilidad. Los premios sin stock se
     * excluyen. Si la suma de probabilidades es menor a 100, el resto es
     * "cofre vacío" (sin premio).
     */
    private function rollChestPrize(Raffle $raffle): ?\App\Models\ChestPrize
    {
        $prizes = \App\Models\ChestPrize::where('raffle_id', $raffle->id)
            ->where('type', '!=', 'action')
            ->where(function ($q) {
                $q->where('total_quantity', '<=', 0) // 0 = stock ilimitado
                    ->orWhere('remaining_quantity', '>', 0);
            })
            ->get();

        if ($prizes->isEmpty()) {
            return null;
        }

        $totalWeight = max(100.0, (float) $prizes->sum('probability'));
        $roll = mt_rand(1, (int) round($totalWeight * 100)) / 100;
        $accumulated = 0.0;

        foreach ($prizes as $prize) {
            $accumulated += (float) $prize->probability;
            if ($roll <= $accumulated) {
                return $prize;
            }
        }

        return null; // Cofre vacío
    }

    /**
     * Álbum de tarjetas coleccionadas del usuario para un sorteo.
     */
    public function raffleAlbum(Request $request, Raffle $raffle)
    {
        $user = $request->user();

        // Solo tarjetas ya reveladas; las pendientes se muestran aparte
        $cards = \App\Models\ActionTicket::where('user_id', $user->id)
            ->where('raffle_id', $raffle->id)
            ->whereNotNull('revealed_at')
            ->orderBy('ticket_number')
            ->get()
            ->map(fn ($card) => $this->cardPayload($card, $raffle));

        $pendingCount = \App\Models\ActionTicket::where('user_id', $user->id)
            ->where('raffle_id', $raffle->id)
            ->whereNull('revealed_at')
            ->count();

        $rarityOrder = ['mythic', 'legendary', 'epic', 'rare', 'uncommon', 'common'];
        $byRarity = [];
        foreach ($rarityOrder as $rarity) {
            $byRarity[$rarity] = $cards->where('rarity', $rarity)->count();
        }

        $totalSold = \App\Models\ActionTicket::where('raffle_id', $raffle->id)->count();
        $userKeysCount = \App\Models\UserKey::where('user_id', $user->id)
            ->where('raffle_id', $raffle->id)
            ->value('quantity') ?? 0;

        return response()->json([
            'raffle' => [
                'id' => $raffle->id,
                'title' => $raffle->title,
                'draw_date' => $raffle->draw_date,
                'total_tickets' => $raffle->total_tickets,
                'sold_tickets' => $totalSold,
            ],
            'cards' => $cards->values(),
            'cards_count' => $cards->count(),
            'pending_count' => $pendingCount,
            'by_rarity' => $byRarity,
            'user_keys' => $userKeysCount,
        ]);
    }

    /**
     * Serializa una tarjeta coleccionable para el API.
     */
    private function cardPayload(\App\Models\ActionTicket $card, ?Raffle $raffle = null): array
    {
        $raffle = $raffle ?? $card->raffle;

        return [
            'id' => $card->id,
            'raffle_id' => $card->raffle_id,
            'ticket_number' => $card->ticket_number,
            'rarity' => $card->rarity,
            'keys_granted' => $card->keys_granted,
            'revealed' => $card->revealed_at !== null,
            'obtained_at' => $card->created_at,
            'raffle_title' => $raffle?->title,
            'raffle_image' => ($raffle && $raffle->images_json && count($raffle->images_json) > 0)
                ? ((str_starts_with($raffle->images_json[0], 'http') || str_starts_with($raffle->images_json[0], 'https'))
                    ? $raffle->images_json[0]
                    : asset('storage/' . $raffle->images_json[0]))
                : null,
        ];
    }

    /**
     * Historial de transacciones de Wallet
     */
    public function walletHistory(Request $request)
    {
        $user = $request->user();
        $transactions = Transaction::where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json($transactions);
    }

    /**
     * Solicitud de retiro de fondos de Wallet
     */
    public function requestWithdrawal(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'amount' => 'required|numeric|min:1',
            'sinpe_phone' => 'required|string',
            'sinpe_owner' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $user = $request->user();
        $amount = (double)$request->amount;

        if ($user->wallet_balance < $amount) {
            return response()->json(['message' => 'Saldo insuficiente para realizar el retiro.'], 422);
        }

        return DB::transaction(function () use ($user, $amount, $request) {
            // Restar saldo de billetera
            $user->decrement('wallet_balance', $amount);

            // Crear transacción de retiro
            $transaction = Transaction::create([
                'user_id' => $user->id,
                'amount' => $amount,
                'type' => 'withdrawal',
                'payment_method' => 'sinpe',
                'status' => 'pending',
                'payment_reference' => 'Retiro SINPE a: ' . $request->sinpe_phone . ' (' . $request->sinpe_owner . ')',
            ]);

            \App\Services\AdminNotificationService::notifyPendingTransaction($transaction);

            return response()->json([
                'message' => 'Solicitud de retiro registrada con éxito',
                'transaction_id' => $transaction->id,
                'remaining_balance' => $user->wallet_balance,
            ], 201);
        });
    }

    /**
     * Dashboard del revendedor
     */
    public function resellerDashboard(Request $request)
    {
        $user = $request->user();
        $resellerProfile = $user->resellerProfile;

        if (!$resellerProfile) {
            return response()->json(['message' => 'El usuario no está registrado como revendedor'], 403);
        }

        // Cargar estadísticas
        $commissionEarned = Transaction::where('reseller_id', $resellerProfile->id)
            ->where('status', 'approved')
            ->sum('amount') * ($resellerProfile->commission_percentage / 100);

        $salesCount = Transaction::where('reseller_id', $resellerProfile->id)
            ->where('status', 'approved')
            ->count();

        $recentSales = Transaction::where('reseller_id', $resellerProfile->id)
            ->with('user:id,name')
            ->orderBy('created_at', 'desc')
            ->take(10)
            ->get();

        return response()->json([
            'reseller_code' => $resellerProfile->reseller_code,
            'commission_preference' => $resellerProfile->commission_preference ?? 'cash',
            'custom_link' => $resellerProfile->custom_link ?: ('https://wincard.kapix.co.cr/register?ref=' . $resellerProfile->reseller_code),
            'commission_percentage' => $resellerProfile->commission_percentage,
            'commission_earned' => $commissionEarned,
            'sales_count' => $salesCount,
            'recent_sales' => $recentSales,
        ]);
    }

    /**
     * Código de referido propio, referidos y ganancias por comisión de afiliado
     * (10% acreditado automáticamente cuando un referido compra, ver TransactionObserver).
     */
    public function myReferrals(Request $request)
    {
        $user = $request->user();

        if (!$user->referral_code) {
            $user->referral_code = User::generateUniqueReferralCode($user->name);
            $user->save();
        }

        $referrals = $user->referrals()
            ->withCount(['transactions as purchases_count' => function ($q) {
                $q->where('type', 'purchase')->where('status', 'approved');
            }])
            ->get()
            ->map(function ($referred) use ($user) {
                return [
                    'id' => $referred->id,
                    'name' => $referred->name,
                    'joined_at' => $referred->created_at,
                    'has_purchased' => $referred->purchases_count > 0,
                    'earned_from_this_referral' => (float) Transaction::where('user_id', $user->id)
                        ->where('type', 'commission_payout')
                        ->where('payment_reference', "AFILIADO-NIVEL1-COMPRA-{$referred->id}")
                        ->sum('amount'),
                ];
            });

        $totalEarned = (float) Transaction::where('user_id', $user->id)
            ->where('type', 'commission_payout')
            ->where('payment_reference', 'like', 'AFILIADO-NIVEL1-COMPRA-%')
            ->sum('amount');

        return response()->json([
            'referral_code' => $user->referral_code,
            'total_referrals' => $referrals->count(),
            'total_earned' => $totalEarned,
            'referrals' => $referrals,
        ]);
    }

    /**
     * Actualizar token FCM para notificaciones push
     */
    public function updateFcmToken(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'fcm_token' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $user = $request->user();
        $user->fcm_token = $request->fcm_token;
        $user->save();

        return response()->json(['message' => 'Token FCM actualizado con éxito']);
    }

    /**
     * Registrar solicitud de recarga de wallet mediante SINPE Móvil local
     */
    public function requestDeposit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'amount' => 'required|numeric|min:100',
            'payment_reference' => 'required|string',
            'payment_screenshot' => 'required|file|image|max:4096',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $user = $request->user();
        $amount = (double)$request->amount;

        $screenshotPath = null;
        if ($request->hasFile('payment_screenshot')) {
            $screenshotPath = $request->file('payment_screenshot')->store('payments', 'public');
        }

        $transaction = Transaction::create([
            'user_id' => $user->id,
            'amount' => $amount,
            'type' => 'deposit',
            'payment_method' => 'sinpe',
            'status' => 'pending',
            'payment_reference' => $request->payment_reference,
            'payment_screenshot' => $screenshotPath,
        ]);

        \App\Services\AdminNotificationService::notifyPendingTransaction($transaction);

        return response()->json([
            'message' => 'Solicitud de recarga de wallet registrada con éxito para revisión.',
            'transaction_id' => $transaction->id,
        ], 201);
    }

    /**
     * Obtener listado de ganadores (Sorteo Mayor e Historial de aperturas recientes)
     */
    public function winners()
    {
        // 1. Ganadores del sorteo mayor
        $grandWinners = \App\Models\Raffle::whereNotNull('winner_user_id')
            ->with(['winnerUser:id,name', 'winnerActionTicket:id,ticket_number,rarity'])
            ->orderBy('draw_date', 'desc')
            ->get()
            ->map(function ($raffle) {
                $image = ($raffle->images_json && count($raffle->images_json) > 0)
                    ? ((str_starts_with($raffle->images_json[0], 'http') || str_starts_with($raffle->images_json[0], 'https'))
                        ? $raffle->images_json[0]
                        : asset('storage/' . $raffle->images_json[0]))
                    : null;
                return [
                    'id' => $raffle->id,
                    'raffle_id' => $raffle->id,
                    'title' => $raffle->title,
                    'raffle_title' => $raffle->title,
                    'image' => $image,
                    'raffle_image' => $image,
                    'winner_name' => $raffle->winnerUser ? $raffle->winnerUser->name : 'Anónimo',
                    'ticket_number' => $raffle->winnerActionTicket ? $raffle->winnerActionTicket->ticket_number : 'N/A',
                    'rarity' => $raffle->winnerActionTicket ? $raffle->winnerActionTicket->rarity : 'common',
                    'draw_date' => $raffle->draw_date ? $raffle->draw_date->toIso8601String() : now()->toIso8601String(),
                ];
            });

        // 2. Historial de aperturas recientes en tiempo real
        $realtimeWinners = \App\Models\ChestOpening::with(['user:id,name', 'raffle:id,title', 'chestPrize'])
            ->orderBy('created_at', 'desc')
            ->take(15)
            ->get()
            ->map(function ($opening) {
                $prize = $opening->chestPrize;
                $rarity = 'common';
                $ticketNumber = null;

                if ($prize && $prize->type === 'action') {
                    $ticket = \App\Models\ActionTicket::where('user_id', $opening->user_id)
                        ->where('raffle_id', $opening->raffle_id)
                        ->where('chest_prize_id', $prize->id)
                        ->where('created_at', '>=', $opening->created_at->subSeconds(2))
                        ->first();
                    if ($ticket) {
                        $rarity = $ticket->rarity;
                        $ticketNumber = $ticket->ticket_number;
                    }
                }

                $prizeName = 'Premio';
                if ($prize) {
                    if ($prize->type === 'wallet_credit') {
                        $prizeName = '💰 ₡' . number_format($prize->value, 0, ',', '.') . ' Wallet';
                    } elseif ($prize->type === 'extra_key') {
                        $prizeName = '🔑 Llave Extra';
                    } elseif ($prize->type === 'action') {
                        $prizeName = '🎴 Tarjeta Coleccionable';
                    } else {
                        $prizeName = '🎁 ' . $prize->name;
                    }
                }

                return [
                    'id' => $opening->id,
                    'user_name' => $opening->user ? $opening->user->name : 'Anónimo',
                    'user_id' => $opening->user_id,
                    'raffle_id' => $opening->raffle_id,
                    'raffle_title' => $opening->raffle ? $opening->raffle->title : 'Sorteo',
                    'prize_name' => $prizeName,
                    'prize_type' => $prize ? $prize->type : 'unknown',
                    'ticket_number' => $ticketNumber ?? ($ticketNumber = $opening->id ? 'REF-' . str_pad($opening->id, 4, '0', STR_PAD_LEFT) : ''),
                    'rarity' => $rarity,
                    'created_at' => $opening->created_at->toIso8601String(),
                ];
            });

        return response()->json([
            'grand_winners' => $grandWinners,
            'realtime_winners' => $realtimeWinners,
        ]);
    }

    /**
     * Generar números disponibles al azar para el sorteo especificado.
     * Acepta ?count=N (por defecto 1) para selección rápida de varias tarjetas.
     */
    public function getAvailableNumber(Request $request, \App\Models\Raffle $raffle, \App\Services\CardShopService $shop)
    {
        $count = min(100, max(1, (int) $request->query('count', 1)));
        $numbers = $shop->randomAvailableNumbers($raffle, $count);

        if (count($numbers) === 0) {
            return response()->json(['message' => 'No quedan números disponibles en este sorteo.'], 422);
        }

        return response()->json([
            'number' => $numbers[0],
            'numbers' => $numbers,
        ]);
    }

    /**
     * Listado paginado de números del sorteo con su disponibilidad
     * (vitrina de tarjetas para comprar).
     */
    public function listNumbers(Request $request, \App\Models\Raffle $raffle, \App\Services\CardShopService $shop)
    {
        $perPage = min(200, max(10, (int) $request->query('per_page', 40)));
        $maxVal = max(1, $raffle->total_tickets - 1);
        $digits = strlen((string) $maxVal);
        $lastPage = (int) ceil(($maxVal + 1) / $perPage);
        $page = min($lastPage, max(1, (int) $request->query('page', 1)));
        $start = ($page - 1) * $perPage;
        $end = min($maxVal, $start + $perPage - 1);

        $numbers = [];
        for ($i = $start; $i <= $end; $i++) {
            $numbers[] = str_pad((string) $i, $digits, '0', STR_PAD_LEFT);
        }

        $taken = $shop->takenNumbers($raffle, $numbers);

        return response()->json([
            'page' => $page,
            'per_page' => $perPage,
            'last_page' => $lastPage,
            'total' => $maxVal + 1,
            'numbers' => array_map(fn ($n) => [
                'number' => $n,
                'available' => ! in_array($n, $taken, true),
            ], $numbers),
        ]);
    }

    /**
     * Verificar disponibilidad de números específicos elegidos por el usuario.
     */
    public function checkNumbers(Request $request, \App\Models\Raffle $raffle, \App\Services\CardShopService $shop)
    {
        $validator = Validator::make($request->all(), [
            'numbers' => 'required|array|min:1|max:100',
            'numbers.*' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        try {
            $normalized = $shop->validateNumbers($raffle, $request->numbers);

            return response()->json(['available' => true, 'numbers' => $normalized]);
        } catch (\InvalidArgumentException $e) {
            return response()->json(['available' => false, 'message' => $e->getMessage()], 422);
        }
    }

    /**
     * Enviar solicitud para ser revendedor.
     */
    public function applyAsReseller(Request $request)
    {
        $user = $request->user();

        // Verificar si ya es revendedor
        if ($user->role && $user->role->name === 'reseller') {
            return response()->json(['message' => 'Ya eres un revendedor autorizado.'], 422);
        }

        // Verificar si tiene una solicitud pendiente
        $pendingRequest = \App\Models\ResellerRequest::where('user_id', $user->id)
            ->where('status', 'pending')
            ->first();

        if ($pendingRequest) {
            return response()->json(['message' => 'Ya tienes una solicitud pendiente de aprobación.'], 422);
        }

        // Validar
        $validator = Validator::make($request->all(), [
            'phone' => 'required|string|min:8|max:20',
            'notes' => 'nullable|string|max:1000',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        // Crear la solicitud
        $resellerRequest = \App\Models\ResellerRequest::create([
            'user_id' => $user->id,
            'phone' => $request->phone,
            'notes' => $request->notes,
            'status' => 'pending',
        ]);

        \App\Services\AdminNotificationService::notifyResellerRequest($resellerRequest);

        return response()->json([
            'message' => 'Solicitud enviada correctamente. Será revisada por un administrador.',
            'request' => $resellerRequest,
        ], 201);
    }

    /**
     * Obtener el estado actual de la solicitud de revendedor.
     */
    public function getResellerApplicationStatus(Request $request)
    {
        $user = $request->user();

        // Si ya es revendedor
        if ($user->role && $user->role->name === 'reseller') {
            return response()->json([
                'status' => 'approved',
                'message' => 'Tu perfil de revendedor está activo.',
            ]);
        }

        // Buscar última solicitud
        $latestRequest = \App\Models\ResellerRequest::where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->first();

        if (!$latestRequest) {
            return response()->json([
                'status' => 'none',
                'message' => 'No has enviado ninguna solicitud.',
            ]);
        }

        return response()->json([
            'status' => $latestRequest->status,
            'request' => $latestRequest,
        ]);
    }

    /**
     * Listar notificaciones del usuario autenticado.
     */
    public function listNotifications(Request $request)
    {
        $notifications = \App\Models\UserNotification::where('user_id', $request->user()->id)
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json($notifications);
    }

    /**
     * Marcar notificaciones como leídas.
     */
    public function markNotificationsRead(Request $request)
    {
        $user = $request->user();

        if ($request->has('notification_id')) {
            $notificationId = $request->input('notification_id');
            \App\Models\UserNotification::where('user_id', $user->id)
                ->where('id', $notificationId)
                ->update(['is_read' => true]);
        } else {
            \App\Models\UserNotification::where('user_id', $user->id)
                ->where('is_read', false)
                ->update(['is_read' => true]);
        }

        return response()->json(['message' => 'Notificaciones marcadas como leídas con éxito']);
    }

    /**
     * Obtener ajustes globales de la aplicación.
     */
    public function getSettings()
    {
        $settings = \App\Models\AppSetting::first();
        
        return response()->json([
            'wallet_enabled' => $settings ? (bool)$settings->wallet_enabled : true,
            'direct_payment_enabled' => $settings ? (bool)$settings->direct_payment_enabled : false,
        ]);
    }

    /**
     * Obtener mensajes del chat de soporte para el usuario.
     */
    public function getSupportMessages(Request $request)
    {
        $user = $request->user();

        $chat = \App\Models\SupportChat::firstOrCreate(
            ['user_id' => $user->id, 'status' => 'open'],
            ['last_message_at' => now()]
        );

        // Si es la primera vez que se crea el chat y no tiene mensajes, agregar mensaje de bienvenida
        if ($chat->messages()->count() === 0) {
            $chat->messages()->create([
                'sender_type' => 'bot',
                'message' => "¡Hola {$user->name}! 👋 Bienvenido al soporte oficial en vivo de Wincar Sorteos.\n¿En qué podemos ayudarte hoy?",
                'is_read' => true,
            ]);
        }

        // Marcar mensajes del soporte como leídos
        $chat->messages()->where('sender_type', '!=', 'user')->where('is_read', false)->update(['is_read' => true]);

        $messages = $chat->messages()
            ->orderBy('created_at', 'asc')
            ->get()
            ->map(function ($msg) {
                return [
                    'id' => $msg->id,
                    'text' => $msg->message,
                    'is_user' => $msg->sender_type === 'user',
                    'sender_type' => $msg->sender_type,
                    'timestamp' => $msg->created_at->toIso8601String(),
                ];
            });

        return response()->json([
            'status' => true,
            'chat_id' => $chat->id,
            'messages' => $messages,
        ]);
    }

    /**
     * Enviar un nuevo mensaje al chat de soporte.
     */
    public function sendSupportMessage(Request $request)
    {
        $request->validate([
            'message' => 'required|string|max:1000',
        ]);

        $user = $request->user();
        $messageText = trim($request->input('message'));

        $chat = \App\Models\SupportChat::firstOrCreate(
            ['user_id' => $user->id, 'status' => 'open'],
            ['last_message_at' => now()]
        );

        // Guardar mensaje enviado por el usuario
        $userMsg = $chat->messages()->create([
            'sender_id' => $user->id,
            'sender_type' => 'user',
            'message' => $messageText,
            'is_read' => false,
        ]);

        $chat->update(['last_message_at' => now()]);

        \App\Services\AdminNotificationService::notifySupportMessage($messageText, $user);

        // Respuesta automática del Bot de Soporte Wincar si coincide con palabras clave frecuentes
        $lower = strtolower($messageText);
        $autoResponse = null;

        if (str_contains($lower, 'recargar') || str_contains($lower, 'billetera') || str_contains($lower, 'saldo') || str_contains($lower, 'sinpe')) {
            $autoResponse = "💳 **Recargas de Billetera**:\nPuedes recargar tu saldo Wincar con tarjeta o transferencia SINPE Móvil directamente desde la sección 'Mi Billetera'. Los fondos se acreditarán inmediatamente al confirmar el comprobante.";
        } elseif (str_contains($lower, 'cofre') || str_contains($lower, 'llave') || str_contains($lower, 'premio')) {
            $autoResponse = "📦 **Cofres y Llaves**:\nAl comprar tarjetas obtienes llaves según la rareza obtenida. Con estas llaves abres cofres de premios y saldo adicional instantáneo.";
        } elseif (str_contains($lower, 'sorteo') || str_contains($lower, 'ganador') || str_contains($lower, 'fecha')) {
            $autoResponse = "🏆 **Sorteos Mayores**:\nLa fecha y hora oficial del sorteo se indica en cada vehículo. Al realizarse el sorteo, la notificación push se enviará al ganador y aparecerá en la sección de 'Ganadores'.";
        }

        if ($autoResponse) {
            $chat->messages()->create([
                'sender_type' => 'bot',
                'message' => $autoResponse,
                'is_read' => true,
            ]);
        }

        return $this->getSupportMessages($request);
    }
}