<?php

namespace App\Filament\Widgets;

use App\Enums\ApprovalStatus;
use App\Models\PartnerMedia;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Widgets\ChartWidget;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Illuminate\Support\Facades\DB;

class MediaCooperationRankingChart extends ChartWidget
{
    use HasWidgetShield, InteractsWithPageFilters;

    protected ?string $heading = 'Ranking Media (Kerjasama Disetujui)';

    protected static ?int $sort = 11;

    protected int|string|array $columnSpan = 1;

    protected function getData(): array
    {
        $startDate = $this->filters['startDate'] ?? null;
        $endDate = $this->filters['endDate'] ?? null;

        $data = PartnerMedia::query()
            ->join('cooperation_media', 'partner_media.id', '=', 'cooperation_media.partner_media_id')
            ->where('cooperation_media.status', ApprovalStatus::ACCEPTED)
            ->when($startDate, fn ($q) => $q->whereDate('cooperation_media.created_at', '>=', $startDate))
            ->when($endDate, fn ($q) => $q->whereDate('cooperation_media.created_at', '<=', $endDate))
            ->select('partner_media.name', DB::raw('count(*) as total'))
            ->groupBy('partner_media.id', 'partner_media.name')
            ->orderByDesc('total')
            ->limit(10)
            ->get();

        return [
            'datasets' => [
                [
                    'label' => 'Total Kerjasama',
                    'data' => $data->pluck('total')->toArray(),
                    'backgroundColor' => '#6366F1',
                ],
            ],
            'labels' => $data->pluck('name')->toArray(),
        ];
    }

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