<?php

declare(strict_types=1);

namespace App\Controller\Public;

use App\Entity\Classe;
use App\Entity\Ecole;
use App\Entity\Inscription;
use App\Entity\InscriptionParcours;
use App\Entity\Niveau;
use App\Entity\Section;
use App\Form\PublicInscriptionType;
use App\Repository\ClasseRepository;
use App\Repository\AnneeScolaireRepository;
use App\Repository\EcoleRepository;
use App\Repository\EtudiantRepository;
use App\Repository\InscriptionRepository;
use App\Repository\NiveauRepository;
use App\Repository\SectionRepository;
use App\Repository\ThemeRepository;
use App\Service\MatriculeGenerator;
use App\Service\PublicUrlGenerator;
use App\Service\Tenant\TenantResolver;
use App\Service\Theme\ThemeResolver;
use App\Service\Whatsapp\WhatsappNotificationService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;

final class HomeController extends AbstractController
{
    public function __construct(
        private readonly SectionRepository $sectionRepository,
        private readonly NiveauRepository $niveauRepository,
        private readonly ClasseRepository $classeRepository,
        private readonly PublicUrlGenerator $publicUrlGenerator,
    ) {}

    #[Route('/', name: 'public_home', methods: ['GET'])]
    public function index(
        Request $request,
        ThemeResolver $themeResolver,
        TenantResolver $tenantResolver,
        EcoleRepository $ecoleRepository,
        ThemeRepository $themeRepository,
    ): Response {
        if ($request->query->has('theme')) {
            $themeCode = $themeResolver->resolvePublicTheme($request->query->get('theme'));
            $ecole = $ecoleRepository->findFirstActiveByThemeCode($themeCode);

            if ($ecole !== null) {
                return $this->renderSchoolPage($ecole, $request, $themeResolver, true);
            }
        }

        $tenantEcole = $tenantResolver->resolveEcole($request);
        if ($tenantEcole !== null) {
            return $this->renderSchoolPage($tenantEcole, $request, $themeResolver, false);
        }

        if ($tenantResolver->isTenantHost($request)) {
            throw $this->createNotFoundException('Madrassa introuvable ou non disponible.');
        }

        return $this->render('public/platform/home.html.twig', [
            'ecoles' => $ecoleRepository->findActivePilots(),
            'themes' => $themeRepository->findActifs(),
        ]);
    }

    #[Route('/inscription', name: 'public_tenant_registration', methods: ['GET', 'POST'])]
    public function tenantRegistration(
        Request $request,
        ThemeResolver $themeResolver,
        TenantResolver $tenantResolver,
        EntityManagerInterface $entityManager,
        MatriculeGenerator $matriculeGenerator,
        WhatsappNotificationService $whatsappNotificationService,
        AnneeScolaireRepository $anneeScolaireRepository,
    ): Response {
        $ecole = $tenantResolver->resolveEcole($request);
        if ($ecole === null) {
            throw $this->createNotFoundException('Madrassa introuvable ou non disponible.');
        }

        return $this->handleRegistration($ecole, $request, $themeResolver, $entityManager, $matriculeGenerator, $whatsappNotificationService, $anneeScolaireRepository);
    }

    #[Route('/madrassas/{slug}', name: 'public_school_show', requirements: ['slug' => '[a-z0-9-]+'], methods: ['GET'])]
    public function school(string $slug, Request $request, ThemeResolver $themeResolver, EcoleRepository $ecoleRepository): Response
    {
        $ecole = $ecoleRepository->findActiveBySlugOrSubdomain($slug);

        if ($ecole === null) {
            throw $this->createNotFoundException('Madrassa introuvable ou non disponible.');
        }

        return $this->renderSchoolPage($ecole, $request, $themeResolver, false);
    }

