<?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 SalesTrendLineChart extends ChartWidget
{
    protected static ?int $sort = 10;

    protected int|string|array $columnSpan = 1;

    protected ?string $heading = 'Sales trend';

    protected ?string $description = 'Net sales vs. collections, last 30 days.';

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

    protected function getData(): array
    {
        $branchId = app(CurrentContext::class)->branchId();
        $start = Carbon::today()->subDays(29)->startOfDay();

        $days = collect(range(0, 29))
            ->map(fn (int $i): Carbon => Carbon::today()->subDays(29 - $i));

        $daily = Invoice::query()
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->where('created_at', '>=', $start)
            ->get(['created_at', 'net_total', 'paid_amount'])
            ->groupBy(fn (Invoice $i): string => $i->created_at->toDateString())
            ->map(fn ($rows) => [
                'net' => (float) $rows->sum('net_total'),
                'paid' => (float) $rows->sum('paid_amount'),
            ]);

        $series = fn (string $key): array => $days
            ->map(fn (Carbon $day): float => round((float) ($daily[$day->toDateString()][$key] ?? 0), 2))
            ->all();

        return [
            'datasets' => [
                [
                    'label' => 'Sales',
                    'data' => $series('net'),
                    'borderColor' => '#6366f1',
                    'backgroundColor' => 'rgba(99, 102, 241, 0.1)',
                    'fill' => false,
                    'tension' => 0.3,
                ],
                [
                    'label' => 'Collections',
                    'data' => $series('paid'),
                    'borderColor' => '#10b981',
                    'backgroundColor' => 'rgba(16, 185, 129, 0.1)',
                    'fill' => false,
                    'tension' => 0.3,
                ],
            ],
            'labels' => $days->map(fn (Carbon $day): string => $day->format('M d'))->all(),
        ];
    }

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