<?php
if (isset($_GET['debug']) && $_GET['debug'] === '1') {
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
}
?>
<!doctype html>
<html lang="es">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta name="description" content="Ofertas y promociones especiales en articulos e insumos tecnologicos. Mecanity Store.">
    <title>Promociones | Mecanity Store</title>
    <link rel="stylesheet" href="assets/css/storefront.css">
    <style>
        .sf-badge-desc {
            display: inline-block;
            background: #e53935;
            color: #fff;
            font-size: 0.72rem;
            font-weight: 700;
            padding: 2px 8px;
            border-radius: 12px;
            margin-bottom: 4px;
            letter-spacing: 0.03em;
        }
        .sf-price-original {
            font-size: 0.82rem;
            color: #999;
            text-decoration: line-through;
            margin-bottom: 0;
        }
        .sf-price-promo {
            font-size: 1.15rem;
            font-weight: 700;
            color: #e53935;
            margin-top: 0;
        }
        .sf-empty-promos {
            grid-column: 1 / -1;
            text-align: center;
            padding: 48px 16px;
            color: #888;
        }
        .sf-empty-promos h2 { font-size: 1.2rem; margin-bottom: 8px; }
    </style>
</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">Tienda</a></li>
                <li><a href="promociones.php" class="sf-nav-active">Promociones</a></li>
                <li><a href="novedades.php">Novedades</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>Promociones</h1>
            <p>Precios especiales en productos seleccionados. Valido mientras dure el stock.</p>
            <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 promociones...">
                <?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 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 currentAbortController = null;
            var page        = 1;
            var perPage     = 12;
            var totalLoaded = 0;

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

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

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

            function buildWhatsAppLink(p) {
                var text = 'Hola, me interesa este producto en promocion: ' + (p.name || '') +
                    ' (Codigo: ' + (p.code || '') + ') - Precio promo: ' + formatPrice(p.precio_promo || 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 renderCards(items, append) {
                if (!grid) return;
                var html = '';

                if (!append && items.length === 0) {
                    html = '<div class="sf-empty-promos">' +
                           '<h2>Sin promociones activas</h2>' +
                           '<p>En este momento no hay productos en promocion. Vuelve pronto.</p>' +
                           '</div>';
                    grid.innerHTML = html;
                    if (initialLoader) initialLoader.style.display = 'none';
                    return;
                }

                items.forEach(function (p) {
                    var searchKey = (p.name || '') + ' ' + (p.code || '') + ' ' + (p.brand || '');
                    var priceFinal = parseFloat(p.price_final || 0);
                    var precioPromo = parseFloat(p.precio_promo || 0);
                    var descuento = parseFloat(p.descuento || 0);
                    var priceDisplay = precioPromo > 0 ? precioPromo : priceFinal;

                    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>';
                    if (descuento > 0) {
                        html += '  <span class="sf-badge-desc">-' + descuento.toFixed(0) + '% OFF</span>';
                        html += '  <p class="sf-price-original">' + escapeHtml(formatPrice(priceFinal)) + '</p>';
                        html += '  <p class="sf-price-promo">' + escapeHtml(formatPrice(precioPromo)) + '</p>';
                    } else {
                        html += '  <p class="sf-price">' + escapeHtml(formatPrice(priceFinal)) + '</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(priceDisplay)) + '">';
                    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) {
                    grid.insertAdjacentHTML('beforeend', html);
                } else {
                    grid.innerHTML = html;
                }

                if (initialLoader) initialLoader.style.display = 'none';
            }

            function fetchAndRender(resetPage) {
                if (resetPage) page = 1;

                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 = 'promociones_search.php?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 };
                        }
                        if (resetPage) totalLoaded = 0;
                        totalLoaded += payload.items.length;
                        renderCards(payload.items, !resetPage);
                        updateCount(totalLoaded, parseInt(payload.total || 0, 10));
                        updateLoadMore(!!payload.has_more);
                    })
                    .catch(function (err) {
                        if (err && err.name === 'AbortError') return;
                        if (initialLoader) initialLoader.style.display = 'none';
                        updateCount(0, 0);
                        updateLoadMore(false);
                    });
            }

            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');

            function openModal(id, name, code, price) {
                if (!modal) return;
                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 || '';
                document.getElementById('sf-modal-producto-label').textContent = name || '';
                if (modalMsg) { modalMsg.textContent = ''; modalMsg.className = 'sf-modal-msg'; }
                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 = '';
            }

            document.addEventListener('click', function (evt) {
                var btn = evt.target.closest('.js-cotizar');
                if (btn) {
                    var actionsEl = btn.closest('[data-id]');
                    if (actionsEl) {
                        openModal(
                            actionsEl.getAttribute('data-id'),
                            actionsEl.getAttribute('data-name'),
                            actionsEl.getAttribute('data-code'),
                            actionsEl.getAttribute('data-price')
                        );
                    }
                    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 submitBtn = modalForm.querySelector('[type=submit]');
                    if (submitBtn) submitBtn.disabled = true;

                    fetch('tienda_lead.php', { method: 'POST', body: new FormData(modalForm) })
                        .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');
                            }
                            if (res.success && modalForm) { modalForm.reset(); setTimeout(closeModal, 2200); }
                        })
                        .catch(function () {
                            if (submitBtn) submitBtn.disabled = false;
                            if (modalMsg) {
                                modalMsg.textContent = 'Error de conexion. Intenta nuevamente.';
                                modalMsg.className   = 'sf-modal-msg sf-modal-err';
                            }
                        });
                });
            }
        })();
    </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">
            <div class="sf-modal-header">
                <h2 id="sf-modal-titulo" class="sf-modal-title">Solicitar Cotizacion</h2>
                <button type="button" id="sf-modal-close" class="sf-modal-close" aria-label="Cerrar">&times;</button>
            </div>
            <p class="sf-modal-producto" id="sf-modal-producto-label"></p>
            <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">
                <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>
                <div class="sf-field">
                    <label for="sf-lead-mensaje">Mensaje (opcional)</label>
                    <textarea id="sf-lead-mensaje" name="mensaje" rows="3"></textarea>
                </div>
                <button type="submit" class="sf-btn sf-btn-primary" style="width:100%;margin-top:4px;">Enviar solicitud</button>
            </form>
        </div>
    </div>
</body>

</html>
