<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Sistema de Ventas Simplificado</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #F2F2F2;
        }
        .page-title {
            color: #0C2659;
            font-weight: 500;
        }
        #searchBar {
            border: 2px solid #0C2659;
        }
        #searchBar:focus {
            border-color: #00AC76;
            box-shadow: 0 0 4px rgba(0,172,118,0.4);
        }
        .btn-primary {
            background-color: #0C2659;
            border-color: #0C2659;
        }
        .btn-primary:hover {
            background-color: #07306C;
        }
        .list-group-item {
            font-size: 0.85rem;
        }
        #cartItems {
            max-height: 300px;
            overflow-y: auto;
        }
        /* Para separar la sección de totales */
        .totales-dias {
            background: #fff;
            padding: 1rem;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .totales-dias h5 {
            margin: 0;
            font-size: 1rem;
        }
        /* Toast styling */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1090; /* Ensure toasts are above other elements like modals */
        }
    </style>
</head>
<body>

<div class="container-fluid py-3">
    <div class="row mb-3">
        <div class="col-12">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addProductModal">
                Agregar Nuevo Producto
            </button>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            <div class="mb-2">
                <input type="text" id="searchBar" class="form-control"
                       placeholder="Buscar por código, nombre o laboratorio...">
            </div>

            <div id="productTable">
                </div>
        </div>

        </div>
</div>

<div class="toast-container position-fixed top-0 end-0 p-3">
    </div>


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<div class="modal fade" id="addProductModal" tabindex="-1" aria-labelledby="addProductModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addProductModalLabel">Agregar Nuevo Producto</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addProductForm">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="nombreComercial" class="form-label">Nombre Comercial</label>
                            <input type="text" class="form-control" id="nombreComercial" required>
                        </div>
                        <div class="col-md-6">
                            <label for="nombreGenerico" class="form-label">Nombre Genérico</label>
                            <input type="text" class="form-control" id="nombreGenerico" required>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="codigoBarra" class="form-label">Código de Barras (Opcional)</label>
                            <input type="text" class="form-control" id="codigoBarra">
                        </div>
                        <div class="col-md-6">
                            <label for="laboratorio" class="form-label">Laboratorio</label>
                            <input type="text" class="form-control" id="laboratorio" required>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <label for="costoUnidad" class="form-label">Costo Unidad</label>
                            <input type="number" step="0.01" class="form-control" id="costoUnidad" value="0">
                        </div>
                        <div class="col-md-3">
                            <label for="costoBlister" class="form-label">Costo Blister</label>
                            <input type="number" step="0.01" class="form-control" id="costoBlister" value="0">
                        </div>
                        <div class="col-md-3">
                            <label for="costoMayor" class="form-label">Costo Mayor</label>
                            <input type="number" step="0.01" class="form-control" id="costoMayor" value="0">
                        </div>
                        <div class="col-md-3">
                            <label for="costoMixto" class="form-label">Costo Mixto</label>
                            <input type="number" step="0.01" class="form-control" id="costoMixto" value="0">
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <label for="precioVentaUnidad" class="form-label">Precio Venta Unidad</label>
                            <input type="number" step="0.01" class="form-control" id="precioVentaUnidad" value="0">
                        </div>
                        <div class="col-md-3">
                            <label for="precioVentaBlister" class="form-label">Precio Venta Blister</label>
                            <input type="number" step="0.01" class="form-control" id="precioVentaBlister" value="0">
                        </div>
                        <div class="col-md-3">
                            <label for="precioVentaMayor" class="form-label">Precio Venta Mayor</label>
                            <input type="number" step="0.01" class="form-control" id="precioVentaMayor" value="0">
                        </div>
                        <div class="col-md-3">
                            <label for="precioVentaMixto" class="form-label">Precio Venta Mixto</label>
                            <input type="number" step="0.01" class="form-control" id="precioVentaMixto" value="0">
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label for="fechaVencimiento" class="form-label">Fecha de Vencimiento</label>
                            <input type="date" class="form-control" id="fechaVencimiento" required>
                        </div>
                        <div class="col-md-4">
                            <label for="existencia" class="form-label">Existencias</label>
                            <input type="number" class="form-control" id="existencia" required value="0" min="0">
                        </div>
                        <div class="col-md-4 d-flex align-items-center">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="exentoIva">
                                <label class="form-check-label" for="exentoIva">
                                    Exento de IVA
                                </label>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-primary" id="saveProduct">Guardar Producto</button>
            </div>
        </div>
    </div>
