<?php

namespace App\Filament\Resources\RaffleResource\Widgets;

use App\Models\Raffle;
use App\Models\Ticket;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Database\Eloquent\Model;

class RaffleStats extends BaseWidget
{
    public ?Model $record = null;

    protected function getStats(): array
    {
        if (! $this->record instanceof Raffle) {
            return [];
        }

        $total = $this->record->total_tickets;

        $sold = $this->record->sold_tickets;
        $reserved = \App\Models\Transaction::where('raffle_id', $this->record->id)
            ->where('type', 'purchase')
            ->where('status', 'pending')
            ->sum('quantity');
        $available = max(0, $total - $sold);

        // Sumar los montos de transacciones aprobadas de este sorteo
        $revenue = \App\Models\Transaction::where('raffle_id', $this->record->id)
            ->where('type', 'purchase')
            ->where('status', 'approved')
            ->sum('amount');

        $percentage = $total > 0 ? round(($sold / $total) * 100, 2) : 0;

        return [
            Stat::make('Total Emitido', number_format($total).' boletos')
                ->description('Total de boletos creados para el sorteo')
                ->icon('heroicon-m-ticket'),

            Stat::make('Estado de Ventas', number_format($sold).' vendidos')
                ->description(number_format($reserved).' reservados | '.number_format($available).' libres')
                ->descriptionIcon('heroicon-m-shopping-bag')
                ->color('success')
                ->chart([$available, $reserved, $sold]),

            Stat::make('Recaudación Real', '₡'.number_format($revenue, 2, '.', ','))
                ->description('Porcentaje vendido: '.$percentage.'%')
                ->descriptionIcon('heroicon-m-banknotes')
                ->color('warning'),
        ];
    }
}
