<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Hook\Admin\Legacy;

use Gls\GlsPoland\Configuration\Api;
use Gls\GlsPoland\Controller\Admin\ConsignmentController;
use Gls\GlsPoland\PrestaShop\Grid\Filters\ConsignmentFilters;
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 DisplayAdminOrderContentShip extends AbstractLegacyOrdersPageHook
{
    public const HOOK_NAME = 'displayAdminOrderContentShip';

    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;
    }

    /**
     * @param array{order: \Order} $parameters
     */
    public function execute(array $parameters): string
    {
        $order = $parameters['order'] ?? null;

        if (!$order instanceof \Order || 0 >= $orderId = (int) $order->id) {
            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/legacy/admin_order_content_ship.html.twig', [
            'can_create' => true,
            'order_id' => $orderId,
            'grid' => $this->gridPresenter->present($grid),
        ]);
    }
}