    #[Route('/madrassas/{slug}/inscription', name: 'public_school_registration', requirements: ['slug' => '[a-z0-9-]+'], methods: ['GET', 'POST'])]
    public function registration(
        string $slug,
        Request $request,
        ThemeResolver $themeResolver,
        EcoleRepository $ecoleRepository,
        EntityManagerInterface $entityManager,
        MatriculeGenerator $matriculeGenerator,
        WhatsappNotificationService $whatsappNotificationService,
        AnneeScolaireRepository $anneeScolaireRepository,
    ): Response {
        $ecole = $ecoleRepository->findActiveBySlugOrSubdomain($slug);
        if ($ecole === null) {
            throw $this->createNotFoundException('Madrassa introuvable ou non disponible.');
        }

        return $this->handleRegistration($ecole, $request, $themeResolver, $entityManager, $matriculeGenerator, $whatsappNotificationService, $anneeScolaireRepository);
    }

    #[Route('/inscription/confirmation/{numeroDossier}', name: 'public_tenant_registration_confirmation', methods: ['GET'])]
    public function tenantRegistrationConfirmation(
        string $numeroDossier,
        Request $request,
        ThemeResolver $themeResolver,
        TenantResolver $tenantResolver,
        InscriptionRepository $inscriptionRepository,
    ): Response {
        $ecole = $tenantResolver->resolveEcole($request);
        if ($ecole === null) {
            throw $this->createNotFoundException('Madrassa introuvable ou non disponible.');
        }

        return $this->handleRegistrationConfirmation($ecole, $numeroDossier, $themeResolver, $inscriptionRepository);
    }

    #[Route('/madrassas/{slug}/inscription/confirmation/{numeroDossier}', name: 'public_school_registration_confirmation', requirements: ['slug' => '[a-z0-9-]+'], methods: ['GET'])]
    public function registrationConfirmation(
        string $slug,
        string $numeroDossier,
        ThemeResolver $themeResolver,
        EcoleRepository $ecoleRepository,
        InscriptionRepository $inscriptionRepository,
    ): Response {
        $ecole = $ecoleRepository->findActiveBySlugOrSubdomain($slug);
        if ($ecole === null) {
            throw $this->createNotFoundException('Madrassa introuvable ou non disponible.');
        }

        return $this->handleRegistrationConfirmation($ecole, $numeroDossier, $themeResolver, $inscriptionRepository);
    }

    #[Route('/anciens-etudiants', name: 'public_tenant_old_students_search', methods: ['GET'])]
    public function tenantSearchOldStudents(Request $request, TenantResolver $tenantResolver, EtudiantRepository $etudiantRepository): JsonResponse
    {
        $ecole = $tenantResolver->resolveEcole($request);
        if ($ecole === null) {
            return $this->json([]);
        }

        return $this->handleSearchOldStudents($ecole, $request, $etudiantRepository);
    }

    #[Route('/madrassas/{slug}/anciens-etudiants', name: 'public_school_old_students_search', requirements: ['slug' => '[a-z0-9-]+'], methods: ['GET'])]
    public function searchOldStudents(string $slug, Request $request, EcoleRepository $ecoleRepository, EtudiantRepository $etudiantRepository): JsonResponse
    {
        $ecole = $ecoleRepository->findActiveBySlugOrSubdomain($slug);
        if ($ecole === null) {
            return $this->json([]);
        }

        return $this->handleSearchOldStudents($ecole, $request, $etudiantRepository);
    }

