<?php

namespace App\Filament\Resources\ReformNewsChartResource\Widgets;

use App\Models\News;
use App\Models\ReformProject;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\Auth;

class ReformNewsChart extends ChartWidget
{
    protected static ?string $heading = 'Reforms vs News (Last 6 Months)';
    protected static ?int $sort = 2;
    protected static ?string $maxHeight = '300px';
    protected static ?string $pollingInterval = '30s';

    protected function getData(): array
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();

        // Always show both datasets if user has 'view reform-stats' permission
        $months = collect(range(5, 0))->map(fn($i) => now()->subMonths($i)->format('M Y'));

        return [
            'datasets' => [
                [
                    'label' => 'Reform Projects',
                    'data' => $this->getDataForModel(ReformProject::class, 6),
                    'backgroundColor' => '#10B981',
                    'borderColor' => '#047857',
                    'borderWidth' => 1,
                ],
                [
                    'label' => 'News Published',
                    'data' => $this->getDataForModel(News::class, 6),
                    'backgroundColor' => '#F59E0B',
                    'borderColor' => '#B45309',
                    'borderWidth' => 1,
                ],
            ],
            'labels' => $months,
        ];
    }

    private function getDataForModel(string $model, int $months): array
    {
        $data = [];
        for ($i = $months - 1; $i >= 0; $i--) {
            $date = now()->subMonths($i);
            $count = $model::whereYear('created_at', $date->year)
                ->whereMonth('created_at', $date->month)
                ->count();
            $data[] = $count;
        }
        return $data;
    }

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

    // Control entire widget visibility with 'view reform-stats'
    public static function canView(): bool
    {
        $user = Auth::user();
        /** @var \App\Models\User $user */
        return $user && $user->can('view reform-stats-on-dashoard');
    }
}
