<?php

namespace App\Filament\Widgets;

use App\Models\Transaction;
use Filament\Widgets\ChartWidget;

class SalesChart extends ChartWidget
{
    protected static ?string $heading = 'Tendencia de Ventas (Últimos 30 Días)';

    protected static ?int $sort = 2;

    protected function getData(): array
    {
        $data = [];
        $labels = [];

        // Generar historial de ventas de los últimos 30 días de la base de datos
        for ($i = 29; $i >= 0; $i--) {
            $date = now()->subDays($i)->format('Y-m-d');
            $labels[] = now()->subDays($i)->format('d M');

            // Sumar montos de transacciones de compra aprobadas del día
            $sum = Transaction::where('type', 'purchase')
                ->where('status', 'approved')
                ->whereDate('created_at', $date)
                ->sum('amount');

            $data[] = (float) $sum;
        }

        return [
            'datasets' => [
                [
                    'label' => 'Ventas Diarias (₡)',
                    'data' => $data,
                    'borderColor' => '#F59E0B', // Color ámbar de Wincar
                    'backgroundColor' => 'rgba(245, 158, 11, 0.1)',
                    'fill' => 'start',
                    'tension' => 0.3, // Curvatura suave de la línea del gráfico
                ],
            ],
            'labels' => $labels,
        ];
    }

    protected function getType(): string
    {
        return 'line';
    }
}
