<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Hook\Admin;

use Gls\GlsPoland\Configuration\Api;
use Gls\GlsPoland\Controller\Admin\ConsignmentController;
use Gls\GlsPoland\PrestaShop\Grid\Filters\ConsignmentFilters;
use Gls\GlsPoland\PrestaShop\Hook\PrestaShopVersionAwareHookInterface;
use Gls\GlsPoland\PrestaShop\Hook\VersionRange;
use PrestaShop\PrestaShop\Core\Grid\GridFactoryInterface;
use PrestaShop\PrestaShop\Core\Grid\Presenter\GridPresenterInterface;
use PrestaShopBundle\Security\Voter\PageVoter;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Twig\Environment;

final class DisplayAdminOrderTabContent implements PrestaShopVersionAwareHookInterface
{
    public const HOOK_NAME = 'displayAdminOrderTabContent';

    private $authorizationChecker;
    private $configuration;
    private $gridFactory;
    private $gridPresenter;
    private $twig;

    public function __construct(AuthorizationCheckerInterface $authorizationChecker, Api\ConfigurationInterface $configuration, GridFactoryInterface $gridFactory, GridPresenterInterface $gridPresenter, Environment $twig)
    {
        $this->authorizationChecker = $authorizationChecker;
        $this->configuration = $configuration;
        $this->gridFactory = $gridFactory;
        $this->gridPresenter = $gridPresenter;
        $this->twig = $twig;
    }

    public static function getVersionRange(): VersionRange
    {
        return new VersionRange('1.7.7');
    }

    /**
     * @param array{id_order: int} $parameters
     */
    public function execute(array $parameters): string
    {
        if (0 >= $orderId = (int) ($parameters['id_order'] ?? null)) {
            return '';
        }

        if (!$this->authorizationChecker->isGranted(PageVoter::READ, ConsignmentController::TAB_NAME)) {
            return '';
        }

        /** @var ConsignmentFilters $filters */
        $filters = ConsignmentFilters::buildDefaults();
        $filters->addFilter([
            'id_order' => $orderId,
            'sandbox' => $this->configuration->isSandboxEnabled(),
        ]);

        $grid = $this->gridFactory->getGrid($filters);

        return $this->twig->render('@Modules/glspoland/views/templates/hook/admin_order_tab_content.html.twig', [
            'can_create' => $this->authorizationChecker->isGranted(PageVoter::CREATE, ConsignmentController::TAB_NAME),
            'order_id' => $orderId,
            'grid' => $this->gridPresenter->present($grid),
        ]);
    }
}
