<!DOCTYPE html>
<html lang="<?php echo e(app()->getLocale()); ?>">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title><?php echo $__env->yieldContent('title', 'Herbal Solutions'); ?></title>
    <meta name="description" content="<?php echo $__env->yieldContent('description', ''); ?>">
    <meta name="keywords" content="<?php echo $__env->yieldContent('keywords', ''); ?>">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">

    <!-- Favicons -->
    <link href="<?php echo e(asset('assets/img/logo.png')); ?>" rel="icon">
    <link href="<?php echo e(asset('assets/img/logo.png')); ?>" rel="apple-touch-icon">

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com" rel="preconnect">
    <link href="https://fonts.gstatic.com" rel="preconnect" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&family=Lato:ital,wght@0,100;0,300;0,400;0,700;0,900;1,100;1,300;1,400;1,700;1,900&family=Raleway:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">

    <!-- Vendor CSS Files -->
    <link href="<?php echo e(asset('assets/vendor/bootstrap/css/bootstrap.min.css')); ?>" rel="stylesheet">
    <link href="<?php echo e(asset('assets/vendor/bootstrap-icons/bootstrap-icons.css')); ?>" rel="stylesheet">
    <link href="<?php echo e(asset('assets/vendor/aos/aos.css')); ?>" rel="stylesheet">
    <link href="<?php echo e(asset('assets/vendor/glightbox/css/glightbox.min.css')); ?>" rel="stylesheet">
    <link href="<?php echo e(asset('assets/vendor/swiper/swiper-bundle.min.css')); ?>" rel="stylesheet">
    <link href="<?php echo e(asset('assets/css/custom.css')); ?>" rel="stylesheet">

    <!-- Main CSS File -->
    <link href="<?php echo e(asset('assets/css/main.css')); ?>" rel="stylesheet">

    <!-- CSS para Sticky Footer -->
    <style>
        html, body {
            height: 100%;
            margin: 0;
        }
        .page-wrapper {
            min-height: 100%;
            display: flex;
            flex-direction: column;
        }
        .main {
            flex: 1 0 auto;
        }
        .footer {
            flex-shrink: 0;
        }
    </style>

    <?php echo $__env->yieldPushContent('styles'); ?>
</head>