    private function handleRegistration(
        Ecole $ecole,
        Request $request,
        ThemeResolver $themeResolver,
        EntityManagerInterface $entityManager,
        MatriculeGenerator $matriculeGenerator,
        WhatsappNotificationService $whatsappNotificationService,
        AnneeScolaireRepository $anneeScolaireRepository,
    ): Response {
        $theme = $themeResolver->resolvePublicTheme($ecole->getThemePublic()?->getCode());
        $currentAnnee = $anneeScolaireRepository->findCurrentForEcole($ecole);
        $inscription = (new Inscription())->setEcole($ecole)->setAnneeScolaire($currentAnnee);
        if (!$request->isMethod('POST')) {
            $inscription->addParcours((new InscriptionParcours())->setEcole($ecole)->setAnneeScolaire($currentAnnee)->setPrincipal(true)->setActif(true)->setOrdre(1));
        }
        $form = $this->createForm(PublicInscriptionType::class, $inscription, ['ecole' => $ecole]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->normalizePublicRegistrationParcours($inscription, $ecole, $currentAnnee);
            $this->assertPublicRegistrationReferencesBelongToSchool($inscription, $ecole);
            $inscription
                ->setNumeroDossier($matriculeGenerator->generateNumeroDossier($ecole))
                ->setStatut($this->initialRegistrationStatus($ecole, $inscription));

            if ($inscription->getTypeCandidat() === Inscription::TYPE_NOUVEAU) {
                $inscription->setMatriculeTemporaire($matriculeGenerator->generateMatriculeTemporaire($ecole));
            }

            $entityManager->persist($inscription);
            $entityManager->flush();

            try {
                $whatsappNotificationService->notifyInscriptionSubmitted($inscription);
            } catch (\Throwable $exception) {
                $inscription->setWhatsappLastError($exception->getMessage());
                $entityManager->flush();
            }

            return $this->redirect($this->publicUrlGenerator->confirmationUrl($ecole, (string) $inscription->getNumeroDossier()));
        }

        return $this->render('public/registration/form.html.twig', [
            'ecole' => $ecole,
            'activeTheme' => $theme,
            'school' => $this->buildSchoolPayload($ecole, $theme),
            'form' => $form,
            'currentAnnee' => $currentAnnee,
        ]);
    }

    private function normalizePublicRegistrationParcours(Inscription $inscription, Ecole $ecole, $currentAnnee): void
    {
        if ($inscription->getParcours()->isEmpty()) {
            $fallback = (new InscriptionParcours())
                ->setSectionSouhaitee($inscription->getSectionSouhaitee())
                ->setNiveauSouhaite($inscription->getNiveauSouhaite())
                ->setClasseSouhaitee($inscription->getClasseSouhaitee())
                ->setLangueSouhaitee($inscription->getLangueSouhaitee())
                ->setModeSouhaite($inscription->getModeSouhaite())
                ->setObservation($inscription->getObservationCandidat());
            $inscription->addParcours($fallback);
        }

        $order = 1;
        $principalAssigned = false;
        $firstActive = null;
        foreach ($inscription->getParcours() as $parcours) {
            if (!$this->hasRegistrationParcoursContent($parcours)) {
                $inscription->removeParcours($parcours);
                continue;
            }

            $parcours
                ->setEcole($ecole)
                ->setAnneeScolaire($parcours->getAnneeScolaire() ?: $currentAnnee)
                ->setOrdre($order++)
                ->setActif(true)
                ->setSectionFinale($parcours->getSectionFinale() ?: $parcours->getSectionSouhaitee())
                ->setNiveauFinal($parcours->getNiveauFinal() ?: $parcours->getNiveauSouhaite())
                ->setClasseFinale($parcours->getClasseFinale() ?: $parcours->getClasseSouhaitee());

            $firstActive ??= $parcours;
            $parcours->setPrincipal(!$principalAssigned);
            $principalAssigned = true;
        }

        if (!$firstActive instanceof InscriptionParcours) {
            return;
        }

        $inscription
            ->setSectionSouhaitee($firstActive->getSectionSouhaitee())
            ->setNiveauSouhaite($firstActive->getNiveauSouhaite())
            ->setClasseSouhaitee($firstActive->getClasseSouhaitee())
            ->setSectionFinale($firstActive->getSectionFinale())
            ->setNiveauFinal($firstActive->getNiveauFinal())
            ->setClasseFinale($firstActive->getClasseFinale())
            ->setLangueSouhaitee($firstActive->getLangueSouhaitee())
            ->setModeSouhaite($firstActive->getModeSouhaite());
    }

