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

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ProductFormType;
use CpCreation\VitiCore\Product\Model\Product;
use CpCreation\VitiCore\Product\Repository\ProductRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

/**
 * @Security("is_granted('ROLE_ADMIN') or is_granted('ROLE_PRODUCT') or is_granted('ROLE_PRODUCT_PRICE')")
 * Class ProductController
 * @package CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Admin
 * @Route("/produits")
 */
class ProductController extends AbstractController
{
    private $productRepository;

    public function __construct(ProductRepository $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    /**
     * @route("", name="admin_product")
     * @Template("@CpCreationVitiCore/admin/product/index.html.twig")
     */
    public function indexAction()
    {
        $products = $this->productRepository->findByPositionOrderAdmin();

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

    /**
     * @param Request $request
     *
     * @Security("is_granted('ROLE_ADMIN')")
     * @Route("/new", name="admin_product_new")
     * @Template("@CpCreationVitiCore/admin/product/new.html.twig")
     *
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function newAction(Request $request)
    {
        $product = new Product();
        $form    = $this->createForm(ProductFormType::class, $product);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var Product $data */
            $data = $form->getData();
            $this->productRepository->save($data);
            $this->addFlash('alert-success', 'Le produit '.$data->getName().' a été ajouté avec succès');

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

        }

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

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

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var Product $data */
            $data = $form->getData();
            $data->setUpdatedAt(new \DateTime()); // Forcer Update de doctrine
            $this->productRepository->save($data);
            $this->addFlash('alert-success', 'Le produit '.$product->getName().' a été modifié avec succès');

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

        }

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

    /**
     * @param Product $product
     * @Route("/{id}/delete", name="admin_product_delete")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deleteAction(Product $product)
    {
        $this->productRepository->softDelete($product);
        $this->addFlash('alert-success', 'Le produit '.$product->getName().' a été supprimé avec succès.');

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

    /**
     * @param Product $product
     * @Route("/{id}/disable", name="admin_product_disable")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function disableAction(Product $product)
    {
        $product->setDisabled(1);
        $this->productRepository->save($product);
        $this->addFlash('alert-success', 'Le produit '.$product->getName().' a été dépublié.');

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

    /**
     * @param Product $product
     * @Route("/{id}/enable", name="admin_product_enable")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function enableAction(Product $product)
    {
        $product->setDisabled(0);
        $this->productRepository->save($product);
        $this->addFlash('alert-success', 'Le produit '.$product->getName().' a été publié.');

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

    /**
     * @param Product $product
     * @Route("/{id}/moveUp", name="admin_product_move_up")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function moveUpAction(Product $product)
    {
        if (($product->getPosition() - 1) < 0) {
            $this->addFlash('alert-warning', 'Le produit '.$product->getName().' ne peut être remonté.');

            return $this->redirectToRoute('admin_product');
        }
        $product->setPosition($product->getPosition() - 1);
        $this->productRepository->save($product);
        $this->addFlash('alert-success', 'Le produit '.$product->getName().' a été remonté.');

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

    /**
     * @param Product $product
     * @Route("/{id}/moveDown", name="admin_product_move_down")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function moveDownAction(Product $product)
    {
        $product->setPosition($product->getPosition() + 1);
        $this->productRepository->save($product);
        $this->addFlash('alert-success', 'Le produit '.$product->getName().' a été descendu.');

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

    /**
     * @param Product $product
     * @Route("/{id}/moveUpShop", name="admin_product_move_up_shop")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function moveUpShopAction(Product $product)
    {
        if (($product->getPositionShop() - 1) < 0) {
            $this->addFlash('alert-warning', 'Le produit '.$product->getName().' ne peut être remonté.');

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

        $products = $this->productRepository->findByPositionShopOrderAdmin();
        $position = $product->getPositionShop() - 1;
        /** @var Product $product */
        foreach ($products as $item) {
            if ($item->getPositionShop() === $position) {
                $item->setPositionShop($product->getPositionShop());
                $this->productRepository->save($item);
            }
        }

        $product->setPositionShop($product->getPositionShop() - 1);
        $this->productRepository->save($product);
        $this->addFlash('alert-success', 'Le produit '.$product->getName().' a été remonté.');

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

    /**
     * @param Product $product
     * @Route("/{id}/moveDownShop", name="admin_product_move_down_shop")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function moveDownShopAction(Product $product)
    {
        $products = $this->productRepository->findByPositionShopOrderAdmin();
        $position = $product->getPositionShop() + 1;
        /** @var Product $product */
        foreach ($products as $item) {
            if ($item->getPositionShop() === $position) {
                $item->setPositionShop($product->getPositionShop());
                $this->productRepository->save($item);
            }
        }
        $product->setPositionShop($product->getPositionShop() + 1);
        $this->productRepository->save($product);
        $this->addFlash('alert-success', 'Le produit '.$product->getName().' a été descendu.');

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

    /**
     * @Route("/initPositionShop", name="admin_product_init_position_shop")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function initPositionShopAction()
    {
        $products = $this->productRepository->findByPositionOrderAdmin();
        $i        = 0;
        /** @var Product $product */
        foreach ($products as $product) {
            if ($product->getDeletedAt()) {
                $product->setPositionShop(-1);
                $i--;
            } else {
                $product->setPositionShop($i);
            }
            $this->productRepository->persist($product);
            $i++;
        }
        $this->productRepository->flush();
        $this->addFlash('alert-success', 'La position des produits dans la page boutique a été réinitialisé');

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

    /**
     * @Route("/initPosition", name="admin_product_init_position")
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function initPositionAction()
    {
        $products = $this->productRepository->findByCreatedAdminAt('ASC');
        $i        = 0;
        /** @var Product $product */
        foreach ($products as $product) {
            if ($product->getDeletedAt()) {
                $product->setPosition(-1);
                $i--;
            } else {
                $product->setPosition($i);
            }
            $this->productRepository->save($product);
            $i++;
        }
        $this->productRepository->flush();
        $this->addFlash('alert-success', 'La position des produits dans la page cuvées a été réinitialisé');

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