</div>

<script>
// ============================
// Variables globales (from original)
// ============================
let cart = []; // This seems to be for a sales cart, not directly used by product management page
let total = 0;
let ventaEnModificacion = null;

// ============================
// Función cargar productos
// ============================
function loadProducts(query = '', page = 1) {
    $.get('buscar_productos_simplificado.php', { query, page }, function(data) {
        $('#productTable').html(data);
        // It's good practice to re-initialize JS plugins on dynamically loaded content here if needed.
        // For example, if flatpickr initialization was global:
        // if (typeof initializeDatePickersGlobal === "function") {
        //     initializeDatePickersGlobal();
        // }
        // The current setup has flatpickr init inside buscar_productos_simplificado.php script block
    });
}

// ============================
// Actualizar carrito (DOM) (from original, may not be relevant for this page if it's purely product management)
// ============================
function updateCart() {
    let cartHtml = '';
    total = 0;

    cart.forEach(item => {
        let subtotal = item.price * item.quantity;
        total += subtotal;
        cartHtml += `
            <li class="list-group-item d-flex justify-content-between align-items-center">
                <div>
                    <strong>${item.name}</strong> (${item.lab})<br>
                    Precio: Q${item.price.toFixed(2)}<br>
                    Cant:
                    <input type="number" min="1" class="form-control d-inline-block quantity-update"
                           data-name="${item.name}"
                           data-lab="${item.lab}"
                           data-price="${item.price}"
                           value="${item.quantity}"
                           style="width:60px;">
                    Subtotal: Q${subtotal.toFixed(2)}
                </div>
                <button class="btn btn-danger btn-sm remove-item"
                        data-name="${item.name}"
                        data-lab="${item.lab}"
                        data-price="${item.price}">
                    X
                </button>
            </li>
        `;
    });
    // Assuming these elements exist if cart functionality is used on this page
    // If not, these lines would error or do nothing.
    // $('#cartItems').html(cartHtml);
    // $('#cartTotal').text(total.toFixed(2));
}


// ============================
// Función para mostrar Toasts de Bootstrap
// ============================
function showToast(message, type = 'info') { // type can be 'success', 'danger', 'warning', 'info'
    const toastId = 'toast-' + Date.now();
    const toastHtml = `
        <div id="${toastId}" class="toast align-items-center text-bg-${type} border-0" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="5000">
          <div class="d-flex">
            <div class="toast-body">
              ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
          </div>
        </div>
    `;
    // Append to the .toast-container
    $('.toast-container').append(toastHtml);

    const toastElement = document.getElementById(toastId);
    const toastInstance = new bootstrap.Toast(toastElement);
    toastInstance.show();

    // Optional: Remove the toast from DOM after it's hidden
    toastElement.addEventListener('hidden.bs.toast', function () {
        toastElement.remove();
    });
}


