<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Filesystem\OrderFilesystem;
use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Cart\Model\CartItem;
use CpCreation\VitiCore\Contact\Model\Contact;
use CpCreation\VitiCore\Contact\Repository\ContactRepository;
use CpCreation\VitiCore\Payment\Model\Payment;
use CpCreation\VitiCore\Product\Model\ProductGift;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;

class Mailer
{
    private $pdf;
    private $mailer;
    private $filesystem;
    private $translator;
    private $emailToMaintenance;
    private $contactRepository;
    private $twig;

    public function __construct(Pdf $pdf,
        PdfPuppeteer $pdfPuppeteer,
        \Swift_Mailer $mailer,
        OrderFilesystem $filesystem,
        TranslatorInterface $translator,
        ContactRepository $contactRepository,
        Environment $twig,
        $emailToMaintenance
    ) {
        $this->pdf                = $pdf;
        $this->pdfPuppeteer       = $pdfPuppeteer;
        $this->mailer             = $mailer;
        $this->filesystem         = $filesystem;
        $this->translator         = $translator;
        $this->emailToMaintenance = $emailToMaintenance;
        $this->twig               = $twig;
        $this->contactRepository  = $contactRepository;
    }

    public function send(\Swift_Message $message)
    {
        $this->mailer->send($message);
    }

    /**
     * @param Contact $contact
     * @param Cart    $cart
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function sendOrder(Contact $contact, Cart $cart)
    {

        $path            = $this->pdf->createPdfOrder($contact, $cart);
        $messageCustomer = (new \Swift_Message($this->translator->trans('order.mail.subject_mail', ['%company%' => $contact->getCompany()])))
            ->setFrom($contact->getEmailFrom(), $contact->getCompany())
            ->setSender($contact->getEmailFrom(), $contact->getCompany())
            ->setReturnPath($contact->getEmailFrom())
            ->setTo($cart->getInvoiceAddress()->getEmail())
            ->attach(
                \Swift_Attachment::fromPath('order/'.$path, 'application/pdf')
            )
            ->setBody(
                $this->twig->render(
                    'mail/order_customer.html.twig',
                    [
                        'contact' => $contact,
                        'cart'    => $cart,
                        'company' => $contact->getCompany(),
                    ]
                ),
                'text/html'
            )
            ->addPart(
                $this->twig->render(
                    'mail/order_customer.txt.twig',
                    [
                        'contact' => $contact,
                        'cart'    => $cart,
                        'company' => $contact->getCompany(),
                    ]
                ),
                'text/plain'
            );

        $this->mailer->send($messageCustomer);

        $path    = $this->pdf->createPdfOrderAdmin($contact, $cart, 'fr');
        $message = (new \Swift_Message('Un nouveau bon de commande est arrivé ! de '.$cart->getInvoiceAddress()->getLastname().' '.$cart->getInvoiceAddress()->getFirstname()))
            ->setFrom($contact->getEmailFrom(), $contact->getCompany())
            ->setSender($contact->getEmailFrom(), $contact->getCompany())
            ->setReturnPath($contact->getEmailFrom())
            ->setTo($contact->getEmailToShop())
            ->attach(
                \Swift_Attachment::fromPath('order/'.$path, 'application/pdf')
            )
            ->setBody(
                $this->twig->render(
                    'mail/order_admin.html.twig',
                    [
                        'contact' => $contact,
                        'cart'    => $cart,
                        'company' => $contact->getCompany(),
                    ]
                ),
                'text/html'
            )
            ->addPart(
                $this->twig->render(
                    'mail/order_admin.txt.twig',
                    [
                        'contact' => $contact,
                        'cart'    => $cart,
                        'company' => $contact->getCompany(),
                    ]
                )
                , 'text/plain'
            );

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

    public function sendPayment(Payment $payment)
    {
        /** @var Contact $contact */
        $contact = $this->contactRepository->findOne();
        $message = (new \Swift_Message('Paiement en ligne sur le site '.$contact->getCompany().' - Référence '.$payment->getReference()))
            ->setFrom($contact->getEmailFrom(), $contact->getCompany())
            ->setSender($contact->getEmailFrom(), $contact->getCompany())
            ->setReturnPath($contact->getEmailFrom())
            ->setTo($contact->getEmailToShop(), $contact->getCompany())
            ->setCc($payment->getEmail(), $payment->getLastname().' '.$payment->getFirstname())
            ->setBody(
                'Nom : '.$payment->getLastname().'<br />'.
                'Prénom : '.$payment->getFirstname().'<br />'.
                'Adresse : '.$payment->getStreet().'<br />'.
                'Code postal : '.$payment->getPostalCode().'<br />'.
                'Ville : '.$payment->getCity().'<br />'.
                'Email : <a href="'.$payment->getEmail().'">'.$payment->getEmail().'</a><br />'.
                'Téléphone : '.$payment->getPhone().'<br />'.
                'Référence Commande : '.$payment->getSlug().'<br />'.
                'Montant : '.number_format($payment->getAmount() / 100, 2).' € TTC <br />',
                'text/html'
            )
            ->addPart(
                'Nom : '.$payment->getLastname().
                ' Prénom : '.$payment->getFirstname().
                ' Adresse : '.$payment->getStreet().
                ' Code postal : '.$payment->getPostalCode().
                ' Ville : '.$payment->getCity().
                ' Email : '.$payment->getEmail().
                ' Téléphone : '.$payment->getPhone().
                ' Référence Commande : '.$payment->getSlug().
                ' Montant : '.number_format($payment->getAmount() / 100, 2).' € TTC',
                'text/plain'
            );

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

