<?php
/**
 * Simplyin HyvaPayment - Payment Status on Success Page
 * Only shows when order was placed with simplyin_payment method.
 * Matches Luma theme design 100%.
 */
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');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$checkoutSession = $objectManager->get(\Magento\Checkout\Model\Session::class);
$order = $checkoutSession->getLastRealOrder();

if (!$order || !$order->getId()) return;

$paymentMethod = $order->getPayment() ? $order->getPayment()->getMethod() : '';
if ($paymentMethod !== 'simplyin_payment') return;

$simplyinLogoUrl = $paymentConfig ? $paymentConfig->getSimplyinLogoUrl() : '';
$checkPaymentStatusUrl = $block->getUrl('simplyin/api/checkPaymentStatus');
$orderEntityId = (int)$order->getId();

$viewModels = $objectManager->get(\Hyva\Theme\Model\ViewModelRegistry::class);
$hyvaCsp = $viewModels->require(\Hyva\Theme\ViewModel\HyvaCsp::class);
?>

<?php
// Dynamically render CSS inline from simplyin-success.css
$cssFile = $block->getViewFileUrl('Simplyin_HyvaPayment::css/simplyin-success.css');
$cssPath = realpath(__DIR__ . '/../../web/css/simplyin-success.css');
if ($cssPath && file_exists($cssPath)) {
    echo '<style>' . file_get_contents($cssPath) . '</style>';
}
?>


<div id="sly-payment-status" class="sly-ps">
    <div class="sly-ps-header">
        <div class="sly-ps-title"><?= $escaper->escapeHtml(__('Payment processing by')) ?></div>
        <div class="sly-ps-logos" id="sly-ps-logos">
            <img src="<?= $escaper->escapeUrl($simplyinLogoUrl) ?>" alt="Simply.IN">
        </div>
    </div>
    <div class="sly-ps-method">
        <input type="radio" checked disabled>
        <div class="sly-ps-method-info">
            <img id="sly-ps-method-logo" src="" alt="" style="display:none">
            <span class="sly-ps-method-name" id="sly-ps-method-name"><?= $escaper->escapeHtml(__('Credit card')) ?></span>
        </div>
        <span class="sly-ps-method-check" id="sly-ps-check" style="display:none">✓</span>
    </div>
    <div class="sly-ps-status" id="sly-ps-status">
        <div class="sly-ps-icon processing" id="sly-ps-icon">
            <svg viewBox="0 0 24 24" width="28" height="28"><circle cx="12" cy="12" r="10" fill="none" stroke="#f59e0b" stroke-width="2"/><path d="M12 6v6l4 2" fill="none" stroke="#f59e0b" stroke-width="2" stroke-linecap="round"/></svg>
        </div>
        <div class="sly-ps-msg">
            <p class="sly-ps-main" id="sly-ps-main"><?= $escaper->escapeHtml(__('Please wait for confirmation')) ?></p>
            <p class="sly-ps-sub" id="sly-ps-sub"><?= $escaper->escapeHtml(__('Processing payment...')) ?></p>
        </div>
    </div>
    <div class="sly-ps-spinner" id="sly-ps-spinner"><div class="sly-ps-spin"></div></div>
</div>

