<?php
/**
 * Simplyin HyvaPayment - Payment Method Config for Hyva Checkout
 * Outputs quote data needed by processPayment controller
 */
declare(strict_types=1);

use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;

/** @var Template $block */
/** @var Escaper $escaper */

$paymentConfig = $block->getData('payment_config');
$isEnabled = $paymentConfig ? $paymentConfig->isSimplyinEnabled() : false;
if (!$isEnabled) return;
// Suppress SimplyIN when the merchant has no payment method configured.
// Fail-closed: a successful empty response, or any error/exception/
// unauthenticated response, hides it. Checked after the enabled guard so the
// availability API is not called when SimplyIN is disabled.
if (!$paymentConfig->hasAvailablePaymentMethods()) return;

$om = \Magento\Framework\App\ObjectManager::getInstance();
$checkoutSession = $om->get(\Magento\Checkout\Model\Session::class);
$storeManager = $om->get(\Magento\Store\Model\StoreManagerInterface::class);

$getPaymentMethodsUrl = $block->getUrl('simplyin/api/getPaymentMethods');
$processPaymentUrl = $block->getUrl('simplyin/api/processPayment');
$simplyinLogoUrl = $paymentConfig ? $paymentConfig->getSimplyinLogoUrl() : '';
$p24LogoUrl = $paymentConfig ? $paymentConfig->getP24LogoUrl() : '';

$quoteId = '';
$currency = 'USD';
$price = 0;
$shippingPrice = 0;
$shopName = 'Magento';
$shopUserEmail = '';
$itemsJson = '[]';

try {
    $store = $storeManager->getStore();
    $currency = $store->getCurrentCurrencyCode();
    $shopName = $store->getName() ?: 'Magento';
    $baseUrl = $store->getBaseUrl();
    
    $quote = $checkoutSession->getQuote();
    if ($quote && $quote->getId()) {
        // Quote ID (masked for guests)
        if ($quote->getCustomerIsGuest() || !$quote->getCustomerId()) {
            $quoteIdMaskFactory = $om->get(\Magento\Quote\Model\QuoteIdMaskFactory::class);
            $quoteIdMask = $quoteIdMaskFactory->create()->load($quote->getId(), 'quote_id');
            $quoteId = $quoteIdMask->getMaskedId() ?: (string)$quote->getId();
        } else {
            $quoteId = (string)$quote->getId();
        }
        
        $price = (float)$quote->getGrandTotal();
        $shippingPrice = (float)$quote->getShippingAddress()->getShippingAmount();
        $shopUserEmail = $quote->getCustomerEmail() ?: '';
        
        // Build items array matching Luma format
        $items = [];
        foreach ($quote->getAllVisibleItems() as $item) {
            $product = $item->getProduct();
            $itemData = [
                'name' => $item->getName(),
                'item_id' => (string)$item->getProductId(),
                'price' => (float)$item->getPriceInclTax(),
                'price_net' => (float)$item->getPrice(),
                'quantity' => (int)$item->getQty(),
                'tax_amount' => (float)$item->getTaxAmount(),
                'tax_rate' => (float)$item->getTaxPercent(),
                'currency' => $currency,
            ];
            // Product URLs
            if ($product) {
                try {
                    $itemData['url'] = $product->getProductUrl();
                    $imageHelper = $om->get(\Magento\Catalog\Helper\Image::class);
                    $itemData['thumbnailUrl'] = $imageHelper->init($product, 'product_thumbnail_image')->getUrl();
                } catch (\Exception $e) {}
            }
            $items[] = $itemData;
        }
        $itemsJson = json_encode($items);
    }
} catch (\Exception $e) {}

// Get shipping method mapping from admin config
$shippingMapping = '{}';
try {
    $apiClient = $om->get(\Simplyin\Payment\Helper\ApiClient::class);
    $shippingMapping = json_encode($apiClient->getShippingMethodMapping());
} catch (\Exception $e) {}

// Get pickup point save URL
// Get pickup point save URL (uses existing Simplyin Payment controller)
$savePickupPointUrl = $block->getUrl('simplyin/api/setPickupPoint');
?>
<div id="simplyin-payment-config" 
     style="display:none"
     data-get-methods-url="<?= $escaper->escapeHtmlAttr($getPaymentMethodsUrl) ?>"
     data-process-payment-url="<?= $escaper->escapeHtmlAttr($processPaymentUrl) ?>"
     data-simplyin-logo="<?= $escaper->escapeHtmlAttr($simplyinLogoUrl) ?>"
     data-p24-logo="<?= $escaper->escapeHtmlAttr($p24LogoUrl) ?>"
     data-quote-id="<?= $escaper->escapeHtmlAttr($quoteId) ?>"
     data-currency="<?= $escaper->escapeHtmlAttr($currency) ?>"
     data-price="<?= $escaper->escapeHtmlAttr((string)$price) ?>"
     data-shipping-price="<?= $escaper->escapeHtmlAttr((string)$shippingPrice) ?>"
     data-shop-name="<?= $escaper->escapeHtmlAttr($shopName) ?>"
     data-shop-email="<?= $escaper->escapeHtmlAttr($shopUserEmail) ?>"
     data-items="<?= $escaper->escapeHtmlAttr($itemsJson) ?>"
     data-shipping-mapping="<?= $escaper->escapeHtmlAttr($shippingMapping) ?>"
     data-save-pickup-url="<?= $escaper->escapeHtmlAttr($savePickupPointUrl) ?>">
</div>
