<?php

declare(strict_types=1);

namespace Macopedia\OrlenShipping\Plugin;

use Closure;
use Magento\Framework\App\ResourceConnection;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\Data\CartInterface;

class QuoteRepositoryPlugin
{
    /**
     * @param ResourceConnection $resourceConnection
     */
    public function __construct(
        protected readonly ResourceConnection $resourceConnection
    ) {
    }

    /**
     * Copy point details
     *
     * @param CartRepositoryInterface $subject
     * @param Closure $proceed
     * @param CartInterface $quote
     * @return void
     */
    public function aroundSave(
        CartRepositoryInterface $subject,
        Closure $proceed,
        CartInterface $quote
    ): void {
        $extensionAttributes = $quote->getExtensionAttributes();
        $proceed($quote);

        if ($extensionAttributes) {
            $connection = $this->resourceConnection->getConnection();
            $quoteTable = $this->resourceConnection->getTableName('quote');

            $attributesData = [
                'orlenpaczka_point_details' => $extensionAttributes->getOrlenpaczkaPointDetails(),
                'orlenpaczka_destination_code' => $extensionAttributes->getOrlenpaczkaDestinationCode(),
            ];

            // Remove any NULL values
            $attributesData = array_filter($attributesData, function ($value) {
                return $value !== null;
            });

            if ($attributesData) {
                $connection->update(
                    $quoteTable,
                    $attributesData,
                    ['entity_id = ?' => $quote->getId()]
                );
            }
        }
    }
}