<div wire:ignore>
<script>
(function() {
    'use strict';
    if (window.__slyPS) return;
    window.__slyPS = true;
    
    var T = {
        creditCard: '<?= $escaper->escapeJs(__('Credit card')) ?>',
        savedCard: '<?= $escaper->escapeJs(__('Saved Card')) ?>',
        bankTransfer: '<?= $escaper->escapeJs(__('Bank Transfer')) ?>',
        paymentSuccess: '<?= $escaper->escapeJs(__('Payment completed successfully!')) ?>',
        orderConfirmed: '<?= $escaper->escapeJs(__('Your order has been confirmed.')) ?>',
        paymentFailed: '<?= $escaper->escapeJs(__('Payment failed')) ?>',
        orderRequiresPayment: '<?= $escaper->escapeJs(__('Your order has been created but requires payment.')) ?>'
    };
    
    var checkUrl = '<?= $escaper->escapeJs($checkPaymentStatusUrl) ?>';
    var orderId = <?= (int)$orderEntityId ?>;
    var pollCount = 0;
    var maxPolls = 60;
    var pollTimer = null;

    // Clear the full Simply.IN client-side session once the order reaches a
    // terminal state (completed / failed). Reuses SessionStorage.clearAll()
    // (loaded on this success page) so we never leave simplyin_token / user /
    // provider_info lingering until the tab is closed. Must only run on terminal
    // states - never during 3DS / polling / pending.
    function clearSimplyinSession() {
        try {
            if (window.SessionStorage && typeof window.SessionStorage.clearAll === 'function') {
                window.SessionStorage.clearAll();
                return;
            }
            // Fallback: drop every simplyin_ prefixed key directly.
            var keys = [];
            for (var i = 0; i < sessionStorage.length; i++) {
                var k = sessionStorage.key(i);
                if (k && k.indexOf('simplyin_') === 0) { keys.push(k); }
            }
            keys.forEach(function (k) { sessionStorage.removeItem(k); });
        } catch (e) { console.warn('[Simplyin] clearSimplyinSession error:', e); }
    }
    
    function loadInfo() {
        try {
            // Load provider info and update logos
            var pi = sessionStorage.getItem('simplyin_provider_info');
            if (pi) {
                var info = JSON.parse(pi);
                var logosEl = document.getElementById('sly-ps-logos');
                if (logosEl && info.logoUrl) {
                    logosEl.innerHTML = '<img src="' + info.logoUrl + '" alt="' + (info.name || 'PayU') + '">';
                }
            }
            
            // Load method name with card details
            var method = sessionStorage.getItem('simplyin_selected_method') || '';
            var last4 = sessionStorage.getItem('simplyin_card_last4') || '';
            var brand = sessionStorage.getItem('simplyin_card_brand') || '';
            var nameEl = document.getElementById('sly-ps-method-name');
            var logoEl = document.getElementById('sly-ps-method-logo');
            
            if (nameEl) {
                if (method === 'add_card' || method === 'card') {
                    var cardText = T.creditCard;
                    if (brand) cardText = brand.charAt(0).toUpperCase() + brand.slice(1);
                    if (last4) cardText += ' (**' + last4 + ')';
                    nameEl.textContent = cardText;
                } else if (method === 'blik') {
                    nameEl.textContent = 'BLIK';
                } else if (method === 'saved_card') {
                    nameEl.textContent = T.savedCard + (last4 ? ' (**' + last4 + ')' : '');
                } else if (method === 'bank_transfer') {
                    nameEl.textContent = T.bankTransfer;
                }
            }
        } catch(e) { console.warn('[Simplyin] loadInfo error:', e); }
    }
    
    function setStatus(type, main, sub) {
        var iconEl = document.getElementById('sly-ps-icon');
        var mainEl = document.getElementById('sly-ps-main');
        var subEl = document.getElementById('sly-ps-sub');
        var spinnerEl = document.getElementById('sly-ps-spinner');
        var checkEl = document.getElementById('sly-ps-check');
        
        if (mainEl) mainEl.textContent = main;
        if (subEl) { subEl.textContent = sub; subEl.className = 'sly-ps-sub ' + type; }
        
        if (type === 'success') {
            if (spinnerEl) spinnerEl.style.display = 'none';
            if (checkEl) checkEl.style.display = '';
            if (iconEl) iconEl.innerHTML = '<svg viewBox="0 0 24 24" width="28" height="28" fill="#22c55e"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>';
        } else if (type === 'failed') {
            if (spinnerEl) spinnerEl.style.display = 'none';
            if (iconEl) iconEl.innerHTML = '<svg viewBox="0 0 24 24" width="28" height="28" fill="#ef4444"><path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/></svg>';
        }
    }
    
    function poll() {
        pollCount++;
        if (pollCount > maxPolls) { stopPoll(); setStatus('success', T.paymentSuccess, T.orderConfirmed); clearSimplyinSession(); return; }
        
        var paymentId = sessionStorage.getItem('simplyin_payment_id') || '';
        var authToken = sessionStorage.getItem('simplyin_token') || '';
        console.log('[Simplyin] Polling payment status, attempt:', pollCount, 'paymentId:', paymentId, 'orderId:', orderId);
        
        if (!paymentId) {
            if (pollCount > 3) { stopPoll(); setStatus('success', T.paymentSuccess, T.orderConfirmed); clearSimplyinSession(); }
            return;
        }
        
        fetch(checkUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
            body: JSON.stringify({ paymentId: paymentId, authToken: authToken, orderId: orderId })
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            console.log('[Simplyin] Payment status response:', data);
            if (data.success) {
                var s = (data.status || data.paymentStatus || '').toLowerCase();
                if (s === 'completed' || s === 'confirmed' || s === 'paid' || s === 'success' || s === 'settled') {
                    stopPoll();
                    setStatus('success', T.paymentSuccess, T.orderConfirmed);
                    clearSimplyinSession();
                } else if (s === 'failed' || s === 'error' || s === 'cancelled' || s === 'rejected') {
                    stopPoll();
                    setStatus('failed', T.paymentFailed, data.message || T.orderRequiresPayment);
                    clearSimplyinSession();
                }
            }
        })
        .catch(function(e) { console.warn('[Simplyin] Poll error:', e); });
    }
    
    function startPoll() { if (!pollTimer) pollTimer = setInterval(poll, 2000); }
    function stopPoll() { if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } }
    
    loadInfo();
    startPoll();
})();
</script>
<?php $hyvaCsp->registerInlineScript(); ?>
</div>
