<?php

namespace App\Event\Signature;

use App\Entity\Contrats;
use App\Service\Mailer\Mailer;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Vich\UploaderBundle\Templating\Helper\UploaderHelper;

#[AsEventListener(event: ContratEvent::class, method: 'onContratSend')]
class ContratSubscriber
{
    public function __construct(
        private readonly Mailer $mailer,
        private readonly UrlGeneratorInterface $urlGenerator,
        private readonly KernelInterface $kernel,
        private readonly UploaderHelper $uploaderHelper
    ) {}

    public function onContratSend(ContratEvent $event): void
    {
        $contrat = $event->getContrats();
        $customer = $contrat->getCustomer();

        // Récupération du chemin relatif via VichUploader
        $contratPath = $this->uploaderHelper->asset($contrat, 'devisFile');
        $absolutePath = $this->kernel->getProjectDir() . "/public" . $contratPath;

        $attachments = [];

        // Vérification si le fichier existe physiquement avant de l'attacher
        if ($contratPath && file_exists($absolutePath)) {
            $attachments[] = new DataPart(
                file_get_contents($absolutePath),
                "Contrat_Ludikevent_" . $contrat->getNumReservation() . ".pdf",
                "application/pdf"
            );
        }

        // Envoi du mail
        $this->mailer->send(
            $customer->getEmail(),
            $customer->getSurname() . " " . $customer->getName(),
            "[Ludikevent] - Contrat de location N°" . $contrat->getNumReservation(),
            "mails/sign/contrat.twig",
            [
                'contrat' => $contrat,
                'contratLink' => $_ENV['CONTRAT_BASEURL'] . $this->urlGenerator->generate('gestion_contrat_view', ['num' => $contrat->getNumReservation()])
            ],
            $attachments
        );
    }
}
