<?php

namespace App\Filament\Widgets;

use App\Models\Branch;
use App\Models\Sales\Invoice;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\Auth;

class BranchSalesBarChart extends ChartWidget
{
    protected static ?int $sort = 13;

    protected ?string $heading = 'Sales by branch';

    protected ?string $description = 'Net sales per branch.';

    protected int|string|array $columnSpan = 1;

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

    protected function getData(): array
    {
        $nameById = Branch::query()->pluck('name', 'id');

        $rows = Invoice::query()
            ->whereNull('deleted_at')
            ->whereNotNull('branch_id')
            ->selectRaw('branch_id, SUM(net_total) as total')
            ->groupBy('branch_id')
            ->orderByDesc('total')
            ->get();

        return [
            'datasets' => [[
                'label' => 'Net sales',
                'data' => $rows->map(fn ($r): float => round((float) $r->total, 2))->all(),
                'backgroundColor' => '#06b6d4',
                'borderRadius' => 4,
            ]],
            'labels' => $rows->map(fn ($r): string => (string) ($nameById[$r->branch_id] ?? "Branch #{$r->branch_id}"))->all(),
        ];
    }

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