    /**
     * @param Contact $contact
     * @param Cart    $cart
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function senDelivery(Contact $contact, Cart $cart)
    {
        $path            = $this->pdf->createPdfOrder($contact, $cart);
        $bodyHtml        = $this->twig->render(
            'mail/delivery.html.twig',
            [
                'contact' => $contact,
                'cart'    => $cart,
                'company' => $contact->getCompany(),
            ]
        );
        $bodyTxt         = $this->twig->render(
            'mail/delivery.txt.twig',
            [
                'contact' => $contact,
                'cart'    => $cart,
                'company' => $contact->getCompany(),
            ]
        );
        $messageCustomer = (new \Swift_Message(
            $this->translator->trans(
                'delivery.mail.subject_mail', [
                '%company%' => $contact->getCompany(),
                '%ref%'     => $cart->getToken(),
            ], null, $cart->getCartCheckout()->getLocale()
            )
        ))
            ->setFrom($contact->getEmailFrom(), $contact->getCompany())
            ->setTo($cart->getInvoiceAddress()->getEmail())
            ->attach(
                \Swift_Attachment::fromPath('order/'.$path, 'application/pdf')
            )
            ->setBody(
                $bodyHtml,
                'text/html'
            )
            ->addPart(
                $bodyTxt,
                'text/plain'
            );

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

    /**
     * @param Contact  $contact
     * @param Cart     $cart
     * @param CartItem $item
     * @return void
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function sendGiftCard(Contact $contact, Cart $cart)
    {
        $bodyHtml = $this->twig->render(
            'mail/gift.html.twig',
            [
                'cart' => $cart,
            ]
        );
        $bodyTxt  = $this->twig->render(
            'mail/gift.txt.twig',
            [
                'cart' => $cart,
            ]
        );

        $messageCustomer = (new \Swift_Message(
            $this->translator->trans(
                'gift.mail.subject_mail', [], null, $cart->getCartCheckout()->getLocale()
            )
        ))
            ->setFrom($contact->getEmailFrom(), $contact->getCompany())
            ->setTo($cart->getInvoiceAddress()->getEmail())
            ->setBody(
                $bodyHtml,
                'text/html'
            )
            ->addPart(
                $bodyTxt,
                'text/plain'
            );
        /** @var CartItem $cartItem */
        foreach ($cart->getItems() as $cartItem) {
            /** @var ProductGift $gift */
            foreach ($cartItem->getGifts() as $gift) {
                $path = $this->pdfPuppeteer->createGiftCard($gift,$contact);
                $messageCustomer->attach(
                    \Swift_Attachment::fromPath('upload/gift/'.$path, 'application/pdf')
                );
            }
        }


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

