<?php
/**
 * 2007-2023 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 *  @author    PrestaShop SA <contact@prestashop.com>
 *  @copyright 2007-2023 PrestaShop SA
 *  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 */
declare(strict_types=1);

namespace PrestaShop\Module\AgileMultisellerPro\Controller\Admin;

use PrestaShop\Module\AgileMultisellerPro\Grid\SellerLocations\AgileDefinitionFactory;
use PrestaShop\Module\AgileMultisellerPro\Grid\SellerLocations\AgileFilters;
use PrestaShop\PrestaShop\Core\Foundation\Database\EntityNotFoundException;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use PrestaShopBundle\Security\Annotation\AdminSecurity;
use PrestaShopBundle\Security\Annotation\ModuleActivated;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

if (!defined('_PS_VERSION_')) {
    exit;
}

/**
 * Class AdminSellerLocations.
 *
 * @ModuleActivated(moduleName="agilemultisellerpro", redirectRoute="admin_module_manage")
 */
class SellerLocations extends FrameworkBundleAdminController
{
    /**
     * List sellers
     *
     * @AdminSecurity("is_granted('read', request.get('_legacy_controller'))", message="Access denied.")
     *
     * @param AgileFilters $filters
     *
     * @return Response
     */
    public function index(AgileFilters $filters): Response
    {
        $dataGridFactory = $this->get('prestashop.module.agilemultisellerpro.grid.factory.sellerlocations');
        $dataGrid = $dataGridFactory->getGrid($filters);

        return $this->render(
            '@Modules/agilemultisellerpro/views/templates/admin/form/grid_form.html.twig',
            [
                'enableSidebar' => true,
                'layoutTitle' => $this->trans('Seller Shipping Locations', 'Modules.Agilemultisellerpro.Admin'),
                'layoutHeaderToolbarBtn' => $this->getToolbarButtons(),
                'dataGrid' => $this->presentGrid($dataGrid),
            ]
        );
    }

    /**
     * Provides filters functionality.
     *
     * @param Request $request
     *
     * @return RedirectResponse
     */
    public function searchAction(Request $request)
    {
        /** @var ResponseBuilder $responseBuilder */
        $responseBuilder = $this->get('prestashop.bundle.grid.response_builder');

        return $responseBuilder->buildSearchResponse(
            $this->get('prestashop.module.agilemultisellerpro.grid.sellerlocations.definitionfactory'),
            $request,
            AgileDefinitionFactory::GRID_ID,
            'admin_agile_seller_locations'
        );
    }

    /**
     * Create location
     *
     * @param Request $request
     *
     * @return Response
     */
    public function createAction(Request $request)
    {
        $sellerLocationFormBuilder = $this->get('prestashop.module.agilemultisellerpro.form.sellerlocation.form_builder');
        $sellerLocation = $sellerLocationFormBuilder->getForm();
        $sellerLocation->handleRequest($request);

        $sellerLocationFormHandler = $this->get('prestashop.module.agilemultisellerpro.form.sellerlocation.form_handler');

        try {
            $result = $sellerLocationFormHandler->handle($sellerLocation);
            $bjectId = $result->getIdentifiableObjectId();
        } catch (\Exception $e) {
            $this->addFlash(
                'error',
                $e->getMessage()
            );
            $bjectId = null;
        }

        if (null !== $bjectId) {
            $this->addFlash('success', $this->trans('Successful update.', 'Admin.Notifications.Success'));

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

        return $this->render(
            '@Modules/agilemultisellerpro/views/templates/admin/form/edit.html.twig',
            [
                'formTitle' => $this->trans('Seller Location', 'Modules.Agilemultisellerpro.Admin'),
                'formPathReturn' => $this->generateUrl('admin_agile_seller_locations'),
                'dataForm' => $sellerLocation->createView(),
            ]
        );
    }

    /**
     * Edit location
     *
     * @param Request $request
     * @param int $sellerLocationId
     *
     * @return Response
     */
    public function editAction(Request $request, $sellerLocationId)
    {
        $isError = false;
        $sellerLocationFormBuilder = $this->get('prestashop.module.agilemultisellerpro.form.sellerlocation.form_builder');
        $sellerLocation = $sellerLocationFormBuilder->getFormFor((int) $sellerLocationId);
        $sellerLocation->handleRequest($request);

        try {
            $sellerLocationFormHandler = $this->get('prestashop.module.agilemultisellerpro.form.sellerlocation.form_handler');
            $result = $sellerLocationFormHandler->handleFor((int) $sellerLocationId, $sellerLocation);
        } catch (\Exception $e) {
            $this->addFlash(
                'error',
                $e->getMessage()
            );
            $isError = true;
        }

        if (false === $isError && $result->isSubmitted() && $result->isValid()) {
            $this->addFlash('success', $this->trans('Successful update.', 'Admin.Notifications.Success'));

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

        return $this->render(
            '@Modules/agilemultisellerpro/views/templates/admin/form/edit.html.twig',
            [
                'formTitle' => $this->trans('Seller Location', 'Modules.Agilemultisellerpro.Admin'),
                'formPathReturn' => $this->generateUrl('admin_agile_seller_locations'),
                'dataForm' => $sellerLocation->createView(),
            ]
        );
    }

    /**
     * Delete seller location
     *
     * @param int $sellertypeId
     *
     * @return Response
     */
    public function deleteAction($sellerLocationId)
    {
        $repository = $this->get('prestashop.module.agilemultisellerpro.repository.sellerlocation_repository');
        try {
            $sellerLocation = $repository->findOneBy(['idLocationCarrier' => $sellerLocationId]);
        } catch (EntityNotFoundException $e) {
            $sellerLocation = null;
        }

        if (null !== $sellerLocation) {
            /** @var EntityManagerInterface $em */
            $em = $this->get('doctrine.orm.entity_manager');
            $em->remove($sellerLocation);
            $em->flush();

            $this->addFlash(
                'success',
                $this->trans('Successful deletion.', 'Admin.Notifications.Success')
            );
        } else {
            $this->addFlash(
                'error',
                $this->trans(
                    'Cannot find seller location %type%',
                    'Modules.Agilemultisellerpro.Admin',
                    ['%type%' => $sellerLocationId]
                )
            );
        }

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

    /**
     * @return array[]
     */
    private function getToolbarButtons()
    {
        return [
            'add' => [
                'desc' => $this->trans('Add new location', 'Modules.Agilemultisellerpro.Admin'),
                'icon' => 'add_circle_outline',
                'href' => $this->generateUrl('admin_agile_seller_locations_add'),
            ],
        ];
    }
}
