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

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Admin;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\CartCheckoutShippingType;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils\Mailer;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils\Pdf;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils\PdfPuppeteer;
use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Cart\Model\CartCheckout;
use CpCreation\VitiCore\Cart\Repository\CartCheckoutRepository;
use CpCreation\VitiCore\Contact\Model\Contact;
use CpCreation\VitiCore\Contact\Repository\ContactRepository;
use Doctrine\ORM\EntityManagerInterface;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Filesystem\GiftFilesystem;


/**
 * @Security("is_granted('ROLE_ADMIN') or is_granted('ROLE_ORDER')")
 * Class OrderController
 *
 * @Route("/order")
 */
class OrderController extends AbstractController
{
    private $cartCheckoutRepository;
    private $contactRepository;
    private $em;
    private $pdf;
    private $mailer;
    private $pathsReturn;
    private $kernelRootDir;
    private $giftFilesystem;
    private $pdfPuppeteer;
    private $kernel;
    private $eventDispatcher;
    private $giftFilesystemAdaper;

    public function __construct(CartCheckoutRepository $cartCheckoutRepository,
        ContactRepository $contactRepository,
        EntityManagerInterface $em,
        Pdf $pdf,
        GiftFilesystem $giftFilesystem,
        Mailer $mailer,
        string $kernelRootDir,
        KernelInterface $kernel,
        EventDispatcherInterface $eventDispatcher,
        PdfPuppeteer $pdfPuppeteer,
        $giftFilesystemAdapter,
        $paths
    ) {
        $this->cartCheckoutRepository = $cartCheckoutRepository;
        $this->contactRepository      = $contactRepository;
        $this->em                     = $em;
        $this->pdf                    = $pdf;
        $this->mailer                 = $mailer;
        $this->pathsReturn            = $paths;
        $this->kernelRootDir          = $kernelRootDir;
        $this->giftFilesystem         = $giftFilesystem;
        $this->pdfPuppeteer           = $pdfPuppeteer;
        $this->kernel                 = $kernel;
        $this->eventDispatcher        = $eventDispatcher;
        $this->giftFilesystemAdaper   = $giftFilesystemAdapter;
    }

    /**
     * @Route("", name="admin_order")
     * @Template("@CpCreationVitiCore/admin/order/index.html.twig")
     */
    public function indexAction()
    {
        $orders = $this->cartCheckoutRepository->findByCreatedAdminAt('ASC');

        return [
            "items" => $orders,
        ];
    }

    /**
     * @param Request      $request
     * @param CartCheckout $cartCheckout
     *
     * @Route("/{id}/pdf", name="admin_order_pdf")
     * @Template("@CpCreationVitiCore/admin/order/index.html.twig")
     *
     * @return RedirectResponse
     * @throws \Doctrine\ORM\NonUniqueResultException
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function pdfAction(Request $request, CartCheckout $cartCheckout)
    {
        /** Récréer un pdf avec un variant désactivé => deletedAt Not Null  */
        $this->em->getFilters()->disable("soft_deletable");
        $contact  = $this->contactRepository->findOne();
        $filename = $this->pdf->createPdfOrderAdmin($contact, $cartCheckout->getCart());

