<?php

namespace App\Filament\Widgets;

use App\Models\Pole;
use App\Models\Region;
use App\Models\Moughataa;
use App\Models\Commune;
use App\Models\Etablissement;
use App\Models\Professeur;
use Filament\Widgets\Widget;

class DrillDownAnalysis extends Widget
{
    protected string $view = 'filament.widgets.drill-down-analysis';

    protected static ?string $heading = 'Analyse Hiérarchique';

    public function getViewData(): array
    {
        $poles = Pole::all();
        
        $poles->each(function ($pole) {
            $pole->regions = Region::where('pole_id', $pole->id)->get();
            $pole->etablissements_count = Etablissement::whereHas('commune.moughataa.region', function ($query) use ($pole) {
                $query->where('pole_id', $pole->id);
            })->count();
            
            $pole->professeurs_count = Professeur::whereHas('etablissements.commune.moughataa.region', function ($query) use ($pole) {
                $query->where('pole_id', $pole->id);
            })->count();
        });
        
        return [
            'poles' => $poles,
        ];
    }
}