    private function assertPublicRegistrationReferencesBelongToSchool(Inscription $inscription, Ecole $ecole): void
    {
        foreach ([
            $inscription->getSectionSouhaitee(),
            $inscription->getNiveauSouhaite(),
            $inscription->getClasseSouhaitee(),
            $inscription->getSectionFinale(),
            $inscription->getNiveauFinal(),
            $inscription->getClasseFinale(),
        ] as $subject) {
            $this->assertReferenceBelongsToSchool($subject, $ecole);
        }

        foreach ($inscription->getParcours() as $parcours) {
            $this->assertReferenceBelongsToSchool($parcours->getSectionSouhaitee(), $ecole);
            $this->assertReferenceBelongsToSchool($parcours->getNiveauSouhaite(), $ecole);
            $this->assertReferenceBelongsToSchool($parcours->getClasseSouhaitee(), $ecole);
            $this->assertReferenceBelongsToSchool($parcours->getSectionFinale(), $ecole);
            $this->assertReferenceBelongsToSchool($parcours->getNiveauFinal(), $ecole);
            $this->assertReferenceBelongsToSchool($parcours->getClasseFinale(), $ecole);
        }
    }

    private function assertReferenceBelongsToSchool(?object $subject, Ecole $ecole): void
    {
        if ($subject === null) {
            return;
        }

        if (!method_exists($subject, 'getEcole')) {
            throw new \LogicException(sprintf('Impossible de vérifier la madrassa de "%s".', $subject::class));
        }

        $subjectSchool = $subject->getEcole();
        if (!$subjectSchool instanceof Ecole) {
            return;
        }

        if ($subjectSchool->getId() !== null && $ecole->getId() !== null && $subjectSchool->getId() === $ecole->getId()) {
            return;
        }

        if ($subjectSchool === $ecole) {
            return;
        }

        throw $this->createNotFoundException('Parcours introuvable pour cette madrassa.');
    }

    private function hasRegistrationParcoursContent(InscriptionParcours $parcours): bool
    {
        return $parcours->getSectionSouhaitee()
            || $parcours->getNiveauSouhaite()
            || $parcours->getClasseSouhaitee()
            || $parcours->getLangueSouhaitee()
            || $parcours->getModeSouhaite()
            || $parcours->getObservation();
    }

    private function handleRegistrationConfirmation(
        Ecole $ecole,
        string $numeroDossier,
        ThemeResolver $themeResolver,
        InscriptionRepository $inscriptionRepository,
    ): Response {
        $inscription = $inscriptionRepository->findOneBy(['ecole' => $ecole, 'numeroDossier' => $numeroDossier]);
        if (!$inscription instanceof Inscription) {
            throw $this->createNotFoundException('Demande d’inscription introuvable.');
        }

        $theme = $themeResolver->resolvePublicTheme($ecole->getThemePublic()?->getCode());

        return $this->render('public/registration/confirmation.html.twig', [
            'ecole' => $ecole,
            'activeTheme' => $theme,
            'school' => $this->buildSchoolPayload($ecole, $theme),
            'inscription' => $inscription,
            'canonicalUrl' => $this->publicUrlGenerator->confirmationUrl($ecole, $numeroDossier),
        ]);
    }

    private function handleSearchOldStudents(Ecole $ecole, Request $request, EtudiantRepository $etudiantRepository): JsonResponse
    {
        $query = trim((string) $request->query->get('q', ''));
        if (mb_strlen($query) < 2) {
            return $this->json([]);
        }

        $items = array_map(static fn ($etudiant) => [
            'id' => $etudiant->getId(),
            'matricule' => $etudiant->getMatricule(),
            'nom' => $etudiant->getNomComplet(),
            'telephone' => $etudiant->getTelephoneWhatsapp() ?: $etudiant->getTelephonePrincipal(),
            'telephonePrincipal' => $etudiant->getTelephonePrincipal(),
            'telephoneWhatsapp' => $etudiant->getTelephoneWhatsapp(),
            'email' => $etudiant->getEmail(),
            'sexe' => $etudiant->getSexe(),
            'dateNaissance' => $etudiant->getDateNaissance()?->format('Y-m-d'),
            'lieuNaissance' => $etudiant->getLieuNaissance(),
            'situationMatrimoniale' => $etudiant->getSituationMatrimoniale(),
            'adresse' => $etudiant->getAdresse(),
            'aDesEnfants' => $etudiant->hasEnfants(),
            'joursDisponibles' => $etudiant->getJoursDisponibles(),
            'plageHoraireSouhaitee' => $etudiant->getPlageHoraireSouhaitee(),
            'sectionId' => $etudiant->getSection()?->getId(),
            'niveauId' => $etudiant->getNiveau()?->getId(),
            'classeId' => $etudiant->getClasse()?->getId(),
        ], $etudiantRepository->searchOldCandidates($ecole, $query));

        return $this->json($items);
    }

