<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Quote\Api\CartManagementInterface;

/**
 *
 */
class CheckoutSubmitBeforeObserver implements ObserverInterface
{
    /**
     * @param Observer $observer
     */
    public function execute(Observer $observer)
    {
        $quote = $observer->getData('quote');

        if (!$quote || !$quote->getBillingAddress()) {
            return;
        }

        if ($quote->getCheckoutMethod() === CartManagementInterface::METHOD_GUEST) {
            $billingAddress = $quote->getBillingAddress();
            $quote->setCustomerFirstname($billingAddress->getFirstname());
            $quote->setCustomerLastname($billingAddress->getLastname());
            if ($billingAddress->getMiddlename() !== null) {
                $quote->setCustomerMiddlename($billingAddress->getMiddlename());
            }
        }
    }

}
