<?php

namespace App\Filament\Widgets;

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

class CategorySalesPolarAreaChart extends ChartWidget
{
    protected static ?int $sort = 17;

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

    protected ?string $description = 'Gross sales split by main category.';

    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'))
            ->whereNotNull('invoice_items.product_id')
            ->leftJoin('products', 'products.id', '=', 'invoice_items.product_id')
            ->leftJoin('main_categories', 'main_categories.id', '=', 'products.main_category_id')
            ->selectRaw(
                'COALESCE(main_categories.name, "Uncategorised") as category,
                 SUM(invoice_items.gross_total) as total'
            )
            ->groupBy('category')
            ->orderByDesc('total')
            ->limit(8)
            ->get();

        $palette = ['#6366f1', '#f59e0b', '#10b981', '#ef4444', '#8b5cf6', '#06b6d4', '#ec4899', '#84cc16'];

        return [
            'datasets' => [[
                'data' => $rows->map(fn ($r): float => round((float) $r->total, 2))->all(),
                'backgroundColor' => array_slice($palette, 0, $rows->count()),
            ]],
            'labels' => $rows->pluck('category')->all(),
        ];
    }

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