<?php

namespace App\Filament\Widgets;

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

class CollectionsChartWidget extends ChartWidget
{
    protected static ?string $heading = 'Cobros por período';
    protected static ?int    $sort    = 3;
    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('payments')
                    ->whereBetween('payment_date', [$cursor->toDateString(), $weekEnd->toDateString()])
                    ->selectRaw("
                        SUM(CASE WHEN currency='USD' THEN net_amount ELSE 0 END) as usd,
                        SUM(CASE WHEN currency='BOB' THEN net_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('payments')
                    ->whereBetween('payment_date', [$cursor->toDateString(), $monthEnd->toDateString()])
                    ->selectRaw("
                        SUM(CASE WHEN currency='USD' THEN net_amount ELSE 0 END) as usd,
                        SUM(CASE WHEN currency='BOB' THEN net_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 neto',
                    'data'            => $usdData,
                    'backgroundColor' => 'rgba(34,197,94,0.6)',
                    'borderColor'     => 'rgb(34,197,94)',
                    'borderWidth'     => 1,
                ],
                [
                    'label'           => 'BOB neto',
                    'data'            => $bobData,
                    'backgroundColor' => 'rgba(251,146,60,0.6)',
                    'borderColor'     => 'rgb(251,146,60)',
                    'borderWidth'     => 1,
                ],
            ],
            'labels' => $labels,
        ];
    }

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