<?php
if (isset($_GET['debug']) && $_GET['debug'] === '1') {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
}

include 'core/autoload.php';
include 'core/app/model/StoreProductData.php';

function sf_normalize($value)
{
    $text = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
    $text = strtr($text, array(
        'Á' => 'a',
        'À' => 'a',
        'Ä' => 'a',
        'Â' => 'a',
        'Ã' => 'a',
        'Å' => 'a',
        'á' => 'a',
        'à' => 'a',
        'ä' => 'a',
        'â' => 'a',
        'ã' => 'a',
        'å' => 'a',
        'É' => 'e',
        'È' => 'e',
        'Ë' => 'e',
        'Ê' => 'e',
        'é' => 'e',
        'è' => 'e',
        'ë' => 'e',
        'ê' => 'e',
        'Í' => 'i',
        'Ì' => 'i',
        'Ï' => 'i',
        'Î' => 'i',
        'í' => 'i',
        'ì' => 'i',
        'ï' => 'i',
        'î' => 'i',
        'Ó' => 'o',
        'Ò' => 'o',
        'Ö' => 'o',
        'Ô' => 'o',
        'Õ' => 'o',
        'ó' => 'o',
        'ò' => 'o',
        'ö' => 'o',
        'ô' => 'o',
        'õ' => 'o',
        'Ú' => 'u',
        'Ù' => 'u',
        'Ü' => 'u',
        'Û' => 'u',
        'ú' => 'u',
        'ù' => 'u',
        'ü' => 'u',
        'û' => 'u',
        'Ñ' => 'n',
        'ñ' => 'n',
        'Ç' => 'c',
        'ç' => 'c',
    ));

    if (function_exists('mb_strtolower')) {
        $text = mb_strtolower($text, 'UTF-8');
    } else {
        $text = strtolower($text);
    }

    return trim(preg_replace('/\s+/u', ' ', $text));
}

$search = isset($_GET['q']) ? trim((string) $_GET['q']) : '';
$selectedBrand = isset($_GET['brand']) ? trim((string) $_GET['brand']) : '';

?>
<!doctype html>
<html lang="es">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta name="description" content="Catalogo de productos disponibles. Filtra por nombre, codigo o marca y solicita tu cotizacion.">
    <title>Mecanity Store | Insumos y Equipos Industriales</title>
    <link rel="stylesheet" href="assets/css/storefront.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" defer></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js" defer></script>
</head>

