<?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\CommissionBase\AgileDefinitionFactory;
use PrestaShop\Module\AgileMultisellerPro\Grid\CommissionBase\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 AdminCommissionBase.
 *
 * @ModuleActivated(moduleName="agilemultisellerpro", redirectRoute="admin_module_manage")
 */
class CommissionBase 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.commissions_base');
        $dataGrid = $dataGridFactory->getGrid($filters);

        return $this->render(
            '@Modules/agilemultisellerpro/views/templates/admin/form/grid_form.html.twig',
            [
                'enableSidebar' => true,
                'layoutTitle' => $this->trans('Transaction Fee', '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.commissions_base.definitionfactory'),
            $request,
            AgileDefinitionFactory::GRID_ID,
            'admin_agile_commissions_base'
        );
    }

    /**
     * Create type
     *
     * @param Request $request
     *
     * @return Response
     */
    public function createAction(Request $request)
    {
        $formBuilder = $this->get('prestashop.module.agilemultisellerpro.form.commissions_base.form_builder');
        $commissionsBase = $formBuilder->getForm();
        $commissionsBase->handleRequest($request);

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

        try {
            $result = $formHandler->handle($commissionsBase);
            $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_commissions_base');
        }

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

    /**
     * Edit type
     *
     * @param Request $request
     * @param int $idCommissionBase
     *
     * @return Response
     */
    public function editAction(Request $request, $idCommissionBase)
    {
        $isError = false;
        $formBuilder = $this->get('prestashop.module.agilemultisellerpro.form.commissions_base.form_builder');
        $commissionsBase = $formBuilder->getFormFor((int) $idCommissionBase);
        $commissionsBase->handleRequest($request);

        try {
            $formHandler = $this->get('prestashop.module.agilemultisellerpro.form.commissions_base.form_handler');
            $result = $formHandler->handleFor((int) $idCommissionBase, $commissionsBase);
        } 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_commissions_base');
        }

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

    /**
     * Delete type
     *
     * @param int $idCommissionBase
     *
     * @return Response
     */
    public function deleteAction($idCommissionBase)
    {
        $repository = $this->get('prestashop.module.agilemultisellerpro.repository.commissions_base_repository');

        try {
            $commissionBase = $repository->findOneBy(['idCommissionBase' => $idCommissionBase]);
        } catch (EntityNotFoundException $e) {
            $commissionBase = null;
        }

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

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

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

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