<?php
declare(strict_types=1);

namespace App\Service;

use App\Entity\Payment;
use Doctrine\Common\Collections\Collection;
use Nucleos\DompdfBundle\Factory\DompdfFactory;
use Nucleos\DompdfBundle\Wrapper\DompdfWrapper;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Part\DataPart;
use Twig\Environment;

class TicketEmailService
{
    public function __construct(
        private readonly MailerInterface $mailer,
        #[Autowire(env: 'SENDER_MAIL')]
        private readonly string $senderMail,
        private readonly Environment $twig,
    ) {
    }

    public function sendSuccessEmail(Payment $payment): void
    {
        $mail = (new TemplatedEmail())
            ->htmlTemplate('email/order.html.twig')
            ->subject('Abiball Ticket')
            ->from(new Address($this->senderMail, 'Noreply'))
            ->to(new Address($payment->getCustomer()?->getEmail(), $payment->getCustomer()?->getFirstname() . ' ' . $payment->getCustomer()?->getLastname()))
            ->context([
                'payment' => $payment,
            ])
            ->addPart(new DataPart($this->generateTicket($payment->getCustomer()?->getTickets()), 'tickets.pdf', 'application/pdf'));

        $this->mailer->send($mail);
    }

    private function generateTicket(Collection $tickets): string
    {
        return (new DompdfWrapper(new DompdfFactory()))->getPdf($this->twig->render('email/pdf.html.twig', ['tickets' => $tickets]));
    }
}