<?php

namespace App\Filament\Widgets;

use Carbon\Carbon;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\On;

class SalesChartWidget extends ChartWidget
{
    protected static ?string $heading = 'Ventas por período';
    protected static ?int    $sort    = 2;
    protected int | string | array $columnSpan = 1;
    protected static ?string $maxHeight = '280px';

    #[On('dashboardFiltersUpdated')]
    public function onFiltersUpdated(array $filters): void
    {
        $this->filters = $filters;
        $this->updateChartData();
    }

    protected function getData(): array
    {
        $desde = $this->filters['desde'] ?? now()->subWeeks(7)->startOfWeek()->toDateString();
        $hasta = $this->filters['hasta'] ?? now()->toDateString();

        $from = Carbon::parse($desde);
        $to   = Carbon::parse($hasta);
        $days = $from->diffInDays($to);

        $labels  = [];
        $usdData = [];
        $bobData = [];

        if ($days <= 60) {
            // Granularidad semanal
            $cursor = $from->copy()->startOfWeek();
            while ($cursor->lte($to)) {
                $weekEnd  = $cursor->copy()->endOfWeek();
                $labels[] = $cursor->format('d/m');

                $row = DB::table('sales')
                    ->whereBetween('sale_date', [$cursor->toDateString(), $weekEnd->toDateString()])
                    ->selectRaw("
                        SUM(CASE WHEN currency='USD' THEN gross_amount ELSE 0 END) as usd,
                        SUM(CASE WHEN currency='BOB' THEN gross_amount ELSE 0 END) as bob
                    ")
                    ->first();

                $usdData[] = round((float) ($row->usd ?? 0), 2);
                $bobData[] = round((float) ($row->bob ?? 0), 2);
                $cursor->addWeek();
            }
        } else {
            // Granularidad mensual
            $cursor = $from->copy()->startOfMonth();
            while ($cursor->lte($to)) {
                $monthEnd = $cursor->copy()->endOfMonth();
                $labels[] = $cursor->format('M y');

                $row = DB::table('sales')
                    ->whereBetween('sale_date', [$cursor->toDateString(), $monthEnd->toDateString()])
                    ->selectRaw("
                        SUM(CASE WHEN currency='USD' THEN gross_amount ELSE 0 END) as usd,
                        SUM(CASE WHEN currency='BOB' THEN gross_amount ELSE 0 END) as bob
                    ")
                    ->first();

                $usdData[] = round((float) ($row->usd ?? 0), 2);
                $bobData[] = round((float) ($row->bob ?? 0), 2);
                $cursor->addMonth();
            }
        }

        return [
            'datasets' => [
                [
                    'label'           => 'USD',
                    'data'            => $usdData,
                    'backgroundColor' => 'rgba(59,130,246,0.6)',
                    'borderColor'     => 'rgb(59,130,246)',
                    'borderWidth'     => 1,
                ],
                [
                    'label'           => 'BOB',
                    'data'            => $bobData,
                    'backgroundColor' => 'rgba(234,179,8,0.6)',
                    'borderColor'     => 'rgb(234,179,8)',
                    'borderWidth'     => 1,
                ],
            ],
            'labels' => $labels,
        ];
    }

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