<?php

namespace App\Service\Mailer;

use App\Entity\Mail;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Symfony\Component\HttpKernel\Profiler\Profiler;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Header\IdentificationHeader;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Environment;

class Mailer
{
    private readonly MailerInterface $mailer;

    public function __construct(
        MailerInterface $mailer,
        private readonly EntityManagerInterface $entityManager,
        private readonly UrlGeneratorInterface $urlGenerator,
        private readonly ?Profiler $profiler,
        private readonly Environment $environment,
    ) {
        $this->mailer = $mailer;
    }

    private function convertMjmlToHtml(string $mjmlContent): string
    {
        $process = new Process(['mjml', '--stdin']);
        $process->setInput($mjmlContent);

        try {
            $process->run();

            if (!$process->isSuccessful()) {
                throw new ProcessFailedException($process);
            }

            return $process->getOutput();
        } catch (ProcessFailedException|Exception) {
            return ''; // Retourne vide en cas d'échec
        }
    }


    /**
     * @param string $address
     * @param string $addressName
     * @param string $subject
     * @param string $template
     * @param array<string, mixed> $data
     * @param array<\Symfony\Component\Mime\Part\DataPart> $files
     */
    public function send(
        string $address,
        string $addressName,
        string $subject,
        string $template,
        array $data,
        array $files = []
    ): void {
        $dest = new Address($address, $addressName);
        $src = new Address("contact@e-cosplay.fr", "E-Cosplay");

        $mail = (new Email())
            ->subject($subject)
            ->to($dest)
            ->from($src);

        $mjmlGenerator = $this->environment->render($template, [
            'system' => [
                'subject' => $subject,
                'path' => $_ENV['PATH_URL'],
            ],
            'datas' => $data,
        ]);

        $htmlContent = $this->convertMjmlToHtml($mjmlGenerator);
        $txtContent = $this->environment->render('txt-'.$template,[
            'system' => [
                'subject' => $subject,
                'path' => $_ENV['PATH_URL'],
            ],
            'datas' => $data,
        ]);
        foreach ($files as $file) {
            $mail->addPart($file);
        }
        $mail->html($htmlContent);
        $mail->text($txtContent);
        $this->mailer->send($mail);
    }

}
