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

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

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

        $formHandler = $this->get('prestashop.module.agilemultisellerpro.form.commissions_rate.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_rate');
        }

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

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

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

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

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

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

        if (null !== $commissionRate) {
            /** @var EntityManagerInterface $em */
            $em = $this->get('doctrine.orm.entity_manager');
            $em->remove($commissionRate);
            $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%' => $idCommissionRate]
                )
            );
        }

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

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