    private function renderSchoolPage(Ecole $ecole, Request $request, ThemeResolver $themeResolver, bool $previewMode): Response
    {
        $theme = $ecole->getThemePublic()?->isActif() ? $ecole->getThemePublic()?->getCode() : null;
        $theme = $themeResolver->resolvePublicTheme($theme);
        $template = sprintf('public/themes/%s/home.html.twig', $theme);

        if (!is_file((string) $this->getParameter('kernel.project_dir').'/templates/'.$template)) {
            $theme = 'qamar';
            $template = 'public/themes/qamar/home.html.twig';
        }

        $sections = $this->sectionRepository->findForEcole($ecole, true);
        $niveaux = $this->niveauRepository->findForEcole($ecole, true);
        $classes = $this->classeRepository->findForEcole($ecole, true);

        return $this->render($template, [
            'ecole' => $ecole,
            'activeTheme' => $theme,
            'tenantSlug' => $request->query->get('tenant'),
            'previewMode' => $previewMode,
            'school' => $this->buildSchoolPayload($ecole, $theme),
            'programs' => $this->buildPrograms($ecole, $theme, $sections),
            'levels' => $this->buildLevels($ecole, $theme, $niveaux, $classes),
            'classes' => $classes,
            'fees' => $this->buildFees($theme, $classes),
            'stats' => $this->buildStats($theme, $sections, $niveaux, $classes),
        ]);
    }

    /** @return array<string, mixed> */
    private function buildSchoolPayload(Ecole $ecole, string $theme): array
    {
        $primary = $ecole->getCouleurPrincipale() ?: match ($theme) {
            'daroul_ilm' => '#0F5C45',
            'sahaba' => '#123D2E',
            default => '#5B3A70',
        };
        $secondary = $ecole->getCouleurSecondaire() ?: match ($theme) {
            'daroul_ilm' => '#DDEFE7',
            'sahaba' => '#F3E8D0',
            default => '#E9C7D8',
        };
        $accent = $ecole->getCouleurAccent() ?: match ($theme) {
            'daroul_ilm' => '#C79A3B',
            'sahaba' => '#C89B3C',
            default => '#C9A24D',
        };
        $presentationImages = array_values(array_filter([
            $ecole->getPresentationImage1(),
            $ecole->getPresentationImage2(),
            $ecole->getPresentationImage3(),
        ]));

        return [
            'name' => $ecole->getNom() ?? 'Madrassa',
            'slug' => $ecole->getSlug() ?? '',
            'route' => $this->publicUrlGenerator->schoolUrl($ecole),
            'registrationRoute' => $this->publicUrlGenerator->registrationUrl($ecole),
            'oldStudentsSearchRoute' => $this->publicUrlGenerator->oldStudentsSearchUrl($ecole),
            'logo' => $ecole->getLogo(),
            'hasLogo' => (bool) $ecole->getLogo(),
            'footerLogo' => $ecole->getLogo(),
            'favicon' => $ecole->getFavicon() ?: 'assets/brand/favicon.png',
            'heroImage' => $ecole->getHeroImage(),
            'hasHeroImage' => (bool) $ecole->getHeroImage(),
            'presentationImages' => $presentationImages,
            'hasPresentationImages' => $presentationImages !== [],
            'initials' => $this->initials($ecole->getNom() ?? 'Madrassa'),
            'heroTitle' => $ecole->getHeroTitle() ?: $ecole->getNom() ?: 'Madrassa SALSABIL',
            'heroSubtitle' => $ecole->getHeroSubtitle() ?: $ecole->getSlogan() ?: 'Une madrassa accompagnée avec sérieux, clarté et proximité.',
            'aboutTitle' => $ecole->getAboutTitle() ?: 'Une formation accessible et suivie',
            'aboutText' => $ecole->getAboutText() ?: $ecole->getDescription() ?: 'Cette madrassa présente ses programmes, ses niveaux et ses contacts avec une identité claire sur SALSABIL Madrassas.',
            'ctaTitle' => $ecole->getCtaTitle() ?: 'Rejoindre '.$ecole->getNom(),
            'ctaText' => $ecole->getCtaText() ?: 'Contactez l’équipe administrative pour démarrer votre parcours d’apprentissage.',
            'description' => $ecole->getDescription() ?: 'Madrassa configurée sur SALSABIL Madrassas.',
            'slogan' => $ecole->getSlogan() ?: '',
            'phone' => $ecole->getTelephone1() ?: 'Téléphone non renseigné',
            'phone2' => $ecole->getTelephone2(),
            'whatsapp' => $ecole->getWhatsapp() ?: $ecole->getTelephone1() ?: 'WhatsApp non renseigné',
            'email' => $ecole->getEmail() ?: 'Email non renseigné',
            'address' => $ecole->getAdresse() ?: 'Adresse non renseignée',
            'city' => $ecole->getDisplayLocation(),
            'colors' => ['primary' => $primary, 'secondary' => $secondary, 'accent' => $accent],
        ];
    }

