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

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

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\ShippingAutoSupType;
use CpCreation\VitiCore\Shop\Model\ShippingAutoSup;
use CpCreation\VitiCore\Shop\Repository\ShippingAutoSupRepository;
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')")
 * Class ShippingAutoSupController
 * @package CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Admin
 * @Route("/shipping-auto-sup")
 */
class ShippingAutoSupController extends AbstractController
{
    private $shippingAutoSupRepository;

    public function __construct(ShippingAutoSupRepository $shippingAutoSupRepository)
    {
        $this->shippingAutoSupRepository = $shippingAutoSupRepository;
    }

    /**
     * @route("", name="admin_shipping_auto_sup")
     * @Template("@CpCreationVitiCore/admin/shipping/autosup/index.html.twig")
     */
    public function indexAction()
    {
        $cities = $this->shippingAutoSupRepository->findOrder();
        $citiesNoFound = $this->shippingAutoSupRepository->findCheckFalse();

        return [
            "items" => $cities,
            "citiesNoFound" => $citiesNoFound
        ];
    }

    /**
     * @param ShippingAutoSup $shippingAutoSup
     * @param Request $request
     * @route("/{id}/edit", name="admin_shipping_auto_sup_edit")
     * @Template("@CpCreationVitiCore/admin/shipping/autosup/edit.html.twig")
     *
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function editAction(ShippingAutoSup $shippingAutoSup, Request $request)
    {
        $form = $this->createForm(ShippingAutoSupType::class, $shippingAutoSup);
        $form->handleRequest($request);
        if($form->isSubmitted() && $form->isValid())
        {
            /** @var $shippingAutoSup $data */
            $data = $form->getData();
            $this->shippingAutoSupRepository->save($data);
            $this->addFlash('alert-success', 'La ville '.$shippingAutoSup->getCity().' a été modifié avec succès. ');

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

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