<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Jet Theme Backend for Magento 2 (System)
 */

namespace Amasty\JetTheme\Block\Checkout;

use Amasty\JetTheme\Model\StoreThemeMapper;
use Magento\Checkout\Block\Checkout\LayoutProcessorInterface;
use Psr\Log\LoggerInterface;

class LayoutProcessor implements LayoutProcessorInterface
{
    /**
     * @var StoreThemeMapper
     */
    private $storeThemeMapper;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(
        StoreThemeMapper $storeThemeMapper,
        LoggerInterface $logger
    ) {
        $this->logger = $logger;
        $this->storeThemeMapper = $storeThemeMapper;
    }

    /**
     * Process js Layout of block
     *
     * @param array $jsLayout
     * @return array
     */
    public function process($jsLayout): array
    {
        try {
            if (!$this->storeThemeMapper->isCurrentThemeJetTheme()) {
                return $jsLayout;
            }

            if (isset($jsLayout["components"]["checkout"]["children"]["sidebar"]["children"]["shipping-information"])) {
                $shippingInformation = $jsLayout["components"]["checkout"]["children"]["sidebar"]["children"]
                ["shipping-information"];

                unset($jsLayout["components"]["checkout"]["children"]["sidebar"]["children"]
                    ["shipping-information"]);

                $this->modifyShippingInformation($shippingInformation);

                $jsLayout["components"]["checkout"]["children"]
                ["steps"]["children"]["billing-step"]["children"]['shipping-information'] = $shippingInformation;
            }
        } catch (\Exception $e) {
            $this->logger->critical($e);
        }

        return $jsLayout;
    }

    /**
     * DDM Compatibility
     *
     * @param array $shippingInformation
     */
    private function modifyShippingInformation(array &$shippingInformation): void
    {
        $needToUnset = !empty(
            $shippingInformation["children"]["ship-to"]["children"]
            ["amasty-delivery-date-sidebar"]["config"]["deps"][0]
        );

        if ($needToUnset) {
            unset($shippingInformation["children"]["ship-to"]["children"]
                ["amasty-delivery-date-sidebar"]["config"]["deps"][0]);
        }
    }
}