// ============================
// Document Ready
// ============================
$(document).ready(function(){
    // Manejar el guardado de nuevo producto
    $('#saveProduct').on('click', function() {
        // Basic validation example (you might want more robust validation)
        if (!$('#nombreComercial').val() || !$('#nombreGenerico').val() || !$('#laboratorio').val() || !$('#fechaVencimiento').val() || !$('#existencia').val()) {
            showToast('Por favor, complete todos los campos requeridos del producto.', 'warning');
            // Highlight missing fields (optional)
            $('#addProductForm input[required]').each(function() {
                if (!$(this).val()) {
                    $(this).addClass('is-invalid');
                } else {
                    $(this).removeClass('is-invalid');
                }
            });
            return;
        }
        $('#addProductForm input.is-invalid').removeClass('is-invalid'); // Clear previous validation states

        const productData = {
            NombreComercial: $('#nombreComercial').val(),
            NombreGenerico: $('#nombreGenerico').val(),
            CodigoBarra: $('#codigoBarra').val(), // <-- NUEVO: Enviar Código de Barras
            laboratorio: $('#laboratorio').val(),
            PrecioVentaUnidad: parseFloat($('#precioVentaUnidad').val()) || 0,
            PrecioVentaBlister: parseFloat($('#precioVentaBlister').val()) || 0,
            PrecioVentaMayor: parseFloat($('#precioVentaMayor').val()) || 0,
            PrecioVentaMixto: parseFloat($('#precioVentaMixto').val()) || 0,
            CostoUnidad: parseFloat($('#costoUnidad').val()) || 0,
            CostoBlister: parseFloat($('#costoBlister').val()) || 0,
            CostoMayor: parseFloat($('#costoMayor').val()) || 0,
            CostoMixto: parseFloat($('#costoMixto').val()) || 0,
            FechaVencimiento: $('#fechaVencimiento').val(),
            existencia: parseInt($('#existencia').val()) || 0,
            exento_iva: $('#exentoIva').is(':checked')
        };

        $.ajax({
            url: 'agregar_producto.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(productData),
            success: function(response) {
                if (response.success) {
                    showToast('Producto agregado exitosamente. Código asignado: ' + response.codigoInterno, 'success');
                    $('#addProductModal').modal('hide');
                    $('#addProductForm')[0].reset(); // Reset form fields
                    loadProducts(); // Recargar la lista de productos
                } else {
                    showToast('Error al agregar producto: ' + (response.message || 'Error desconocido'), 'danger');
                }
            },
            error: function(jqXHR) {
                let errorMsg = 'Error al comunicarse con el servidor para agregar el producto.';
                 if(jqXHR.responseJSON && jqXHR.responseJSON.message){
                    errorMsg = jqXHR.responseJSON.message;
                }
                showToast(errorMsg, 'danger');
            }
        });
    });


    // Cargar productos inicial
    loadProducts();

    // Buscar mientras teclean
    let searchTimeout;
    $('#searchBar').on('keyup', function() {
        clearTimeout(searchTimeout);
        let query = $(this).val();
        searchTimeout = setTimeout(function() {
            loadProducts(query, 1); // Load page 1 for new search
        }, 300); // Debounce search
    });

    // Delegar click para paginación (buscar_productos_simplificado.php)
    $(document).on('click', '.pagination .page-link', function(e){
        e.preventDefault();
        let page = $(this).data('page');
        if (page) {
            let query = $('#searchBar').val();
            loadProducts(query, page);
        }
    });

    // ============================
    // Actualizar Exento IVA
    // ============================
    $(document).on('change', '.exento-iva-check', function() {
        const checkbox = $(this);
        const productId = checkbox.data('id');
        const isChecked = checkbox.is(':checked');

        $.ajax({
            url: 'actualizar_exento_iva.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                id: productId,
                exento_iva: isChecked
            }),
            success: function(response) {
                if (response.success) {
                    showToast('Estado de IVA actualizado.', 'success');
                } else {
                    showToast('Error al actualizar: ' + (response.message || 'Error desconocido'), 'danger');
                    // Revert the checkbox on failure
                    checkbox.prop('checked', !isChecked);
                }
            },
            error: function() {
                showToast('Error de conexión al actualizar el estado de IVA.', 'danger');
                // Revert the checkbox on failure
                checkbox.prop('checked', !isChecked);
            }
        });
    });
    
    // ============================
    // Botón "Eliminar Producto"
    // ============================
    $(document).on('click', '.delete-product-btn', function() {
        const button = $(this);
        const productId = button.data('id');
        // Find the 'NombreComercial' from the same row for the confirmation message
        const productName = button.closest('tr').find('td:nth-child(2) .editable').text().trim();

        if (confirm(`¿Está seguro de que desea eliminar el producto "${productName}" (ID: ${productId})? Esta acción no se puede deshacer.`)) {
            button.prop('disabled', true).text('Elim...'); // Shorten text during load

            $.ajax({
                url: 'eliminar_producto.php',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ id: productId }),
                success: function(response) {
                    if (response.success) {
                        showToast(response.message, 'success');

                        let currentPage = 1;
                        const activePageElement = $('ul.pagination li.active span.page-link');
                        if (activePageElement.length) {
                            const pageText = activePageElement.text();
                            if ($.isNumeric(pageText)) {
                                currentPage = parseInt(pageText);
                            }
                        }

                        // Check if this was the last item on the current page (and not page 1)
                        const productRows = $('#productos-lista tbody tr');
                        // If only one row exists AND it's the one being deleted (check by id or rely on count)
                        // and current page is > 1
                        if (productRows.length === 1 && productRows.first().data('id') == productId && currentPage > 1) {
                           currentPage--;
                        } else if (productRows.length === 0 && currentPage > 1) { // Table became empty
                           currentPage--;
                        }


                        loadProducts($('#searchBar').val(), currentPage);
                        // The button will be removed with the row, no need to re-enable here if successful
                    } else {
                        showToast('Error al eliminar: ' + (response.message || 'Error desconocido'), 'danger');
                        button.prop('disabled', false).text('Eliminar');
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    let errorMessage = 'Error de comunicación con el servidor al intentar eliminar.';
                    if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
                        errorMessage = jqXHR.responseJSON.message;
                    } else if (jqXHR.status === 404) { // Specifically handle 404 from eliminar_producto.php
                        errorMessage = 'Producto no encontrado en el servidor o ya fue eliminado.';
                    }
                    showToast(errorMessage, 'danger');
                    button.prop('disabled', false).text('Eliminar');
                }
            });
        }
    });


    // The following sections are from your original index.php related to sales cart,
    // which might or might not be intended for this specific product management page.
    // I'm keeping them as they were in your provided file.
    // If this page is ONLY for product management, these could be removed.

    // ============================
    // Manejo de "add-to-cart"
    // ============================
    $(document).on('click', '.add-to-cart', function(){
        const name  = $(this).data('name');
        const lab   = $(this).data('lab');
        const price = parseFloat($(this).data('price')) || 0;

        let existing = cart.find(i => i.name === name && i.lab === lab && i.price === price);
        if (existing) {
            existing.quantity += 1;
        } else {
            cart.push({ name, lab, price, quantity: 1 });
        }
        updateCart();
    });

    // ============================
    // Actualizar cantidad
    // ============================
    $(document).on('change', '.quantity-update', function(){
        const name  = $(this).data('name');
        const lab   = $(this).data('lab');
        const price = parseFloat($(this).data('price')) || 0;
        const newQty = parseInt($(this).val());

        let item = cart.find(i => i.name === name && i.lab === lab && i.price === price);
        if (item && newQty > 0) {
            item.quantity = newQty;
        } else if (item && newQty <= 0) { // Remove if quantity is 0 or less
            cart = cart.filter(i => !(i.name === name && i.lab === lab && i.price === price));
        }
        updateCart();
    });

    // ============================
    // Eliminar item del carrito
    // ============================
    $(document).on('click', '.remove-item', function(){
        const name  = $(this).data('name');
        const lab   = $(this).data('lab');
        const price = parseFloat($(this).data('price')) || 0;

        cart = cart.filter(i => !(i.name === name && i.lab === lab && i.price === price));
        updateCart();
    });

    // ============================
    // Botón "Vender (Normal)"
    // ============================
    $('#btnVender').on('click', function(){ // Assuming #btnVender exists in your HTML if this is used
        if (cart.length === 0) {
            showToast('El carrito está vacío.', 'warning');
            return;
        }

        // ... (rest of your #btnVender logic from original file) ...
        // For brevity, I'm omitting the full AJAX call here as it's unchanged
        // but it would be present in your actual file if this button exists.
        // Example:
        // $.ajax({ /* ... url: 'finalizar_venta_simplificado.php' or 'update_sale.php' ... */ });
    });


    // ... (Any other original JavaScript functions and event handlers from your index.php like
    //      btnVentaEspecial, formVentaEspecial submit, btnVerUltimasVentas, loadUltimasVentas,
    //      ver-detalle-venta, modificar-venta, eliminar-venta (for sales), formConfirmarEliminar submit,
    //      formEditarVentaEspecial submit, loadSalesOfDay, loadSucursalName would go here)

});
</script>
</body>
</html>