<?php

declare(strict_types=1);

namespace App\Controller\School;

use App\Service\School\SchoolContext;
use App\Entity\Ecole;
use App\Form\SchoolConfigurationType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/school/configuration', name: 'school_configuration_')]
#[IsGranted('ROLE_ECOLE_ADMIN')]
final class ConfigurationController extends AbstractController
{
    public function __construct(private readonly SchoolContext $schoolContext)
    {
    }

    #[Route('', name: 'edit', methods: ['GET', 'POST'])]
    public function edit(Request $request, EntityManagerInterface $entityManager): Response
    {
        $ecole = $this->schoolContext->getEcole();
        $form = $this->createForm(SchoolConfigurationType::class, $ecole);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->handleUploads($ecole, $form);
            $entityManager->flush();

            $this->addFlash('success', 'La configuration publique de la madrassa a été mise à jour.');

            return $this->redirectToRoute('school_configuration_edit', [], Response::HTTP_SEE_OTHER);
        }

        return $this->render('school/configuration/edit.html.twig', [
            'ecole' => $ecole,
            'form' => $form,
        ]);
    }


    /**
     * @param FormInterface<Ecole> $form
     */
    private function handleUploads(Ecole $ecole, FormInterface $form): void
    {
        $logoFile = $form->get('logoFile')->getData();
        if ($logoFile instanceof UploadedFile) {
            $ecole->setLogo($this->moveUploadedFile($logoFile, $ecole, 'logo'));
        }

        $faviconFile = $form->get('faviconFile')->getData();
        if ($faviconFile instanceof UploadedFile) {
            $ecole->setFavicon($this->moveUploadedFile($faviconFile, $ecole, 'favicon'));
        }

        $heroImageFile = $form->get('heroImageFile')->getData();
        if ($heroImageFile instanceof UploadedFile) {
            $ecole->setHeroImage($this->moveUploadedFile($heroImageFile, $ecole, 'hero'));
        }

        $presentationImage1File = $form->get('presentationImage1File')->getData();
        if ($presentationImage1File instanceof UploadedFile) {
            $ecole->setPresentationImage1($this->moveUploadedFile($presentationImage1File, $ecole, 'presentation-1'));
        }

        $presentationImage2File = $form->get('presentationImage2File')->getData();
        if ($presentationImage2File instanceof UploadedFile) {
            $ecole->setPresentationImage2($this->moveUploadedFile($presentationImage2File, $ecole, 'presentation-2'));
        }

        $presentationImage3File = $form->get('presentationImage3File')->getData();
        if ($presentationImage3File instanceof UploadedFile) {
            $ecole->setPresentationImage3($this->moveUploadedFile($presentationImage3File, $ecole, 'presentation-3'));
        }

        $signatureFile = $form->get('imageSignatureAdministrationFile')->getData();
        if ($signatureFile instanceof UploadedFile) {
            $ecole->setImageSignatureAdministration($this->moveUploadedFile($signatureFile, $ecole, 'signature-administration'));
        }

        $cachetFile = $form->get('imageCachetAdministrationFile')->getData();
        if ($cachetFile instanceof UploadedFile) {
            $ecole->setImageCachetAdministration($this->moveUploadedFile($cachetFile, $ecole, 'cachet-administration'));
        }
    }

    private function moveUploadedFile(UploadedFile $file, Ecole $ecole, string $kind): string
    {
        $projectDir = (string) $this->getParameter('kernel.project_dir');
        $targetDir = $projectDir.'/public/uploads/ecoles';

        if (!is_dir($targetDir) && !mkdir($targetDir, 0775, true) && !is_dir($targetDir)) {
            throw new \RuntimeException(sprintf('Impossible de créer le dossier de téléversement "%s".', $targetDir));
        }

        $slug = $ecole->getSlug() ?: 'madrassa';
        $slug = preg_replace('/[^a-z0-9-]+/', '-', mb_strtolower($slug)) ?: 'madrassa';
        $slug = trim($slug, '-') ?: 'madrassa';

        $extension = $file->guessExtension() ?: $file->getClientOriginalExtension() ?: 'bin';
        $extension = mb_strtolower($extension);
        if ($extension === 'jpeg') {
            $extension = 'jpg';
        }

        $filename = sprintf('%s-%s-%s.%s', $slug, $kind, bin2hex(random_bytes(4)), $extension);
        $file->move($targetDir, $filename);

        return 'uploads/ecoles/'.$filename;
    }
}
