<?php

namespace TbiBank\FusionPay\Plugin;

use Magento\Checkout\Model\Session\Proxy as CheckoutSession;
use Magento\Payment\Model\Method\AbstractMethod;
use Psr\Log\LoggerInterface;

use TbiBank\FusionPay\Helper\Data;
use TbiBank\FusionPay\Model\ProgrammaticOrderContext;

class PaymentMethodVisibility
{
    /**
     * @var CheckoutSession
     */
    protected $checkoutSession;

    /**
     * @var ProgrammaticOrderContext
     */
    protected $programmaticOrderContext;

    /**
     * @var Data
     */
    protected $helperData;

    /**
     * @var LoggerInterface
     */
    protected $logger; // Add logger property

    /**
     * Constructor
     *
     * @param CheckoutSession $checkoutSession Checkout session instance
     */
    public function __construct(
        CheckoutSession $checkoutSession,
        ProgrammaticOrderContext $programmaticOrderContext,
        Data $helperData,
        LoggerInterface $logger // Inject LoggerInterface
        )
    {
        $this->checkoutSession = $checkoutSession;
        $this->programmaticOrderContext = $programmaticOrderContext;
        $this->helperData = $helperData;
        $this->logger = $logger; // Assign logger to class property
    }

    /**
     * Plugin after isActive
     *
     * @param AbstractMethod $subject Subject
     * @param bool $result Result
     * @return bool
     */
    public function afterIsActive(AbstractMethod $subject, $result)
    {
        // Bypass check for programmatic orders created via Gateway.php
        if ($this->programmaticOrderContext->isActive()) {
            return true;
        }

        // Check if the payment method being evaluated is FusionPay
        if ($subject->getCode() == 'fusionpay') {
            // Implement your custom logic here to determine if FusionPay should be active
            // If conditions are not met, return false to make the payment method inactive
            if (!$this->isFusionPayAvailable()) {
                return false;
            }
        }

        // For all other cases or payment methods, return the original result
        return $result;
    }

    /**
     * Check if FusionPay is available based on custom conditions
     *
     * @return bool
     */
    protected function isFusionPayAvailable()
    {
        // If module is not configured the payment method should be hidden
        if ($this->helperData->getConfigValue('tbi_settings/general_settings/status') == 'Inactive') {
            return false;
        }

        // Use helperData to retrieve minimum and maximum amount to limit visibility
        $minAmount = $this->helperData->getConfigValue('tbi_settings/label_settings/bnpl_min');
        
        // Get the highest tier limit dynamically
        $maxAmount = $minAmount; // Default fallback
        $tierCount = $this->helperData->getConfigValue('tbi_settings/label_settings/tier_count') ?: 0;
        
        if ($tierCount > 0) {
            // Find the highest tier dynamically
            for ($i = 1; $i <= $tierCount; $i++) {
                $tierAmount = $this->helperData->getConfigValue("tbi_settings/label_settings/tier{$i}");
                if ($tierAmount && $tierAmount > $maxAmount) {
                    $maxAmount = $tierAmount;
                }
            }
        }

        $minimum_visible = $this->helperData->getConfigValue('tbi_settings/label_settings/minimum_visible');
        $maximum_visible = $this->helperData->getConfigValue('tbi_settings/label_settings/maximum_visible');

        if ($minimum_visible >= $minAmount && $minimum_visible <= $maxAmount) {
            $minAmount = $minimum_visible;
        }

        if ($maximum_visible <= $maxAmount && $maximum_visible >= $minAmount) {
            $maxAmount = $maximum_visible;
        }

        $cartTotal = $this->getCartTotal();

        return $cartTotal > $minAmount && $cartTotal < $maxAmount;
    }

    /**
     * Retrieve the current cart total
     *
     * @return float
     */
    protected function getCartTotal()
    {
        $quote = $this->checkoutSession->getQuote();
        return $quote->getGrandTotal();
    }
}
