<?php

namespace FiloBlu\Rma\Observer;

use FiloBlu\Rma\Helper\RmaHelper;
use FiloBlu\Rma\Helper\RmaPoliciesHelper;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Api\OrderItemRepositoryInterface;

class OverrideTheoricShippingAmount implements ObserverInterface
{
    /**
     * @var RmaHelper
     */
    private $rmaHelper;
    /**
     * @var OrderItemRepositoryInterface
     */
    private $orderItemRepository;
    /**
     * @var RmaPoliciesHelper
     */
    private $rmaPoliciesHelper;

    /**
     * @param RmaHelper $rmaHelper
     * @param RmaPoliciesHelper $rmaPoliciesHelper
     * @param OrderItemRepositoryInterface $orderItemRepository
     */
    public function __construct(
        RmaHelper                    $rmaHelper,
        RmaPoliciesHelper            $rmaPoliciesHelper,
        OrderItemRepositoryInterface $orderItemRepository
    )
    {
        $this->rmaHelper = $rmaHelper;
        $this->orderItemRepository = $orderItemRepository;
        $this->rmaPoliciesHelper = $rmaPoliciesHelper;
    }


    public function execute(Observer $observer)
    {
        $data = $observer->getRmaData();

        $theoricShippingAmount = $observer->getTheoricShippingAmount();

        if (empty((int)$theoricShippingAmount->getValue())) {
            return;
        }

        $rmaItemsReasonPolicies = $this->rmaPoliciesHelper->getRmaItemReasonPolicy();

        if (empty($rmaItemsReasonPolicies)) {
            return;
        }

        $disallowedRmaStatues = $this->rmaHelper->getDisallowedRmaStatus();

        $rmaItemsReasonPoliciesLookup = [];

        foreach ($rmaItemsReasonPolicies as $rmaItemsReasonPolicy) {
           $rmaItemsReasonPoliciesLookup[$rmaItemsReasonPolicy['rma_item_reason']] = $rmaItemsReasonPolicy['return_cost'];
        }

        $disallowedItemsCount = 0;

        foreach ($data['items'] ?? [] as $item) {

            if (is_object($item)) {
                $item = $item->toArray();
            }

            if (empty($item['order_item_id'])) {
                continue;
            }

            if (!array_key_exists('reason', $item)) {
                continue;
            }

            if (array_key_exists($item['reason'], $rmaItemsReasonPoliciesLookup)) {
                $orderItem = $this->orderItemRepository->get($item['order_item_id']);

                $key = array_search($item['reason'], array_column($disallowedRmaStatues, 'rma_reson'));

                if (!array_key_exists($key, $disallowedRmaStatues)) {
                    continue;
                }

                $disallowedRmaStatuesItem = $disallowedRmaStatues[$key];

                $attribute = $disallowedRmaStatuesItem['rma_status_product_attribute_bind'];

                if (empty($attribute)) {
                    continue;
                }

                $product = $orderItem->getProduct();

                $showAttribute = (bool)$product->getData($attribute);

                if ($showAttribute) {
                    if (!$rmaItemsReasonPoliciesLookup[$item['reason']]) {
                        $disallowedItemsCount++;
                        continue;
                    }
                }

                if ($orderItem->getProductType() == 'configurable') {
                    $childrenItems = $orderItem->getChildrenItems();

                    if (count($childrenItems)) {
                        $childrenItem = reset($childrenItems);
                        $product = $childrenItem->getProduct();
                    }
                }

                $showAttribute = (bool)$product->getData($attribute);

                if ($showAttribute) {
                    if (!$rmaItemsReasonPoliciesLookup[$item['reason']]) {
                        $disallowedItemsCount++;
                    }
                }

            }
        }

        if ($disallowedItemsCount) {
            $theoricShippingAmount->setValue(0.0);
        }
    }

}
