<?php

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


use Cocur\Slugify\Slugify;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Filesystem\GiftFilesystem;
use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Contact\Model\Contact;
use CpCreation\VitiCore\Product\Model\ProductGift;
use Doctrine\Common\Collections\ArrayCollection;
use Spatie\Browsershot\Browsershot;
use Twig\Environment;

class PdfPuppeteer
{

    public function __construct(
        private Environment $twig,
        private GiftFilesystem $giftFilesystem,
        private string $includePathNode,
        private string $includePathNpm,
        private string $includePath,
        private string $includePathChromium
    ) {

    }


    public function createGiftCard(ProductGift $gift, Contact $contact): string
    {
        $gifts = new ArrayCollection();
        $gifts->add($gift);
        $html     = $this->twig->render('pdf/gift.html.twig', [
            'gifts'   => $gifts,
            'contact' => $contact,
        ]);
        $slugify  = new Slugify();
        $filename = 'carte-cadeau-'.$slugify->slugify($gift->getCartItem()->getCart()->getLastname()).'-'.$slugify->slugify($gift->getCartItem()->getVariant()->getProduct()->getFullName()).'-'.$slugify->slugify($gift->getCartItem()->getVariant()->getType()->getName()).'-'.date('d_m_y_H:i').'_'.uniqid().'.pdf';
        $pdf      = $this->createPDF($html);
        $this->giftFilesystem->write($filename, $pdf->pdf());

        return $filename;
    }

    public function createGiftCardCombined(Cart $cart, Contact $contact)
    {
        $gifts = new ArrayCollection();
        foreach ($cart->getItems() as $item) {
            foreach ($item->getGifts() as $gift) {
                $gifts->add($gift);
            }
        }
        $html     = $this->twig->render('pdf/gift.html.twig', [
            'gifts'   => $gifts,
            'contact' => $contact,
        ]);
        $slugify  = new Slugify();
        $filename = 'carte-cadeau-'.$slugify->slugify($cart->getLastname()).'-'.date('d_m_y_H:i').'_'.uniqid().'.pdf';
        $pdf      = $this->createPDF($html);
        $this->giftFilesystem->write($filename, $pdf->pdf());

        return $filename;
    }

    private function createPDF(string $template)
    {
        $pdf = Browsershot::html($template)->emulateMedia('print')->noSandbox()->format('A4')->ignoreHttpsErrors()->setOption('args', ['--disable-web-security'])->showBackground()->timeout(120);
        if ($this->includePathChromium) {
            $pdf->setChromePath($this->includePathChromium);
        }
        if ($this->includePath) {
            $pdf->setIncludePath('$PATH:'.$this->includePath);
        }
        if ($this->includePathNode) {
            $pdf->setNodeBinary($this->includePathNode);
        }
        if ($this->includePathNpm) {
            $pdf->setNpmBinary($this->includePathNpm);
        }

        return $pdf;
    }
}