<?php
declare(strict_types=1);

namespace FiloBlu\Rma\Helper;

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\Store\Model\ScopeInterface;

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';

    /**
     * @param ScopeConfigInterface $scopeConfig
     * @param Context $context
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        Context              $context
    ) {
        $this->scopeConfig = $scopeConfig;
        parent::__construct($context);
    }

    /**
     * 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 $order
     * @return bool
     */
    public function isIbanRequired(OrderInterface $order) : bool
    {
        $mappedPaymentMethods = $this->getPaymentMethodsConfigArray();

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

        $payedWith = $order->getPayment()->getMethod();
        $ccType = $order->getPayment()->getCcType();

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

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