<?php
namespace TbiBank\FusionPay\Block\Frontend;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use TbiBank\FusionPay\Helper\Data as FusionPayHelper;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\ProductRepository;
use Magento\Sales\Api\OrderRepositoryInterface;

class CheckoutModal extends Template
{
    /**
     * @var FusionPayHelper
     */
    protected $fusionPayHelper;
    protected $cart;
    protected $productRepository;
    protected $orderRepository;


    /**
     * Constructor
     *
     * @param Context $context
     * @param FusionPayHelper $fusionPayHelper
     * @param array $data
     */
    public function __construct(
        Context $context,
        FusionPayHelper $fusionPayHelper,
        Cart $cart,
        ProductRepository $productRepository,
        OrderRepositoryInterface $orderRepository,
        array $data = []
    ) {
        $this->fusionPayHelper = $fusionPayHelper;
        $this->cart = $cart;
        $this->productRepository = $productRepository;
        $this->orderRepository = $orderRepository;

        parent::__construct($context, $data);
    }
    
    /**
     * Get Calculator URL
     *
     * @return string
     */
    public function getCalculatorUrl()
    {
        $resellerCode = $this->fusionPayHelper->getConfigValue('tbi_settings/general_settings/reseller_code');
        $resellerKey = $this->fusionPayHelper->getConfigValue('tbi_settings/general_settings/reseller_key');
        $url = $this->fusionPayHelper->getConstValue('TBI_CALC_URL');

        // Ensure URL is properly encoded
        return $this->fusionPayHelper->Encode($url . '?origin=plugin&page=checkout&code=' . urlencode($resellerCode) . '&key=' . urlencode($resellerKey) . '&amount=');
    }

    /**
     * Get Loading Image
     *
     * @return string
     */
    public function getLoadingImg()
    {
        return $this->fusionPayHelper->getConstValue('TBI_LOADING_SVG');
    }

    /**
     * Get Origin
     *
     * @return string
     */
    public function getOrigin()
    {
        return $this->fusionPayHelper->Encode($this->fusionPayHelper->getConstValue('TBI_PLATFORM_URL'));
    }

    /**
     * Check if payment method is enabled
     *
     * @return bool
     */
    public function isPaymentMethodEnabled()
    {
        $status = $this->fusionPayHelper->getConfigValue('tbi_settings/general_settings/status');
        $paymentActive = $this->fusionPayHelper->getConfigValue('payment/fusionpay/active');
        
        return $status !== 'Inactive' && $paymentActive == 1;
    }

    /**
     * Render block HTML
     * Only render if payment method is enabled
     *
     * @return string
     */
    protected function _toHtml()
    {
        if (!$this->isPaymentMethodEnabled()) {
            return '';
        }
        
        return parent::_toHtml();
    }

}