    /**
     * @param $exception
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function sendErrorConnexionApiConnectSocialInstagram($exception)
    {

        /** @var Contact $contact */
        $contact = $this->contactRepository->findOne();
        $message = (new \Swift_Message('Erreur Connexion à l\'api Connect Social CPCREATION '.$contact->getCompany()))
            ->setFrom($contact->getEmailFrom(), $contact->getCompany())
            ->setSender($contact->getEmailFrom(), $contact->getCompany())
            ->setReturnPath($contact->getEmailFrom())
            ->setTo($this->emailToMaintenance)
            ->setBody(
                $exception.' '.$contact->getCompany()
                ,
                'text/html'
            )
            ->addPart(

                $exception.' '.$contact->getCompany(), 'text/plain'
            );

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

    /**
     * @param $exception
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function sendErrorInstagram($exception)
    {

        /** @var Contact $contact */
        $contact = $this->contactRepository->findOne();
        $message = (new \Swift_Message('Erreur connexion à l\'api display Instagram '.$contact->getCompany()))
            ->setFrom($contact->getEmailFrom(), $contact->getCompany())
            ->setTo($this->emailToMaintenance)
            ->setBody(
                $exception.' '.$contact->getCompany()
                ,
                'text/html'
            )
            ->addPart(

                $exception.' '.$contact->getCompany(), 'text/plain'
            );

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

    /**
     * @param $exception
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function sendErrorFacebookInstagram($exception)
    {

        /** @var Contact $contact */
        $contact = $this->contactRepository->findOne();
        $message = (new \Swift_Message('Erreur connexion à l\'api Facebook pour Instagram '.$contact->getCompany()))
            ->setFrom($contact->getEmailFrom(), $contact->getCompany())
            ->setTo($this->emailToMaintenance)
            ->setBody(
                $exception.' '.$contact->getCompany()
                ,
                'text/html'
            )
            ->addPart(

                $exception.' '.$contact->getCompany(), 'text/plain'
            );

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

    /**
     * @param $exception
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function sendErrorFacebookFacebook($exception)
    {

        /** @var Contact $contact */
        $contact = $this->contactRepository->findOne();
        $message = (new \Swift_Message('Erreur connexion à l\'api Facebook pour Facebook '.$contact->getCompany()))
            ->setFrom($contact->getEmailFrom(), $contact->getCompany())
            ->setTo($this->emailToMaintenance)
            ->setBody(
                $exception.' '.$contact->getCompany()
                ,
                'text/html'
            )
            ->addPart(

                $exception.' '.$contact->getCompany(), 'text/plain'
            );

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

    /**
     * @param $exception
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function sendErrorException($exception)
    {

        /** @var Contact $contact */
        $contact = $this->contactRepository->findOne();
        $message = (new \Swift_Message('Erreur '.$contact->getCompany()))
            ->setFrom($contact->getEmailFrom(), $contact->getCompany())
            ->setTo($this->emailToMaintenance)
            ->setBody(
                $exception.' '.$contact->getCompany()
                ,
                'text/html'
            )
            ->addPart(

                $exception.' '.$contact->getCompany(), 'text/plain'
            );

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

    /**
     * @param $response
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function sendErrorValidReturnPayment($response)
    {

        /** @var Contact $contact */
        $contact = $this->contactRepository->findOne();
        $message = (new \Swift_Message('Erreur Validation Paiement - retour de banque '.$contact->getCompany()))
            ->setFrom($contact->getEmailFrom(), $contact->getCompany())
            ->setTo($this->emailToMaintenance)
            ->setBody(
                $response
                ,
                'text/html'
            )
            ->addPart(

                $response, 'text/plain'
            );

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

    /**
     * @param $exception
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function sendErrorIpLocate($exception, $ip)
    {

        /** @var Contact $contact */
        $contact = $this->contactRepository->findOne();
        $message = (new \Swift_Message('Erreur location de l\'adresse IP '.$ip.' '.$contact->getCompany()))
            ->setFrom($contact->getEmailFrom(), $contact->getCompany())
            ->setTo($this->emailToMaintenance)
            ->setBody(
                $exception.' '.$contact->getCompany()
                ,
                'text/html'
            )
            ->addPart(

                $exception.' '.$contact->getCompany(), 'text/plain'
            );

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