    /** @param list<Section> $sections @return list<array{title: string, description: string}> */
    private function buildPrograms(Ecole $ecole, string $theme, array $sections): array
    {
        if ($sections !== []) {
            return array_map(fn (Section $section) => [
                'title' => $section->getNom() ?? 'Section',
                'description' => $section->getDescription() ?: ($section->getPublicCible() ?: 'Programme disponible dans cette madrassa.'),
            ], array_slice($sections, 0, 6));
        }

        return $theme === 'daroul_ilm'
            ? [
                ['title' => 'Cours en ligne WhatsApp', 'description' => 'Des cours accessibles en français, haoussa et foulfouldé avec un suivi organisé.'],
                ['title' => 'Présentiel personnalisé', 'description' => 'Un accompagnement adapté aux adultes débutants, nouveaux convertis et profils spécifiques.'],
                ['title' => 'Sciences islamiques', 'description' => 'Tawhid, fiqh, adab et bases essentielles enseignés avec méthode.'],
            ]
            : [
                ['title' => 'Qa’ida Nouraniyya', 'description' => 'Un cadre régulier pour apprendre les bases de la lecture.'],
                ['title' => 'Lecture du Qur’an', 'description' => 'Correction, fluidité et progression accompagnée.'],
                ['title' => 'Mémorisation', 'description' => 'Objectifs progressifs et révisions suivies.'],
            ];
    }

    /** @param list<Niveau> $niveaux @param list<Classe> $classes @return list<array{title: string, description: string}> */
    private function buildLevels(Ecole $ecole, string $theme, array $niveaux, array $classes): array
    {
        if ($niveaux !== []) {
            return array_map(fn (Niveau $niveau) => [
                'title' => $niveau->getNom() ?? 'Niveau',
                'description' => $niveau->getDescription() ?: ($niveau->getSection()?->getNom() ?: 'Niveau configuré pour cette madrassa.'),
            ], array_slice($niveaux, 0, 6));
        }

        if ($classes !== []) {
            return array_map(fn (Classe $classe) => [
                'title' => $classe->getNom() ?? 'Classe',
                'description' => trim(($classe->getSection()?->getNom() ?? '').' '.($classe->getLangue() ? '· '.str_replace('_', ' ', $classe->getLangue()) : '')),
            ], array_slice($classes, 0, 6));
        }

        return $theme === 'daroul_ilm'
            ? [
                ['title' => 'Débutant', 'description' => 'Bases de lecture et accompagnement progressif.'],
                ['title' => 'Lecture et tajwid', 'description' => 'Correction, fluidité et règles essentielles de récitation.'],
                ['title' => 'Sciences islamiques', 'description' => 'Parcours organisé selon la langue et le programme choisi.'],
            ]
            : [
                ['title' => 'Qa’ida Nouraniyya', 'description' => 'Fondations, alphabet et premiers repères de lecture.'],
                ['title' => 'Amélioration lecture', 'description' => 'Lecture guidée, correction et consolidation des acquis.'],
                ['title' => 'Mémorisation', 'description' => 'Objectifs progressifs, révision et suivi régulier.'],
            ];
    }

