<?php

declare(strict_types=1);

namespace Macopedia\OrlenShipping\Controller\Adminhtml\Point;

use Macopedia\OrlenShipping\Model\Carrier\OrlenShipping;
use Macopedia\OrlenShipping\Helper\Data;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Controller\Result\RawFactory;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Registry;
use Magento\Framework\Translate\InlineInterface;
use Magento\Framework\View\Result\LayoutFactory;
use Magento\Framework\View\Result\PageFactory;
use Magento\Sales\Api\Data\OrderExtensionInterface;
use Magento\Sales\Api\OrderManagementInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Controller\Adminhtml\Order;
use Magento\Sales\Controller\Adminhtml\Order\View;
use Psr\Log\LoggerInterface;

class Save extends Order
{
    /**
     * @param Context $context
     * @param Registry $coreRegistry
     * @param FileFactory $fileFactory
     * @param InlineInterface $translateInline
     * @param PageFactory $resultPageFactory
     * @param JsonFactory $resultJsonFactory
     * @param LayoutFactory $resultLayoutFactory
     * @param RawFactory $resultRawFactory
     * @param OrderManagementInterface $orderManagement
     * @param OrderRepositoryInterface $orderRepository
     * @param LoggerInterface $logger
     * @param Data $helper
     */
    public function __construct(
        Context $context,
        Registry $coreRegistry,
        FileFactory $fileFactory,
        InlineInterface $translateInline,
        PageFactory $resultPageFactory,
        JsonFactory $resultJsonFactory,
        LayoutFactory $resultLayoutFactory,
        RawFactory $resultRawFactory,
        OrderManagementInterface $orderManagement,
        OrderRepositoryInterface $orderRepository,
        LoggerInterface $logger,
        protected readonly Data $helper,
    ) {
        parent::__construct(
            $context,
            $coreRegistry,
            $fileFactory,
            $translateInline,
            $resultPageFactory,
            $resultJsonFactory,
            $resultLayoutFactory,
            $resultRawFactory,
            $orderManagement,
            $orderRepository,
            $logger
        );
    }

    /**
     * Is allowed
     *
     * @return bool
     */
    protected function _isAllowed(): bool
    {
        return $this->_authorization->isAllowed(View::ADMIN_RESOURCE);
    }

    /**
     * Execute action based on request and return result
     *
     * @return ResultInterface
     */
    public function execute(): ResultInterface
    {
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $description = $this->getRequest()->getParam('description');
        $destinationCode = $this->getRequest()->getParam('destination_code');
        try {
            if ($description && $destinationCode) {
                $order = $this->_initOrder();
                /** @var  OrderExtensionInterface $extensionAttributes */
                $extensionAttributes = $order->getExtensionAttributes();
                if ($order->getIsNotVirtual() &&
                    $extensionAttributes &&
                    $extensionAttributes->getShippingAssignments()
                ) {
                    $pointDetails = sprintf('%s - %s', 'ORLEN Paczka', $destinationCode . ' ' . $description);
                    $order->setShippingDescription($pointDetails);
                    $order->setData('orlenpaczka_destination_code', $destinationCode);
                    $order->setData('orlenpaczka_point_details', $description);
                    $order->setExtensionAttributes($extensionAttributes);
                    $this->orderRepository->save($order);

                    $resultJson->setData([
                        'type' => 'success',
                        'pointAddress' => $pointDetails,
                    ]);
                }
            }
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage(), $e->getTrace());
            $resultJson->setData([
                'type' => 'error',
                'message' => $e->getMessage(),
            ]);
        }

        return $resultJson;
    }
}
