<?php

namespace App\Filament\Widgets;

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

class SalesChannelDoughnutChart extends ChartWidget
{
    protected static ?int $sort = 15;

    protected ?string $heading = 'Revenue by channel';

    protected ?string $description = 'Net sales split by sales channel.';

    protected int|string|array $columnSpan = 1;

    private const CHANNEL_LABELS = [
        'sales' => 'Sales',
        'till' => 'Till',
        'sales_order' => 'Sales orders',
    ];

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

    protected function getData(): array
    {
        $branchId = app(CurrentContext::class)->branchId();

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

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

        return [
            'datasets' => [[
                'data' => $rows->map(fn ($r): float => round((float) $r->total, 2))->all(),
                'backgroundColor' => array_slice($palette, 0, $rows->count()),
                'borderWidth' => 2,
            ]],
            'labels' => $rows->map(fn ($r): string => self::CHANNEL_LABELS[$r->channel] ?? ucwords((string) ($r->channel ?: 'Walk-in')))->all(),
        ];
    }

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