    /** @param list<Classe> $classes @return list<array{title: string, amount: string}> */
    private function buildFees(string $theme, array $classes): array
    {
        $tariffed = array_values(array_filter($classes, fn (Classe $classe) => $classe->getTarifDefaut() !== null));
        if ($tariffed !== []) {
            return array_map(fn (Classe $classe) => [
                'title' => $classe->getNom() ?? 'Classe',
                'amount' => number_format((float) $classe->getTarifDefaut(), 0, ',', ' ').' FCFA',
            ], array_slice($tariffed, 0, 3));
        }

        return $theme === 'daroul_ilm'
            ? [
                ['title' => 'Inscription en ligne', 'amount' => '2 000 FCFA'],
                ['title' => 'Mensualité', 'amount' => '2 000 FCFA'],
                ['title' => 'Présentiel personnalisé', 'amount' => 'Selon les séances'],
            ]
            : [
                ['title' => 'Frais d’inscription', 'amount' => '1 000 FCFA'],
                ['title' => 'Frais annuels', 'amount' => '10 000 FCFA'],
                ['title' => 'Accompagnement', 'amount' => 'Selon le parcours'],
            ];
    }

    /** @param list<Section> $sections @param list<Niveau> $niveaux @param list<Classe> $classes @return list<array{label: string, value: string}> */
    private function buildStats(string $theme, array $sections, array $niveaux, array $classes): array
    {
        if ($sections !== [] || $niveaux !== [] || $classes !== []) {
            return [
                ['label' => 'Programmes actifs', 'value' => (string) count($sections)],
                ['label' => 'Niveaux configurés', 'value' => (string) count($niveaux)],
                ['label' => 'Classes ouvertes', 'value' => (string) count($classes)],
                ['label' => 'Suivi administratif', 'value' => '100%'],
            ];
        }

        return $theme === 'daroul_ilm'
            ? [
                ['label' => 'Langues proposées', 'value' => '3'],
                ['label' => 'Parcours principaux', 'value' => '2'],
                ['label' => 'Modes de cours', 'value' => '2'],
                ['label' => 'Suivi administratif', 'value' => '100%'],
            ]
            : [
                ['label' => 'Étudiantes suivies', 'value' => '250+'],
                ['label' => 'Niveaux organisés', 'value' => '3'],
                ['label' => 'Séances par semaine', 'value' => '2'],
                ['label' => 'Suivi progressif', 'value' => '100%'],
            ];
    }

    private function initials(string $name): string
    {
        $parts = preg_split('/\s+/', trim($name)) ?: [];
        $letters = '';
        foreach ($parts as $part) { if ($part !== '') { $letters .= mb_substr($part, 0, 1); } if (mb_strlen($letters) >= 2) { break; } }
        return mb_strtoupper($letters ?: 'M');
    }

    private function initialRegistrationStatus(Ecole $ecole, Inscription $inscription): string
    {
        if ($ecole->getSlug() === 'qamar') {
            return $inscription->getTypeCandidat() === Inscription::TYPE_NOUVEAU
                ? Inscription::STATUT_A_TESTER
                : Inscription::STATUT_A_AFFECTER;
        }

        if ($ecole->getSlug() === 'daroul-ilm' && $inscription->getTypeCandidat() === Inscription::TYPE_ANCIEN) {
            return Inscription::STATUT_A_AFFECTER;
        }

        return Inscription::STATUT_SOUMISE;
    }
}
