<?php

namespace App\Filament\Widgets;

use App\Models\Pole;
use App\Models\Rapport;
use App\Models\Etablissement;
use Filament\Widgets\ChartWidget;

class InspectionAnalysis extends ChartWidget
{
    protected ?string $heading = 'Analyse des Rapports d\'Inspection';

    protected function getData(): array
    {
        $poles = Pole::all();
        
        return [
            'datasets' => [
                [
                    '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(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)',
                ],
            ],
            'labels' => $poles->pluck('libellefr')->toArray(),
        ];
    }

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