<body class="storefront">
    <nav class="sf-navbar">
        <div class="sf-wrap sf-navbar-inner">
            <a class="sf-brand-logo" href="tienda.php">
                <img src="logo_mecanity.png" alt="Mecanity Store" class="sf-brand-img">
                <span class="sf-brand-name">Mecanity <strong>Store</strong></span>
            </a>
            <ul class="sf-nav-links">
                <li><a href="tienda.php" class="sf-nav-active">Tienda</a></li>
                <li><a href="promociones.php">Promociones</a></li>
                <li><a href="novedades.php">Novedades</a></li>
                <li><a href="gaming.php">Gaming</a></li>
                <li><a href="contacto.php">Contacto</a></li>
            </ul>
            <span class="sf-brand-tagline">Insumos y Equipos Industriales</span>
        </div>
    </nav>
    <header class="sf-hero">
        <div class="sf-wrap">
            <h1>Catalogo de productos</h1>
            <p>Explora nuestro catalogo de productos. Filtra por nombre, codigo o marca y solicita tu cotizacion.</p>

            <form class="sf-search" id="sf-live-form" method="get" action="tienda.php">
                <input type="search" id="sf-live-search" name="q" placeholder="Buscar producto por nombre o codigo" autocomplete="off" value="<?php echo htmlspecialchars($search, ENT_QUOTES, 'UTF-8'); ?>">
                <select id="sf-brand-filter" name="brand" aria-label="Filtrar por marca">
                    <option value="">Todas las marcas</option>
                    <?php if ($selectedBrand !== ''): ?>
                        <option value="<?php echo htmlspecialchars($selectedBrand, ENT_QUOTES, 'UTF-8'); ?>" selected><?php echo htmlspecialchars($selectedBrand, ENT_QUOTES, 'UTF-8'); ?></option>
                    <?php endif; ?>
                </select>
                <button class="sf-btn sf-btn-primary" type="submit">Buscar</button>
            </form>
            <p class="sf-code" id="sf-result-count" style="margin-top: 8px;"></p>
        </div>
    </header>

    <main class="sf-wrap">
        <section class="sf-grid" id="sf-grid">
            <div class="sf-skeleton-loader" id="sf-initial-loader" aria-label="Cargando productos...">
                <?php for ($i = 0; $i < 12; $i++): ?>
                    <div class="sf-skeleton-card"></div>
                <?php endfor; ?>
            </div>
        </section>
        <div class="sf-pagination" id="sf-pagination" style="display:none">
            <button type="button" class="sf-btn sf-btn-primary" id="sf-load-more">Cargar mas</button>
        </div>

    </main>

    <script>
        (function() {
            var input = document.getElementById('sf-live-search');
            var form = document.getElementById('sf-live-form');
            var brandSelect = document.getElementById('sf-brand-filter');
            var count = document.getElementById('sf-result-count');
            var grid = document.getElementById('sf-grid');
            var loadMoreBtn = document.getElementById('sf-load-more');
            var paginationWrap = document.getElementById('sf-pagination');
            var initialLoader = document.getElementById('sf-initial-loader');
            var cards = [];
            var currentAbortController = null;
            var debounceTimer = null;
            var page = 1;
            var perPage = 12;

            function normalize(value) {
                var text = (value || '').toLowerCase();
                text = text.replace(/[áàäâ]/g, 'a');
                text = text.replace(/[éèëê]/g, 'e');
                text = text.replace(/[íìïî]/g, 'i');
                text = text.replace(/[óòöô]/g, 'o');
                text = text.replace(/[úùüû]/g, 'u');
                text = text.replace(/ñ/g, 'n');
                return text;
            }

            function updateCount(visible, total) {
                if (!count) {
                    return;
                }
                count.textContent = 'Mostrando ' + visible + ' de ' + total + ' productos';
            }

            function updateLoadMore(show) {
                if (!loadMoreBtn) {
                    return;
                }
                loadMoreBtn.style.display = show ? '' : 'none';
                if (paginationWrap) {
                    paginationWrap.style.display = show ? '' : 'none';
                }
            }

            function applyFilter() {
                if (!input) {
                    return;
                }

                var query = normalize(input.value);
                var visible = 0;

                cards.forEach(function(card) {
                    var haystack = normalize(card.getAttribute('data-search') || '');
                    var match = query === '' || haystack.indexOf(query) !== -1;
                    card.style.display = match ? '' : 'none';
                    if (match) {
                        visible++;
                    }
                });

                updateCount(visible, cards.length);
            }

            function formatPrice(raw) {
                var adjusted = parseFloat(raw) || 0;
                return 'Bs. ' + adjusted.toLocaleString('es-BO', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
            }

            function buildWhatsAppLink(p) {
                var text = 'Hola, me interesa este producto: ' + (p.name || '') +
                    ' (Codigo: ' + (p.code || '') + ') - Precio: ' + formatPrice(p.price_final || 0);
                return 'https://wa.me/59175060017?text=' + encodeURIComponent(text);
            }

            function escapeHtml(text) {
                return String(text || '')
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .replace(/"/g, '&quot;')
                    .replace(/'/g, '&#039;');
            }

            function syncBrandOptions(brands) {
                if (!brandSelect || !Array.isArray(brands) || brands.length === 0) {
                    return;
                }

                var selected = brandSelect.value || '';
                var html = '<option value="">Todas las marcas</option>';
                brands.forEach(function(brand) {
                    var isSel = selected === brand ? ' selected' : '';
                    html += '<option value="' + escapeHtml(brand) + '"' + isSel + '>' + escapeHtml(brand) + '</option>';
                });
                brandSelect.innerHTML = html;
            }

            function renderCards(items, append) {
                if (!grid) {
                    return;
                }

                var html = '';
                items.forEach(function(p) {
                    var searchKey = (p.name || '') + ' ' + (p.code || '') + ' ' + (p.brand || '');
                    html += '<article class="sf-card js-product-card" data-search="' + escapeHtml(searchKey) + '">';
                    html += '  <div class="sf-thumb">';
                    html += '    <img loading="lazy" src="' + escapeHtml(p.image) + '" alt="' + escapeHtml(p.name) + '">';
                    html += '  </div>';
                    html += '  <div>';
                    html += '    <h3 class="sf-title">' + escapeHtml(p.name) + '</h3>';
                    html += '    <p class="sf-brand">' + escapeHtml(p.brand) + '</p>';
                    html += '    <p class="sf-code">Codigo: ' + escapeHtml(p.code) + '</p>';
                    html += '  </div>';
                    html += '  <p class="sf-price">' + escapeHtml(formatPrice(p.price_final || 0)) + '</p>';
                    html += '  <p class="sf-stock">Stock La Paz: ' + parseInt(p.stock_lapaz || 0, 10) + '</p>';
                    html += '  <p class="sf-stock">Stock interior: ' + parseInt(p.stock_interior || 0, 10) + '</p>';
                    html += '  <div class="sf-actions"';
                    html += '    data-id="' + parseInt(p.id, 10) + '"';
                    html += '    data-name="' + escapeHtml(p.name) + '"';
                    html += '    data-code="' + escapeHtml(p.code) + '"';
                    html += '    data-price="' + escapeHtml(formatPrice(p.price_final || 0)) + '">';
                    html += '    <div class="sf-actions-row">';
                    html += '      <a class="sf-btn sf-btn-secondary" href="tienda_producto.php?id=' + parseInt(p.id, 10) + '">Ver detalle</a>';
                    html += '      <a class="sf-btn sf-btn-whatsapp" target="_blank" rel="noopener" href="' + escapeHtml(buildWhatsAppLink(p)) + '">WhatsApp</a>';
                    html += '    </div>';
                    html += '    <button type="button" class="sf-btn sf-btn-quote js-cotizar">Solicitar cotizacion</button>';
                    html += '  </div>';
                    html += '</article>';
                });

                if (!append && items.length === 0) {
                    html = '<div class="sf-empty"><h2>Sin coincidencias</h2><p>No se encontraron productos para esta busqueda.</p></div>';
                }

                if (append) {
                    grid.insertAdjacentHTML('beforeend', html);
                } else {
                    grid.innerHTML = html;
                }
                if (initialLoader) {
                    initialLoader.style.display = 'none';
                }
                cards = Array.prototype.slice.call(document.querySelectorAll('.js-product-card'));
            }

            function fetchAndRender(resetPage) {
                if (!input) {
                    return;
                }

                var rawQuery = input.value || '';
                var brand = brandSelect ? (brandSelect.value || '') : '';
                var query = rawQuery.length >= 3 ? rawQuery : '';

                // Si tiene menos de 3 caracteres, usar filtro local
                if (rawQuery.length > 0 && rawQuery.length < 3 && brand === '') {
                    applyFilter();
                    updateLoadMore(false);
                    return;
                }

                if (resetPage) {
                    page = 1;
                }

                // Cancelar cualquier fetch en curso antes de lanzar uno nuevo
                if (currentAbortController) {
                    currentAbortController.abort();
                }
                currentAbortController = typeof AbortController !== 'undefined' ? new AbortController() : null;
                var fetchOptions = {
                    headers: {
                        'Accept': 'application/json'
                    }
                };
                if (currentAbortController) {
                    fetchOptions.signal = currentAbortController.signal;
                }

                var url = 'tienda_search.php?q=' + encodeURIComponent(query) +
                    '&brand=' + encodeURIComponent(brand) +
                    '&page=' + encodeURIComponent(page) +
                    '&per_page=' + encodeURIComponent(perPage);

                fetch(url, fetchOptions)
                    .then(function(response) {
                        return response.json();
                    })
                    .then(function(payload) {
                        if (!payload || !Array.isArray(payload.items)) {
                            payload = {
                                items: [],
                                total: 0,
                                has_more: false,
                                brands: []
                            };
                        }
                        syncBrandOptions(payload.brands || []);
                        renderCards(payload.items, !resetPage);
                        updateCount(cards.length, parseInt(payload.total || 0, 10));
                        updateLoadMore(!!payload.has_more);
                    })
                    .catch(function(err) {
                        if (err && err.name === 'AbortError') {
                            return; // fetch cancelado intencionalmente, ignorar
                        }
                        updateCount(0, 0);
                        updateLoadMore(false);
                    });
            }

            if (form) {
                form.addEventListener('submit', function(evt) {
                    evt.preventDefault();
                });
            }

            if (input) {
                input.addEventListener('input', function() {
                    if (debounceTimer) {
                        clearTimeout(debounceTimer);
                    }
                    debounceTimer = setTimeout(function() {
                        fetchAndRender(true);
                    }, 180);
                });
            }

            if (brandSelect) {
                brandSelect.addEventListener('change', function() {
                    fetchAndRender(true);
                });
            }

            if (loadMoreBtn) {
                loadMoreBtn.addEventListener('click', function() {
                    page += 1;
                    fetchAndRender(false);
                });
            }

            fetchAndRender(true);

            // --- Modal cotizacion ---
            var modal = document.getElementById('sf-modal-cotizar');
            var modalForm = document.getElementById('sf-modal-form');
            var modalMsg = document.getElementById('sf-modal-msg');
            var selectedPaymentMethod = 'contado';
            var selectedCuotasInfo = '';
            var currentProductId = '';
            var currentProductName = '';
            var currentProductCode = '';
            var currentProductPrice = '';
            var currentProductImg = '';

            function parsePriceNumber(priceText) {
                var num = (priceText || '').replace(/[^0-9.,]/g, '').replace(/\./g, '').replace(/,/g, '.');
                var parts = num.split('.');
                if (parts.length > 2) {
                    var last = parts.pop();
                    num = parts.join('') + '.' + last;
                }
                return parseFloat(num) || 0;
            }

            function openModal(id, name, code, price, img) {
                if (!modal) return;
                currentProductId = id || '';
                currentProductName = name || '';
                currentProductCode = code || '';
                currentProductPrice = price || '';
                currentProductImg = img || '';
                document.getElementById('sf-lead-producto-id').value = id || '';
                document.getElementById('sf-lead-producto-nombre').value = name || '';
                document.getElementById('sf-lead-producto-codigo').value = code || '';
                document.getElementById('sf-lead-precio').value = price || '';
                if (modalMsg) { modalMsg.textContent = ''; modalMsg.className = 'sf-modal-msg'; }
                var resumen = document.getElementById('sf-modal-resumen');
                if (resumen) {
                    resumen.style.display = 'flex';
                    resumen.innerHTML = '<img class="sf-resumen-img" src="' + escapeHtml(img || 'assets/images/error/01.png') + '" alt="">' +
                        '<div class="sf-resumen-info"><p class="sf-resumen-name">' + escapeHtml(name || '') + '</p>' +
                        '<p class="sf-resumen-price">' + escapeHtml(price || '') + '</p></div>';
                }
                selectedPaymentMethod = 'contado';
                selectedCuotasInfo = '';
                document.getElementById('sf-lead-metodo-pago').value = 'contado';
                document.getElementById('sf-lead-cuotas-info').value = '';
                updatePaymentHighlight();
                simulatePayment();
                if (modalForm) modalForm.reset();
                document.getElementById('sf-lead-producto-id').value = id || '';
                document.getElementById('sf-lead-producto-nombre').value = name || '';
                document.getElementById('sf-lead-producto-codigo').value = code || '';
                document.getElementById('sf-lead-precio').value = price || '';
                modal.classList.add('is-open');
                document.body.style.overflow = 'hidden';
            }

            function closeModal() {
                if (!modal) return;
                modal.classList.remove('is-open');
                document.body.style.overflow = '';
            }

            function updatePaymentHighlight() {
                document.querySelectorAll('.sf-payment-btn').forEach(function(b) {
                    b.classList.toggle('sf-payment-active', b.getAttribute('data-method') === selectedPaymentMethod);
                });
            }

            function simulatePayment() {
                var container = document.getElementById('sf-payment-simulation');
                if (!container) return;
                var total = parsePriceNumber(currentProductPrice);
                if (selectedPaymentMethod === 'contado') {
                    container.innerHTML = '<div class="sf-payment-sim"><div class="sf-payment-sim-title">Pago al contado</div>' +
                        '<p style="margin:0;color:var(--sf-accent);font-weight:700;">Total: ' + escapeHtml(currentProductPrice) + '</p>' +
                        '<p style="margin:4px 0 0;font-size:0.82rem;color:var(--sf-muted);">Su reserva sera confirmada al recibir el pago.</p></div>';
                } else if (selectedPaymentMethod === 'credito') {
                    container.innerHTML = '<div class="sf-payment-sim"><div class="sf-payment-sim-title">Plan de credito flexible</div>' +
                        '<div style="margin-top:8px;">' +
                        '<button type="button" class="sf-cuota-btn" data-cuotas="6">6 cuotas de Bs ' + (total / 6).toFixed(2) + '</button>' +
                        '<button type="button" class="sf-cuota-btn" data-cuotas="9">9 cuotas de Bs ' + (total / 9).toFixed(2) + '</button>' +
                        '<button type="button" class="sf-cuota-btn" data-cuotas="12">12 cuotas de Bs ' + (total / 12).toFixed(2) + '</button>' +
                        '</div><div id="sf-cuota-confirm" class="sf-cuota-confirm"></div></div>';
                    document.querySelectorAll('.sf-cuota-btn').forEach(function(btn) {
                        btn.addEventListener('click', function() {
                            var cuotas = btn.getAttribute('data-cuotas');
                            var monto = (total / cuotas).toFixed(2);
                            selectedCuotasInfo = cuotas + ' cuotas de Bs ' + monto;
                            document.getElementById('sf-lead-cuotas-info').value = selectedCuotasInfo;
                            document.querySelectorAll('.sf-cuota-btn').forEach(function(b) { b.classList.remove('sf-cuota-active'); });
                            btn.classList.add('sf-cuota-active');
                            document.getElementById('sf-cuota-confirm').textContent = 'Credito seleccionado: ' + selectedCuotasInfo;
                        });
                    });
                } else if (selectedPaymentMethod === 'qr') {
                    container.innerHTML = '<div class="sf-qr-box"><div class="sf-qr-icon">&#9400;</div>' +
                        '<p style="font-weight:600;">Pago QR Simple</p>' +
                        '<p style="font-size:0.85rem;color:var(--sf-muted);">Escanea el codigo QR para pagar</p>' +
                        '<p style="font-weight:700;color:var(--sf-accent);margin-top:6px;">Monto: ' + escapeHtml(currentProductPrice) + '</p></div>';
                }
            }

            document.querySelectorAll('.sf-payment-btn').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    selectedPaymentMethod = btn.getAttribute('data-method');
                    selectedCuotasInfo = '';
                    document.getElementById('sf-lead-metodo-pago').value = selectedPaymentMethod;
                    document.getElementById('sf-lead-cuotas-info').value = '';
                    updatePaymentHighlight();
                    simulatePayment();
                });
            });

            document.addEventListener('click', function(evt) {
                var btn = evt.target.closest('.js-cotizar');
                if (btn) {
                    var actionsEl = btn.closest('[data-id]');
                    var parentCard = btn.closest('.sf-card');
                    var imgEl = parentCard ? parentCard.querySelector('.sf-thumb img') : null;
                    openModal(
                        actionsEl ? actionsEl.getAttribute('data-id') : '',
                        actionsEl ? actionsEl.getAttribute('data-name') : '',
                        actionsEl ? actionsEl.getAttribute('data-code') : '',
                        actionsEl ? actionsEl.getAttribute('data-price') : '',
                        imgEl ? imgEl.getAttribute('src') : ''
                    );
                    return;
                }
                if (evt.target === modal) closeModal();
            });

            var closeBtn = document.getElementById('sf-modal-close');
            if (closeBtn) closeBtn.addEventListener('click', closeModal);

            if (modalForm) {
                modalForm.addEventListener('submit', function(evt) {
                    evt.preventDefault();
                    var nombre = document.getElementById('sf-lead-nombre').value.trim();
                    var telefono = document.getElementById('sf-lead-tel').value.trim();
                    if (!nombre || !telefono) { alert('Por favor completa nombre y telefono.'); return; }

                    var submitBtn = modalForm.querySelector('[type=submit]');
                    if (submitBtn) submitBtn.disabled = true;

                    var metodoTexto = '';
                    if (selectedPaymentMethod === 'contado') metodoTexto = 'CONTADO';
                    else if (selectedPaymentMethod === 'credito') metodoTexto = selectedCuotasInfo ? 'CREDITO - ' + selectedCuotasInfo : 'CREDITO (plan por definir)';
                    else metodoTexto = 'PAGO QR - Simple';

                    var fecha = new Date().toLocaleString('es-BO');
                    var nroPedido = 'Mecanity-' + Math.floor(Math.random() * 10000) + '-' + Date.now().toString().slice(-6);

                    var pdfElement = document.createElement('div');
                    pdfElement.style.position = 'absolute';
                    pdfElement.style.top = '-9999px';
                    pdfElement.style.left = '-9999px';
                    pdfElement.style.width = '800px';
                    pdfElement.style.padding = '28px';
                    pdfElement.style.fontFamily = "'Segoe UI', system-ui, sans-serif";
                    pdfElement.style.backgroundColor = '#ffffff';
                    pdfElement.innerHTML =
                        '<div style="text-align:center;border-bottom:3px solid #178a57;padding-bottom:16px;margin-bottom:24px;">' +
                        '<h1 style="color:#178a57;margin:0;">Mecanity STORE</h1>' +
                        '<p style="color:#334155;">Reserva confirmada - Comprobante oficial</p>' +
                        '<p style="font-size:12px;">Insumos y Equipos Industriales | La Paz - Bolivia</p></div>' +
                        '<div style="display:flex;justify-content:space-between;margin-bottom:20px;">' +
                        '<div><strong>COMPROBANTE DE RESERVA</strong><br>Fecha: ' + fecha + '</div>' +
                        '<div><strong>N Pedido:</strong> ' + nroPedido + '</div></div>' +
                        '<div style="background:#e8f5ee;padding:14px;border-radius:12px;margin-bottom:20px;">' +
                        '<h4 style="margin:0 0 6px;">Datos del cliente</h4>' +
                        '<p style="margin:0;"><strong>Nombre:</strong> ' + escapeHtml(nombre) + '<br>' +
                        '<strong>WhatsApp:</strong> ' + escapeHtml(telefono) + '<br>' +
                        '<strong>Email:</strong> ' + escapeHtml(document.getElementById('sf-lead-email').value.trim() || '—') + '<br>' +
                        '<strong>Empresa:</strong> ' + escapeHtml(document.getElementById('sf-lead-empresa').value.trim() || '—') + '</p></div>' +
                        '<h3>Producto reservado</h3>' +
                        '<table style="width:100%;border-collapse:collapse;margin:16px 0;">' +
                        '<tr style="background:#f1f5f1;"><th style="padding:10px;text-align:left;">Producto</th><th>Codigo</th><th>Precio</th></tr>' +
                        '<tr><td style="padding:8px;">' + escapeHtml(currentProductName) + '</td><td>' + escapeHtml(currentProductCode) + '</td><td>' + escapeHtml(currentProductPrice) + '</td></tr></table>' +
                        '<div style="text-align:right;border-top:1px solid #dde4df;padding-top:16px;">' +
                        '<h3 style="color:#178a57;">Total: ' + escapeHtml(currentProductPrice) + '</h3>' +
                        '<p><strong>Metodo de pago:</strong> ' + metodoTexto + '</p>' +
                        '<p><strong>Estado:</strong> RESERVA PENDIENTE - Confirmar pago</p></div>' +
                        '<div style="margin-top:32px;text-align:center;font-size:10px;color:#5c6b62;">Mecanity Store | Insumos y Equipos Industriales</div>';

                    document.body.appendChild(pdfElement);

                    var data = new FormData(modalForm);
                    data.set('metodo_pago', selectedPaymentMethod);
                    data.set('cuotas_info', selectedCuotasInfo);

                    fetch('tienda_lead.php', { method: 'POST', body: data })
                        .then(function(r) { return r.json(); })
                        .then(function(res) {
                            if (submitBtn) submitBtn.disabled = false;
                            if (modalMsg) {
                                modalMsg.textContent = res.message || (res.success ? 'Enviado.' : 'Error.');
                                modalMsg.className = 'sf-modal-msg ' + (res.success ? 'sf-modal-ok' : 'sf-modal-err');
                            }
                        })
                        .catch(function() {
                            if (submitBtn) submitBtn.disabled = false;
                        });

                    var whatsappMsg = 'RESERVA Mecanity STORE%0A%0A' +
                        'Cliente: ' + encodeURIComponent(nombre) + '%0A' +
                        'Telefono: ' + encodeURIComponent(telefono) + '%0A' +
                        'Producto: ' + encodeURIComponent(currentProductName) + ' (' + encodeURIComponent(currentProductCode) + ')%0A' +
                        'Total: ' + encodeURIComponent(currentProductPrice) + '%0A' +
                        'Metodo: ' + encodeURIComponent(metodoTexto) + '%0A' +
                        'N Pedido: ' + encodeURIComponent(nroPedido) + '%0A%0A' +
                        'Adjunto el comprobante de reserva. Por favor confirmar disponibilidad.';

                    try {
                        html2canvas(pdfElement, { scale: 2, backgroundColor: '#ffffff', logging: false, useCORS: true }).then(function(canvas) {
                            var jsPDF = window.jspdf.jsPDF;
                            var imgData = canvas.toDataURL('image/png');
                            var pdf = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' });
                            var imgWidth = 210;
                            var imgHeight = (canvas.height * imgWidth) / canvas.width;
                            pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
                            pdf.save('Reserva_Mecanity_' + nroPedido + '.pdf');
                            document.body.removeChild(pdfElement);
                            window.open('https://wa.me/59175060017?text=' + whatsappMsg, '_blank');
                            setTimeout(closeModal, 1500);
                        }).catch(function() {
                            document.body.removeChild(pdfElement);
                            window.open('https://wa.me/59175060017?text=' + whatsappMsg, '_blank');
                            setTimeout(closeModal, 1500);
                        });
                    } catch(e) {
                        document.body.removeChild(pdfElement);
                        window.open('https://wa.me/59175060017?text=' + whatsappMsg, '_blank');
                        setTimeout(closeModal, 1500);
                    }
                });
            }
        })();
    </script>

    <!-- Modal de cotizacion -->
    <div id="sf-modal-cotizar" class="sf-modal" role="dialog" aria-modal="true" aria-labelledby="sf-modal-titulo">
        <div class="sf-modal-box" style="max-height:92vh;">
            <div class="sf-modal-header">
                <h2 id="sf-modal-titulo" class="sf-modal-title">Reservar Producto</h2>
                <button type="button" id="sf-modal-close" class="sf-modal-close" aria-label="Cerrar">&times;</button>
            </div>
            <div id="sf-modal-resumen" class="sf-resumen-producto" style="display:none;"></div>
            <div id="sf-modal-msg" class="sf-modal-msg"></div>
            <form id="sf-modal-form" autocomplete="off">
                <input type="hidden" name="producto_id" id="sf-lead-producto-id">
                <input type="hidden" name="producto_nombre" id="sf-lead-producto-nombre">
                <input type="hidden" name="producto_codigo" id="sf-lead-producto-codigo">
                <input type="hidden" name="precio_mostrado" id="sf-lead-precio">
                <input type="hidden" name="metodo_pago" id="sf-lead-metodo-pago" value="contado">
                <input type="hidden" name="cuotas_info" id="sf-lead-cuotas-info" value="">

                <div class="sf-field">
                    <label for="sf-lead-nombre">Nombre <span class="sf-req">*</span></label>
                    <input type="text" id="sf-lead-nombre" name="nombre" required autocomplete="name">
                </div>
                <div class="sf-field">
                    <label for="sf-lead-empresa">Empresa</label>
                    <input type="text" id="sf-lead-empresa" name="empresa" autocomplete="organization">
                </div>
                <div class="sf-field">
                    <label for="sf-lead-tel">Telefono / WhatsApp <span class="sf-req">*</span></label>
                    <input type="tel" id="sf-lead-tel" name="telefono" required autocomplete="tel">
                </div>
                <div class="sf-field">
                    <label for="sf-lead-email">Email</label>
                    <input type="email" id="sf-lead-email" name="email" autocomplete="email">
                </div>

                <label style="font-weight:600;font-size:0.88rem;margin-bottom:4px;display:block;">Metodo de pago</label>
                <div class="sf-payment-methods">
                    <button type="button" class="sf-payment-btn sf-payment-active" data-method="contado">Contado</button>
                    <button type="button" class="sf-payment-btn" data-method="credito">Credito / Cuotas</button>
                    <button type="button" class="sf-payment-btn" data-method="qr">QR Simple</button>
                </div>
                <div id="sf-payment-simulation"></div>

                <div class="sf-field">
                    <label for="sf-lead-mensaje">Comentarios adicionales</label>
                    <textarea id="sf-lead-mensaje" name="mensaje" rows="2" placeholder="Ej: solicitar factura, horario de contacto..."></textarea>
                </div>
                <button type="submit" class="sf-btn sf-btn-whatsapp-send" style="width:100%;margin-top:4px;">Enviar reserva por WhatsApp</button>
            </form>
        </div>
    </div>
</body>

</html>