<body class="<?php echo $__env->yieldContent('body-class', 'index-page'); ?>">
    <div class="page-wrapper">
        <!-- Header -->
        <?php echo $__env->make('partials.header', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

        <!-- Main Content -->
        <main class="main">
            <?php echo $__env->yieldContent('content'); ?>
        </main>

        <!-- Footer -->
        <?php echo $__env->make('partials.footer', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

        <!-- Carrito Modal -->
        <div class="modal fade" id="cartModal" tabindex="-1" aria-labelledby="cartModalLabel" aria-hidden="true" data-total-text="<?php echo e(__('messages.total')); ?>" data-remove-text="<?php echo e(__('messages.remove')); ?>">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="cartModalLabel"><?php echo e(__('messages.cart_summary')); ?></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th><?php echo e(__('messages.product')); ?></th>
                                    <th><?php echo e(__('messages.quantity')); ?></th>
                                    <th><?php echo e(__('messages.price')); ?></th>
                                    <th><?php echo e(__('messages.total')); ?></th>
                                    <th><?php echo e(__('messages.remove')); ?></th>
                                </tr>
                            </thead>
                            <tbody id="cartItems"></tbody>
                        </table>
                        <p class="text-end fw-bold" id="cartTotal"><?php echo e(__('messages.total')); ?>: $0.00</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo e(__('messages.close')); ?></button>
                        <a href="<?php echo e(route('checkout')); ?>" class="btn btn-primary"><?php echo e(__('messages.payment')); ?></a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Scroll Top -->
    <a href="#" id="scroll-top" class="scroll-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>

    <!-- Vendor JS Files -->
    <script src="<?php echo e(asset('assets/vendor/bootstrap/js/bootstrap.bundle.min.js')); ?>"></script>
    <script src="<?php echo e(asset('assets/vendor/aos/aos.js')); ?>" defer></script>
    <script src="<?php echo e(asset('assets/vendor/glightbox/js/glightbox.min.js')); ?>" defer></script>
    <script src="<?php echo e(asset('assets/vendor/imagesloaded/imagesloaded.pkgd.min.js')); ?>" defer></script>
    <script src="<?php echo e(asset('assets/vendor/isotope-layout/isotope.pkgd.min.js')); ?>" defer></script>
    <script src="<?php echo e(asset('assets/vendor/waypoints/noframework.waypoints.js')); ?>" defer></script>
    <script src="<?php echo e(asset('assets/vendor/swiper/swiper-bundle.min.js')); ?>" defer></script>

    <!-- Main JS File -->
    <script src="<?php echo e(asset('assets/js/main.js')); ?>" defer></script>

    <!-- Diagnóstico global -->
    <script>
        console.log('App: Cargado - Versión 2025-05-13');
    </script>

    <!-- Script global del carrito -->
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            console.log('App: Scripts globales iniciados');

            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
            if (!csrfToken) {
                console.error('App: CSRF token no encontrado');
                alert('Error: Token CSRF no encontrado');
                return;
            }

            // Añadir al carrito
            document.addEventListener('click', (e) => {
                const button = e.target.closest('.add-to-cart');
                if (!button) return;

                e.preventDefault();
                console.log('App: Clic en add-to-cart');

                const productId = button.getAttribute('data-product-id')?.trim();
                const quantityInput = document.querySelector(`input[data-product-id="${productId}"]`);
                const quantity = quantityInput ? parseInt(quantityInput.value) : 1;

                console.log(`App: productId: "${productId}", quantity: ${quantity}`);

                if (!productId || isNaN(parseInt(productId)) || isNaN(quantity) || quantity < 1) {
                    console.error('App: Datos inválidos', { productId, quantity });
                    alert('Error: Datos de producto o cantidad inválidos');
                    return;
                }

                button.disabled = true;
                button.textContent = '<?php echo e(__('messages.adding')); ?>';

                fetch('<?php echo e(route('cart.add')); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({ product_id: parseInt(productId), quantity })
                })
                .then(response => {
                    console.log(`App: Respuesta /cart/add: ${response.status}`);
                    if (!response.ok) {
                        return response.json().then(err => {
                            throw new Error(err.message || `Error HTTP: ${response.status}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('App: Respuesta JSON:', JSON.stringify(data, null, 2));
                    if (data.success && data.cart !== undefined) {
                        console.log('App: Carrito actualizado:', data.cart);
                        window.updateCart(data.cart, true);
                        if (typeof window.updateCheckoutForm === 'function' && document.getElementById('cart-table')) {
                            console.log('App: Actualizando tabla de checkout');
                            window.updateCheckoutForm(data.cart);
                        }
                    } else {
                        console.error('App: Error en respuesta:', data.message || 'Respuesta inválida');
                        alert('Error: ' + (data.message || 'No se pudo añadir el producto'));
                    }
                })
                .catch(error => {
                    console.error('App: Error al añadir:', error.message);
                    alert('Error al añadir el producto: ' + error.message);
                })
                .finally(() => {
                    button.disabled = false;
                    button.textContent = '<?php echo e(__('messages.add_to_cart')); ?>';
                    console.log('App: Botón restaurado');
                });
            });

            // Actualizar contador
            window.updateCartCount = function(cart) {
                const cartCount = cart && Object.keys(cart).length > 0 ? Object.values(cart).reduce((sum, item) => sum + Number(item.quantity), 0) : 0;
                const cartCountElement = document.getElementById('cart-count');
                if (cartCountElement) {
                    cartCountElement.textContent = cartCount;
                    console.log('App: Contador actualizado:', cartCount);
                }
            };

            // Actualizar modal
            window.updateCart = function(cart, showModal = false) {
                console.log('App: Actualizando carrito:', JSON.stringify(cart, null, 2));
                const cartItems = document.getElementById('cartItems');
                if (!cartItems) {
                    console.error('App: #cartItems no encontrado');
                    return;
                }

                cartItems.innerHTML = '';
                let total = 0;

                if (!cart || Object.keys(cart).length === 0) {
                    cartItems.innerHTML = '<tr><td colspan="5"><?php echo e(__('messages.cart_empty')); ?></td></tr>';
                } else {
                    Object.entries(cart).forEach(([id, item]) => {
                        const price = parseFloat(item.price);
                        const quantity = Number(item.quantity);
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${item.name}</td>
                            <td>${quantity}</td>
                            <td>$${price.toFixed(2)}</td>
                            <td>$${(price * quantity).toFixed(2)}</td>
                            <td><button class="btn btn-danger btn-sm modal-remove-from-cart" data-product-id="${id}">${document.querySelector('#cartModal').dataset.removeText}</button></td>
                        `;
                        cartItems.appendChild(row);
                        total += price * quantity;
                    });
                }

                const cartTotalElement = document.getElementById('cartTotal');
                if (cartTotalElement) {
                    cartTotalElement.textContent = `${document.querySelector('#cartModal').dataset.totalText}: $${total.toFixed(2)}`;
                }
                window.updateCartCount(cart);

                // Eliminar desde modal
                document.querySelectorAll('#cartModal .modal-remove-from-cart').forEach(button => {
                    button.addEventListener('click', e => {
                        e.preventDefault();
                        e.stopPropagation();
                        const productId = button.getAttribute('data-product-id')?.trim();
                        console.log('App: Eliminando desde modal:', productId);

                        fetch('<?php echo e(route('cart.remove')); ?>', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': csrfToken,
                                'Accept': 'application/json'
                            },
                            body: JSON.stringify({ product_id: parseInt(productId) })
                        })
                        .then(response => {
                            console.log('App: Respuesta /cart/remove (modal):', response.status);
                            if (!response.ok) {
                                return response.json().then(err => {
                                    throw new Error(err.message || `Error HTTP: ${response.status}`);
                                });
                            }
                            return response.json();
                        })
                        .then(data => {
                            console.log('App: Carrito después de eliminar (modal):', data.cart);
                            window.updateCart(data.cart);
                            if (typeof window.updateCheckoutForm === 'function' && document.getElementById('cart-table')) {
                                console.log('App: Actualizando tabla de checkout desde modal');
                                window.updateCheckoutForm(data.cart);
                            }
                        })
                        .catch(error => {
                            console.error('App: Error en modal:', error);
                            alert('Error al eliminar desde modal: ' + error.message);
                        });
                    });
                });

                if (showModal) {
                    console.log('App: Mostrando modal');
                    new bootstrap.Modal(document.getElementById('cartModal')).show();
                }
            };

            // Actualizar tabla de checkout
            window.updateCheckoutTable = function(cart) {
                console.log('App: Actualizando tabla de checkout:', JSON.stringify(cart, null, 2));
                const table = document.getElementById('cart-table');
                if (!table) {
                    console.error('App: #cart-table no encontrado');
                    return;
                }

                let total = 0;
                if (!cart || Object.keys(cart).length === 0) {
                    table.innerHTML = '<tr><td colspan="5" class="text-center"><?php echo e(__('messages.cart_empty')); ?></td></tr>';
                    console.log('App: Carrito vacío');
                } else {
                    // Eliminar filas obsoletas
                    table.querySelectorAll('tr[data-product-id]').forEach(row => {
                        const rowId = row.getAttribute('data-product-id');
                        if (!cart[rowId]) {
                            console.log('App: Eliminando fila:', rowId);
                            row.remove();
                        }
                    });
                    // Actualizar o añadir filas
                    Object.entries(cart).forEach(([id, item]) => {
                        let row = table.querySelector(`tr[data-product-id="${id}"]`);
                        if (row) {
                            const quantityCell = row.querySelector('.quantity');
                            const totalCell = row.querySelector('.total');
                            if (quantityCell && totalCell) {
                                quantityCell.textContent = item.quantity;
                                totalCell.textContent = `$${parseFloat(item.price * item.quantity).toFixed(2)}`;
                                console.log('App: Fila actualizada:', id);
                            } else {
                                console.error('App: Celdas .quantity o .total no encontradas en fila:', id);
                            }
                        } else {
                            // Añadir nueva fila si no existe
                            row = document.createElement('tr');
                            row.setAttribute('data-product-id', id);
                            row.innerHTML = `
                                <td>${item.name}</td>
                                <td class="quantity">${item.quantity}</td>
                                <td class="price">$${parseFloat(item.price).toFixed(2)}</td>
                                <td class="total">$${parseFloat(item.price * item.quantity).toFixed(2)}</td>
                                <td><button class="btn btn-danger btn-sm checkout-remove-from-cart" data-product-id="${id}"><?php echo e(__('messages.remove')); ?></button></td>
                            `;
                            table.appendChild(row);
                            console.log('App: Fila añadida:', id);
                        }
                    });
                    total = Object.values(cart).reduce((sum, item) => sum + parseFloat(item.price) * parseInt(item.quantity), 0);
                }

                const cartTotalElement = document.getElementById('cart-total');
                if (cartTotalElement) {
                    cartTotalElement.textContent = `$${total.toFixed(2)}`;
                    console.log('App: Total actualizado:', total.toFixed(2));
                } else {
                    console.error('App: #cart-total no encontrado');
                }
            };

            // Cargar carrito inicial
            fetch('<?php echo e(route('cart.get')); ?>', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                }
            })
            .then(response => {
                console.log('App: Respuesta /cart:', response.status);
                if (!response.ok) throw new Error('Error HTTP: ' + response.status);
                return response.json();
            })
            .then(data => {
                console.log('App: Carrito inicial:', JSON.stringify(data.cart, null, 2));
                window.updateCart(data.cart);
                if (document.getElementById('cart-table')) {
                    console.log('App: Inicializando tabla de checkout');
                    window.updateCheckoutForm(data.cart);
                }
            })
            .catch(error => {
                console.error('App: Error al cargar carrito:', error);
                window.updateCart({});
                alert('Error al cargar el carrito: ' + error.message);
            });

            // Escuchar cambios en el carrito desde checkout
            document.addEventListener('cartUpdated', function(e) {
                console.log('App: Evento cartUpdated recibido con carrito:', JSON.stringify(e.detail.cart, null, 2));
                window.updateCart(e.detail.cart);
                if (typeof window.updateCheckoutForm === 'function' && document.getElementById('cart-table')) {
                    console.log('App: Actualizando tabla de checkout desde evento cartUpdated');
                    window.updateCheckoutForm(e.detail.cart);
                }
            });

            // Actualizar modal al abrirla
            document.getElementById('cartModal').addEventListener('show.bs.modal', function() {
                console.log('App: Abriendo modal, recargando carrito');
                fetch('<?php echo e(route('cart.get')); ?>', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': csrfToken
                    }
                })
                .then(response => {
                    console.log('App: Respuesta /cart al abrir modal:', response.status);
                    if (!response.ok) throw new Error('Error HTTP: ' + response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('App: Carrito al abrir modal:', JSON.stringify(data.cart, null, 2));
                    window.updateCart(data.cart);
                })
                .catch(error => {
                    console.error('App: Error al recargar carrito para modal:', error);
                    window.updateCart({});
                });
            });
        });
    </script>

    <?php echo $__env->yieldPushContent('scripts'); ?>
</body>
</html><?php /**PATH C:\xampp\htdocs\herbalsolutions\resources\views/layouts/app.blade.php ENDPATH**/ ?>