<?php

namespace App\Filament\Widgets;

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

class PaymentStatusPieChart extends ChartWidget
{
    protected static ?int $sort = 14;

    protected ?string $heading = 'Revenue by payment status';

    protected ?string $description = 'Net sales split by invoice payment status.';

    protected int|string|array $columnSpan = 1;

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

    protected function getData(): array
    {
        $branchId = app(CurrentContext::class)->branchId();
        $nameById = Status::query()
            ->where('context', Status::CTX_INVOICE_PAYMENT)
            ->pluck('name', 'id');

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

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

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

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