        return new RedirectResponse($request->getUriForPath('/order/'.$filename));
    }

    /**
     * @param Request $request
     * @param Cart    $cart
     *
     * @Route("/{id}/download", name="admin_order_gift_download")
     * @return Response
     */
    public function downloadAction(Cart $cart): Response
    {
        $contact = $this->contactRepository->findOne();
        $path = $this->giftFilesystemAdaper->getAdapter()->getPathPrefix();
        $filename = $this->pdfPuppeteer->createGiftCardCombined($cart,$contact);
        $file = $path.$filename;
        return $this->file($file);
    }

    /**
     * @Route("/{id}/resend_gift", name="admin_order_gift_resend")
     * @return RedirectResponse
     */
    public function resendGiftCardAction(Cart $cart): RedirectResponse
    {
        $contact = $this->contactRepository->findOne();
        $this->mailer->sendGiftCard($contact, $cart);
        $this->addFlash('alert-success', 'les cartes cadeaux ont étés renvoyés !');

        return $this->redirectToRoute('admin_order');
    }

    /**
     * @param Request      $request
     * @param CartCheckout $cartCheckout
     *
     * @Route("/{id}/html", name="admin_order_order")
     * @Template("@CpCreationVitiCore/admin/order/order.html.twig")
     *
     * @return array
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function htmlAction(Request $request, CartCheckout $cartCheckout)
    {
        $this->em->getFilters()->disable("soft_deletable");
        $contact = $this->contactRepository->findOne();

        return [
            'contact' => $contact,
            'cart'    => $cartCheckout->getCart(),
            'admin'   => true,
            'html'    => true,
        ];
    }

    /**
     * @param Request      $request
     * @param CartCheckout $cartCheckout
     *
     * @Route("/{id}/delivery", name="admin_order_delivery")
     * @Template("@CpCreationVitiCore/admin/order/delivery.html.twig")
     *
     * @return array|RedirectResponse
     */
    public function deliveryAction(Request $request, CartCheckout $cartCheckout)
    {
        $this->em->getFilters()->disable("soft_deletable");
        $form = $this->createForm(
            CartCheckoutShippingType::class, $cartCheckout, [
                'validation_groups' => [
                    'admin',
                ],
            ]
        );

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            /** @var CartCheckout $data */
            $data = $form->getData();
            $this->cartCheckoutRepository->save($data);
            $this->addFlash('alert-success', 'La commande de '.$data->getCart()->getInvoiceAddress()->getCompany().' '.$data->getCart()->getInvoiceAddress()->getLastname().' '.$data->getCart()->getInvoiceAddress()->getFirstname().' a été mis à jour');

            return $this->redirectToRoute('admin_order');

        }

        return [
            "form" => $form->createView(),
            "item" => $cartCheckout,
        ];
    }

    /**
     * @param Request      $request
     * @param CartCheckout $cartCheckout
     *
     * @Route("/{id}/delivery-resend", name="admin_order_delivery_resend")
     *
     * @return RedirectResponse
     * @throws \Doctrine\ORM\NonUniqueResultException
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function deliveryResendAction(Request $request, CartCheckout $cartCheckout)
    {
        $this->em->getFilters()->disable("soft_deletable");
        $contact = $this->contactRepository->findOne();

        $this->mailer->senDelivery($contact, $cartCheckout->getCart());
        $this->addFlash('alert-success', 'Email renvoyé pour la commande de '.$cartCheckout->getCart()->getInvoiceAddress()->getCompany().' '.$cartCheckout->getCart()->getInvoiceAddress()->getLastname().' '.$cartCheckout->getCart()->getInvoiceAddress()->getFirstname());

        return $this->redirectToRoute('admin_order');

    }

    /**
     * @param CartCheckout $cartCheckout
     *
     * @Route("/{id}/payedAt", name="admin_order_payedAt")
     * @return RedirectResponse
     */
    public function payedAction(CartCheckout $cartCheckout)
    {
        if (!$cartCheckout->getPayedAt()) {
            $cartCheckout->setPayedAt(new \DateTime());
        } else {
            $cartCheckout->setPayedAt(null);
        }
        $this->cartCheckoutRepository->save($cartCheckout);

        return $this->redirectToRoute('admin_order');
    }

    /**
     * @param CartCheckout $cartCheckout
     * @Route("/{id}/redirect/payment", name="admin_order_redirect_payment")
     *
     * @return RedirectResponse
     */
    public function redirectPagePaymentAction(CartCheckout $cartCheckout)
    {
        $method = $cartCheckout->getPaymentMethod()->getMethod();
        $method = str_replace("-", "", $method);
        $path   = $this->pathsReturn[$method]['path'];

        return $this->redirectToRoute(
            $path, ["id" => $cartCheckout->getCart()->getId()]
        );

    }

    /**
     * @param CartCheckout $cartCheckout
     * @Route("/{id}/disabled", name="admin_order_disabled")
     *
     * @return RedirectResponse
     */
    public function deleteAction(CartCheckout $cartCheckout)
    {
        $this->cartCheckoutRepository->softDelete($cartCheckout);
        $this->addFlash('alert-success', 'La commande '.$cartCheckout->getPayedToken().' a été supprimé.');

        return $this->redirectToRoute('admin_order');

    }

    /**
     * @param Cart $cart
     * @return Response
     * @Template("@CpCreationVitiCore/admin/order/gift.html.twig")
     */
    public function showGiftOptions(Cart $cart){

        $this->em->getFilters()->enable("soft_deletable");
        $this->em->getFilters()->disable("soft_deletable");
        $haveGift = false;
        foreach ($cart->getItems() as $item){
            if($item->getVariant()->getType()->isGift()){
                $haveGift = $item->getVariant()->getType()->isGift();
            }
        }
        return [
            'haveGift' => $haveGift,
            'item' => $cart
        ];
    }
}
