<?php

namespace App\Filament\Widgets;

use App\Models\Pole;
use App\Models\Inspecteur;
use App\Models\Etablissement;
use App\Models\Professeur;
use App\Models\Rapport;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\Cache;

class PoleStatsChart extends ChartWidget
{
    protected ?string $heading = 'Statistiques par Pôle';

    protected function getData(): array
    {
        return Cache::remember('pole_stats_chart', 3600, function () {
            $poles = Pole::all();
            
            return [
                'datasets' => [
                    [
                        'label' => 'Inspecteurs',
                        'data' => $poles->pluck('inspecteurs_count')->toArray(),
                        'backgroundColor' => 'rgba(59, 130, 246, 0.5)',
                        'borderColor' => 'rgb(59, 130, 246)',
                    ],
                    [
                        'label' => 'Établissements',
                        'data' => $poles->map(function ($pole) {
                            return Etablissement::whereHas('commune.moughataa.region', function ($query) use ($pole) {
                                $query->where('pole_id', $pole->id);
                            })->count();
                        })->toArray(),
                        'backgroundColor' => 'rgba(16, 185, 129, 0.5)',
                        'borderColor' => 'rgb(16, 185, 129)',
                    ],
                    [
                        'label' => 'Professeurs',
                        'data' => $poles->map(function ($pole) {
                            return Professeur::whereHas('etablissements.commune.moughataa.region', function ($query) use ($pole) {
                                $query->where('pole_id', $pole->id);
                            })->count();
                        })->toArray(),
                        'backgroundColor' => 'rgba(245, 158, 11, 0.5)',
                        'borderColor' => 'rgb(245, 158, 11)',
                    ],
                    [
                        'label' => 'Rapports',
                        'data' => $poles->map(function ($pole) {
                            return Rapport::whereHas('etablissement.commune.moughataa.region', function ($query) use ($pole) {
                                $query->where('pole_id', $pole->id);
                            })->count();
                        })->toArray(),
                        'backgroundColor' => 'rgba(239, 68, 68, 0.5)',
                        'borderColor' => 'rgb(239, 68, 68)',
                    ],
                ],
                'labels' => $poles->pluck('libellefr')->toArray(),
            ];
        });
    }

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