<?php
/**
 * Hyva-compatible Product Modal Template
 * Uses Alpine.js instead of jQuery
 */

use Magento\Framework\Escaper;

/** @var $block \TbiBank\FusionPay\Block\Frontend\ProductModal */
/** @var Escaper $escaper */

if (!$block->isEnabled()) {
    return;
}

$productId = $block->getRequest()->getParam('id', false);
$loadingImg = $block->getLoadingImg();
$allowedOrigin = $block->getAllowedOrigin();
?>

<div x-data="{
        isOpen: false,
        isLoading: true,
        iframeSrc: '',
        allowedOrigin: '<?= $escaper->escapeJs($allowedOrigin) ?>',
        resizeHelper: window.FusionPayTbiRoIframeResize,
        
        init() {
            window.addEventListener('message', (event) => this.handleMessage(event));
            this.resizeHelper.bindHostSurfaceSync(this.getIframe(), this.allowedOrigin);
            // CKT-4091: on a short viewport the popup can overflow the
            // screen with no way to scroll it into view, so Esc needs to
            // close it too - an outside click shouldn't be the only way out.
            window.addEventListener('keydown', (event) => {
                if (event.key === 'Escape' && this.isOpen) {
                    this.closeModal();
                }
            });
        },

        getFrameContainer() {
            return document.getElementById('iframe_container');
        },

        getIframe() {
            return document.getElementById('tbi_popup_iframe');
        },

        resetIframe() {
            this.resizeHelper.resetReadyState(this.getFrameContainer(), this.getIframe());
        },
        
        async openModal() {
            const form = document.getElementById('product_addtocart_form');
            if (!this.validateForm(form)) {
                alert(document.getElementById('tbi_popup_container').getAttribute('data-required'));
                return;
            }
            
            const formData = new FormData(form);
            
            try {
                this.isLoading = true;
                this.isOpen = true;
                document.body.style.overflow = 'hidden';
                document.getElementById('tbi_popup_container').classList.add('show');
                this.resetIframe();
                
                const response = await fetch('/fusionpay/api/RegisterProductApplication', {
                    method: 'POST',
                    body: new URLSearchParams(formData),
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });
                
                const result = await response.json();
                
                if (result.success !== false && result.url) {
                    this.iframeSrc = this.resizeHelper.appendHostSurface(result.url);
                    // Fallback timeout to hide loading if iframe doesn't load properly
                    setTimeout(() => {
                        if (this.isLoading) {
                            this.isLoading = false;
                        }
                    }, 5000);
                } else {
                    alert(document.getElementById('tbi_popup_container').getAttribute('data-price'));
                    this.closeModal();
                }
            } catch (error) {
                console.error('Error:', error);
                this.closeModal();
            }
        },
        
        closeModal() {
            this.isOpen = false;
            this.isLoading = true;
            this.iframeSrc = '';
            document.body.style.overflow = 'auto';
            document.getElementById('tbi_popup_container').classList.remove('show');
        },
        
        onIframeLoad() {
            this.isLoading = false;
        },
        
        validateForm(form) {
            if (!form) return false;
            const requiredFields = form.querySelectorAll('[required]');
            for (let field of requiredFields) {
                if (!field.value) return false;
            }
            const superAttribute = form.querySelectorAll('[name^=\'super_attribute\']');
            if (superAttribute.length > 0) {
                for (let attr of superAttribute) {
                    if (!attr.value) return false;
                }
            }
            return true;
        },
        
        async handleMessage(event) {
            if (event.origin !== this.allowedOrigin) return;
            try {
                const data = this.resizeHelper.parseMessage(event.data);

                if (this.resizeHelper.handleMessage(data, this.getFrameContainer(), this.getIframe())) {
                    return;
                }

                if (data.scheme_id) {
                    await this.addToCart(data);
                } else if (data.command === 'redirect' && data.url) {
                    window.location.href = data.url;
                } else if (data.command === 'close' || data.command === 'close_calculator') {
                    this.closeModal();
                }
            } catch (error) {
                console.error('Invalid JSON:', error);
            }
        },
        
        async addToCart(data) {
            const form = document.getElementById('product_addtocart_form');
            const formData = new FormData(form);
            const formDataJson = {};
            for (let [key, value] of formData.entries()) {
                formDataJson[key] = value;
            }
            formDataJson.scheme_id = data.scheme_id;
            formDataJson.downpayment = data.downpayment ?? 0;
            
            try {
                const response = await fetch('/fusionpay/api/addToCart', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify(formDataJson)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    if (window.dispatchEvent) {
                        window.dispatchEvent(new CustomEvent('reload-customer-section-data'));
                    }
                    window.dispatchEvent(new CustomEvent('private-content-loaded'));
                    this.closeModal();
                    window.dispatchEvent(new CustomEvent('show-messages'));
                } else {
                    console.error('Error adding to cart:', result.error);
                }
            } catch (error) {
                console.error('Request failed:', error);
            }
        }
     }"
     @tbi-open-modal.window="openModal()"
     x-show="isOpen"
     x-cloak
     @click.self="closeModal()"
     id="tbi_popup_container"
     data-price="<?= $escaper->escapeHtmlAttr(__('Price is below the TBI limit.')) ?>"
     data-required="<?= $escaper->escapeHtmlAttr(__('Please select all required options.')) ?>"
     data-origin="<?= $escaper->escapeHtmlAttr($allowedOrigin) ?>">
    
    <div id="iframe_container" @click.stop>
        <iframe 
            id="tbi_popup_iframe"
            :src="iframeSrc"
            @load="onIframeLoad()"
            scrolling="auto"
            frameborder="0"
            width="200"
            height="200">
        </iframe>
        
        <div id="tbi_loading" x-show="isLoading">
            <img src="<?= $escaper->escapeUrl($loadingImg) ?>" alt="tbi bank loading" width="128" height="128">
            <div id="tbi_loading_text"><?= $escaper->escapeHtml(__('please wait')) ?></div>
        </div>
    </div>
</div>

