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

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ShippingConfigType;
use CpCreation\VitiCore\Shop\Model\ShippingConfig;
use CpCreation\VitiCore\Shop\Repository\ShippingConfigRepository;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

/**
 * @Security("is_granted('ROLE_ADMIN') or is_granted('ROLE_SHIPPING')")
 * Class ShippingConfigController
 * @package CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Admin
 * @Route("/shipping-config")
 */
class ShippingConfigController extends AbstractController
{
    private $shippingConfigRepository;
    private $em;

    public function __construct(ShippingConfigRepository $shippingConfigRepository, EntityManagerInterface $em)
    {
        $this->shippingConfigRepository = $shippingConfigRepository;
        $this->em                       = $em;
    }

    /**
     * @route("", name="admin_shipping_config")
     * @Template("@CpCreationVitiCore/admin/shipping/config/index.html.twig")
     */
    public function indexAction()
    {
        $config = $this->shippingConfigRepository->findAll();

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


    /**
     * @param Request $request
     * @Route("/new", name="admin_shipping_config_new")
     * @Template("@CpCreationVitiCore/admin/shipping/config/new.html.twig")
     *
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function newAction(Request $request)
    {

        $form = $this->createForm(ShippingConfigType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var ShippingConfig $data */
            $data = $form->getData();
            $this->shippingConfigRepository->save($data);
            $this->addFlash('alert-success', 'La configuration a été ajouté avec succès');

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

        }

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

    /**
     * @param ShippingConfig $config
     * @param Request        $request
     * @Route("/{id}/edit", name="admin_shipping_config_edit")
     * @Template("@CpCreationVitiCore/admin/shipping/config/edit.html.twig")
     *
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function editAction(ShippingConfig $config, Request $request)
    {
        $form = $this->createForm(ShippingConfigType::class, $config);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var ShippingConfig $data */
            $data = $form->getData();
            $data->setUpdatedAt(new \DateTime()); // Forcer Update de doctrine
            $this->shippingConfigRepository->save($data);
            $this->addFlash('alert-success', 'La configuration a été modifié avec succès');

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

        }

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

    /**
     * @param ShippingConfig $config
     * @Route("/{id}/delete", name="admin_shipping_config_delete")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deleteAction(ShippingConfig $config)
    {
        $this->shippingConfigRepository->delete($config);
        $this->addFlash('alert-success', 'La configuration a été supprimé avec succès.');

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


    /**
     * @param ShippingConfig $config
     * @route("/{id}/delete/price", name="admin_shipping_config_price_delete")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     * @throws \Doctrine\DBAL\DBALException
     */
    public function deleteShippingPrice(ShippingConfig $config)
    {
        $connection = $this->em->getConnection();
        $platform   = $connection->getDatabasePlatform();
        $connection->executeUpdate($platform->getTruncateTableSQL('shop_shipping_auto', true));
        $config->setFile(null);
        $this->shippingConfigRepository->save($config);

        return $this->redirectToRoute('admin_shipping_config_edit', ['id' => $config->getId()]);
    }

    /**
     * @param ShippingConfig $config
     * @route("/{id}/delete/sup", name="admin_shipping_config_sup_delete")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     * @throws \Doctrine\DBAL\DBALException
     */
    public function deleteShippingCost(ShippingConfig $config)
    {
        $connection = $this->em->getConnection();
        $platform   = $connection->getDatabasePlatform();
        $connection->executeUpdate($platform->getTruncateTableSQL('shop_shipping_auto_sup', true));
        $config->setFileSup(null);
        $this->shippingConfigRepository->save($config);

        return $this->redirectToRoute('admin_shipping_config_edit', ['id' => $config->getId()]);
    }
}
