<?php

declare(strict_types=1);

namespace Macopedia\OrlenShipping\Observer;

use Macopedia\OrlenShipping\Model\Carrier\OrlenShipping;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class CopyPointDetails implements ObserverInterface
{
    /**
     * Copy point details from quote to order
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer): void
    {
        $quote = $observer->getEvent()->getQuote();
        $order = $observer->getEvent()->getOrder();

        if ($quote && $order) {
            if (!str_contains($quote->getShippingAddress()->getShippingMethod(), OrlenShipping::CODE)) {
                $quote->setData('orlenpaczka_point_details', null);
                $quote->setData('orlenpaczka_destination_code', null);
            }
            $order->setData('orlenpaczka_point_details', $quote->getData('orlenpaczka_point_details'));
            $order->setData('orlenpaczka_destination_code', $quote->getData('orlenpaczka_destination_code'));

            $destinationCode = $quote->getData('orlenpaczka_destination_code');
            $pointDetails = $quote->getData('orlenpaczka_point_details');
            if ($destinationCode && $pointDetails) {
                $order->setShippingDescription(
                    sprintf('%s - %s', 'ORLEN Paczka', $destinationCode . ' ' . $pointDetails)
                );
            }
        }
    }
}
