<?php

namespace App\Filament\Widgets;

use App\Models\Sales\Invoice;
use App\Services\CurrentContext;
use Carbon\Carbon;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\Auth;

class MonthlySalesAreaChart extends ChartWidget
{
    protected static ?int $sort = 11;

    protected int|string|array $columnSpan = 1;

    protected ?string $heading = 'Monthly sales';

    protected ?string $description = 'Net sales per month, last 12 months.';

    public static function canView(): bool
    {
        return Auth::user()?->hasPermissionTo('dashboard.access') ?? false;
    }

    protected function getData(): array
    {
        $branchId = app(CurrentContext::class)->branchId();
        $start = Carbon::now()->startOfMonth()->subMonths(11);

        $months = collect(range(0, 11))
            ->map(fn (int $i): Carbon => Carbon::now()->startOfMonth()->subMonths(11 - $i));

        $byMonth = Invoice::query()
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->where('created_at', '>=', $start)
            ->get(['created_at', 'net_total'])
            ->groupBy(fn (Invoice $i): string => $i->created_at->format('Y-m'))
            ->map(fn ($rows): float => (float) $rows->sum('net_total'));

        return [
            'datasets' => [[
                'label' => 'Net sales',
                'data' => $months
                    ->map(fn (Carbon $month): float => round($byMonth[$month->format('Y-m')] ?? 0, 2))
                    ->all(),
                'borderColor' => '#8b5cf6',
                'backgroundColor' => 'rgba(139, 92, 246, 0.25)',
                'fill' => true,
                'tension' => 0.3,
            ]],
            'labels' => $months->map(fn (Carbon $month): string => $month->format('M y'))->all(),
        ];
    }

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