<?php

namespace App\Filament\Widgets;

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

class WeekdaySalesRadarChart extends ChartWidget
{
    protected static ?int $sort = 16;

    protected ?string $heading = 'Weekday activity';

    protected ?string $description = 'Sales value and invoice count by day of week, last 30 days.';

    protected int|string|array $columnSpan = 1;

    private const WEEKDAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

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

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

        $invoices = Invoice::query()
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->where('created_at', '>=', Carbon::today()->subDays(29)->startOfDay())
            ->get(['created_at', 'net_total'])
            ->groupBy(fn (Invoice $i): int => $i->created_at->dayOfWeekIso);

        $bucket = fn (string $key): array => collect(range(1, 7))
            ->map(function (int $weekday) use ($invoices, $key): float {
                $group = $invoices->get($weekday) ?? collect();

                $value = $key === 'sum' ? $group->sum('net_total') : $group->count();

                return round((float) $value, 2);
            })
            ->all();

        return [
            'datasets' => [
                [
                    'label' => 'Sales (Rs.)',
                    'data' => $bucket('sum'),
                    'borderColor' => '#6366f1',
                    'backgroundColor' => 'rgba(99, 102, 241, 0.2)',
                    'fill' => true,
                ],
                [
                    'label' => 'Invoices',
                    'data' => $bucket('count'),
                    'borderColor' => '#f59e0b',
                    'backgroundColor' => 'rgba(245, 158, 11, 0.2)',
                    'fill' => true,
                ],
            ],
            'labels' => self::WEEKDAYS,
        ];
    }

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