<?php

namespace Lc\SovBundle\Builder\Ticket;

use Doctrine\ORM\EntityManagerInterface;
use Lc\CaracoleBundle\Notification\MailMailjetNotification;
use Lc\SovBundle\Component\FormComponent;
use Lc\SovBundle\Factory\Ticket\TicketFactory;
use Lc\SovBundle\Factory\Ticket\TicketMessageFactory;
use Lc\SovBundle\Model\Ticket\TicketInterface;
use Lc\SovBundle\Model\Ticket\TicketMessageInterface;
use Lc\SovBundle\Model\Ticket\TicketModel;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class TicketMessageBuilder
{
    protected EntityManagerInterface $entityManager;
    protected MailMailjetNotification $mailMailjetNotification;
    protected TicketMessageFactory $ticketMessageFactory;

    public function __construct(
            EntityManagerInterface $entityManager,
            MailMailjetNotification $mailMailjetNotification,
            TicketMessageFactory $ticketMessageFactory
    ) {
        $this->entityManager = $entityManager;
        $this->mailMailjetNotification = $mailMailjetNotification;
        $this->ticketMessageFactory = $ticketMessageFactory;
    }

    public function create(array $params = []): TicketMessageInterface
    {
        $ticket = $params['ticket'];
        $ticketMessage = $this->ticketMessageFactory->create($ticket);

        $ticketMessage->setStatus(1);
        $ticketMessage->setTicket($ticket);
        $ticketMessage->setMessage($params['message']);

        if (isset($params['answerByAdmin']) && $params['answerByAdmin']) {
            $ticketMessage->setAnswerByAdmin($params['answerByAdmin']);

            // envoi email au client
            $this->mailMailjetNotification->send(
                    [
                            MailMailjetNotification::SUBJECT => 'Réponse à votre demande',
                            MailMailjetNotification::TO_EMAIL => $ticket->getUser() ? $ticket->getUser()->getEmail(
                            ) : $ticket->getVisitorEmail(),
                            MailMailjetNotification::CONTENT_TEMPLATE => 'mail/ticket-response',
                            MailMailjetNotification::CONTENT_DATA => [
                                    'firstname' => $ticket->getUser() ? $ticket->getUser()->getFirstname(
                                    ) : $ticket->getVisitorFirstname(),
                                    'ticket' => $ticket,
                            ],
                    ]
            );
        }
        $this->entityManager->persist($ticketMessage);

        if (isset($params['imageFilename']) && $params['imageFilename']) {
            $ticketMessage->setImageFilename($params['imageFilename']);
        }
        if (isset($params['closeTicket']) && $params['closeTicket']) {
            $ticket->setStatus(TicketModel::TICKET_STATUS_CLOSED);
        }

        $ticket->setUpdatedAt(new \DateTime());

        $this->entityManager->persist($ticket);
        $this->entityManager->flush();

        return $ticketMessage;
    }

}
