<?php
declare(strict_types=1);

namespace FiloBlu\Rma\Helper;

use FiloBlu\Rma\Model\Payment\ChangeSizePay;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Store\Model\ScopeInterface;

use RuntimeException;

use function in_array;

class OfflinePaymentMethodsHelper extends AbstractHelper
{
    const IBAN_OFFLINE_PAYMENTS_ENABLED = 'filoblu_disablerma_section/iban_offline_payments/enabled';
    const IBAN_FOR_PAYMENT_METHODS = 'filoblu_disablerma_section/iban_offline_payments/iban_for_payment_methods';
    /**
     * @var \Magento\Sales\Api\OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * @param ScopeConfigInterface $scopeConfig
     * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
     * @param Context $context
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        OrderRepositoryInterface $orderRepository,
        Context              $context
    ) {
        parent::__construct($context);
        $this->orderRepository = $orderRepository;
        $this->scopeConfig = $scopeConfig;

    }

    /**
     * Check if feature for iban in form is enabled
     *
     * @return mixed
     */
    public function isIbanOfflinePaymentsEnabled()
    {
        return $this->scopeConfig->getValue(self::IBAN_OFFLINE_PAYMENTS_ENABLED, ScopeInterface::SCOPE_STORE);
    }

    /**
     * Get payment methods configuration
     *
     * @return array|mixed
     */
    public function getPaymentMethodsConfig()
    {
        if (!$this->scopeConfig->getValue(self::IBAN_FOR_PAYMENT_METHODS, ScopeInterface::SCOPE_STORE)) {
            return [];
        }

        return $this->scopeConfig->getValue(self::IBAN_FOR_PAYMENT_METHODS, ScopeInterface::SCOPE_STORE);
    }

    /**
     * Get Exploded Payment Methods configuration
     *
     * @return array
     */
    public function getPaymentMethodsConfigArray() : array
    {
        if (empty($this->getPaymentMethodsConfig())) {
            return [];
        }

        if (!explode(',', $this->getPaymentMethodsConfig())) {
            return $this->getPaymentMethodsConfig();
        }

        return explode(',', $this->getPaymentMethodsConfig());
    }

    /**
     * Check if the Iban is Required from used Payment Method
     * @param OrderInterface|\Magento\Sales\Model\Order $order
     * @return bool
     */
    public function isIbanRequired(OrderInterface $order) : bool
    {
        $orderPayment = $order->getPayment();

        if($orderPayment === null) {
            throw new RuntimeException('Missing order payment information');
        }

        $payedWith = $orderPayment->getMethod();
        $ccType = $orderPayment->getCcType();

        if($payedWith === ChangeSizePay::PAYMENT_CODE) {

             $information = $orderPayment->getAdditionalInformation();

             if(!isset($information['parent_order_id']))
             {
                 throw new RuntimeException('Missing \'parent_order_id\' information on order');
             }

            $parentOrderId = $information['parent_order_id'];
            $parentOrder =  $this->orderRepository->get($parentOrderId);

            $parentOrderPayment =  $parentOrder->getPayment();

            if($parentOrderPayment === null) {
                throw new RuntimeException('Missing parent order payment information');
            }
            $payedWith = $parentOrderPayment->getMethod();
            $ccType = $parentOrderPayment->getCcType();
        }

        $mappedPaymentMethods = $this->getPaymentMethodsConfigArray();

        if (empty($mappedPaymentMethods)) {
            return false;
        }

        if ($payedWith === 'adyen_hpp' && $ccType !== 'bankTransfer_IBAN' && $ccType !== 'multibanco') {
            return false;
        }

        return in_array($payedWith, $mappedPaymentMethods, true);
    }
}
