<?php

namespace App\Filament\Widgets;

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

class TopSellingProductsBarChart extends ChartWidget
{
    protected static ?int $sort = 12;

    protected ?string $heading = 'Top selling products';

    protected ?string $description = 'Units sold, top 10 products.';

    protected int|string|array $columnSpan = 1;

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

    protected function getData(): array
    {
        $rows = InvoiceItem::query()
            ->join('invoices', 'invoices.id', '=', 'invoice_items.invoice_id')
            ->whereNull('invoices.deleted_at')
            ->tap(fn ($q) => app(CurrentContext::class)->restrictToAccessibleBranches($q, 'invoices.branch_id'))
            ->selectRaw(
                'COALESCE(invoice_items.product_name, "Unnamed") as product_name,
                 SUM(invoice_items.quantity) as quantity'
            )
            ->groupBy('invoice_items.product_id', 'invoice_items.product_name')
            ->orderByDesc('quantity')
            ->limit(10)
            ->get();

        return [
            'datasets' => [[
                'label' => 'Units sold',
                'data' => $rows->map(fn ($r): float => round((float) $r->quantity, 2))->all(),
                'backgroundColor' => '#f59e0b',
                'borderRadius' => 4,
            ]],
            'labels' => $rows->pluck('product_name')->all(),
        ];
    }

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