<?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 Gls\GlsPoland\PrestaShop\Helper\CarrierFinder;
use Gls\GlsPoland\PrestaShop\Order\ParcelShopDetailsProvider;
use PrestaShop\PrestaShop\Core\Grid\GridFactoryInterface;
use PrestaShopBundle\Security\Voter\PageVoter;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Twig\Environment;

final class DisplayAdminOrderTabShip extends AbstractLegacyOrdersPageHook
{
    public const HOOK_NAME = 'displayAdminOrderTabShip';

    private $authorizationChecker;
    private $configuration;
    private $gridFactory;
    private $parcelShopDetailsProvider;
    private $carrierFinder;
    private $twig;

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

    public function execute(array $parameters): string
    {
        $canViewGrid = $this->authorizationChecker->isGranted(PageVoter::READ, ConsignmentController::TAB_NAME)
            || $this->authorizationChecker->isGranted(PageVoter::READ, 'AdminModules');
        $order = $parameters['order'] ?? null;

        $isGlsCarrier = $order instanceof \Order
            && \Validate::isLoadedObject($order)
            && null !== $this->carrierFinder->findOneByCarrierId((int) $order->id_carrier);

        $hasParcelShop = $order instanceof \Order
            && \Validate::isLoadedObject($order)
            && null !== $this->parcelShopDetailsProvider->getForOrder($order);

        $hasConsignments = false;

        if ($canViewGrid && $order instanceof \Order && \Validate::isLoadedObject($order) && 0 < (int) $order->id) {
            /** @var ConsignmentFilters $filters */
            $filters = ConsignmentFilters::buildDefaults();
            $filters->addFilter([
                'id_order' => (int) $order->id,
                'sandbox' => $this->configuration->isSandboxEnabled(),
            ]);

            $hasConsignments = 0 < $this->gridFactory->getGrid($filters)->getData()->getRecordsTotal();
        }

        if (!$isGlsCarrier && !$hasParcelShop && !$hasConsignments) {
            return '';
        }

        return $this->twig->render('@Modules/glspoland/views/templates/hook/legacy/admin_order_tab_ship.html.twig');
    }
}
