// billCreatePOS.js
// Lógica POS para la creación de facturas en gestorfit

document.addEventListener('DOMContentLoaded', function () {
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
    // --- Proveedor ---
    let selectedSupplier = null;
    $('#supplier_search').on('input', function () {
        const query = $(this).val();
        if (query.length < 2) {
            $('#supplierResults').addClass('d-none').empty();
            return;
        }
        $.get('/admin-fit/supplier/search', { q: query }, function (data) {
            let html = '';
            data.forEach(supplier => {
                html += `<button type="button" class="list-group-item list-group-item-action" data-id="${supplier.id}" data-name="${supplier.supplier_name}">${supplier.supplier_name} <small class='text-muted'>${supplier.rif || ''}</small></button>`;
            });
            $('#supplierResults').html(html).removeClass('d-none');
        });
    });
    $('#supplierResults').on('click', 'button', function () {
        selectedSupplier = { id: $(this).data('id'), name: $(this).data('name') };
        $('#supplier_id').val(selectedSupplier.id);
        $('#supplierSelectedLabel').text('Proveedor seleccionado: ' + selectedSupplier.name);
        $('#supplierResults').addClass('d-none').empty();
        $('#supplier_search').val(selectedSupplier.name);
    });

    // --- Producto ---
    window.selectedProduct = null;

    // --- Detalle de factura tipo ticket ---
    let billDetails = [];
    function formatCurrency(val) {
        // Formato: punto para miles, coma para decimales (ej: 1.234,56)
        return (val == null ? '0,00' : val.toLocaleString('es-ES', { minimumFractionDigits: 2, maximumFractionDigits: 2 })) + ' Bs';
    }
    function renderBillDetails() {
        let html = '';
        let auxTotal = 0, total = 0;
        const rate = parseFloat($('#amount_rate_input').val()) || 1;
        
        if (billDetails.length === 0) {
            html = `<tr id="emptyDetailsRow">
                <td colspan="6" class="text-center py-4 text-muted">
                    <i class="bi bi-inbox fs-3 d-block mb-2 opacity-50"></i>
                    No hay productos agregados
                </td>
            </tr>`;
        } else {
            billDetails.forEach((item, idx) => {
                const subtotal = item.sale_price * item.quantity;
                auxTotal += subtotal;
                const subtotalFinal = subtotal * rate;
                total += subtotalFinal;
                html += `<tr>
                    <td class="fw-medium ps-3">${item.name}</td>
                    <td class="text-end">${formatCurrency(item.sale_price)}</td>
                    <td class="text-center">
                        <input type="number" min="1" class="form-control form-control-sm bill-qty-input text-center" data-idx="${idx}" value="${item.quantity}">
                    </td>
                    <td class="text-end text-muted">${formatCurrency(subtotal)}</td>
                    <td class="text-end fw-bold text-success">${formatCurrency(subtotalFinal)}</td>
                    <td class="text-center">
                        <button type="button" class="btn btn-sm btn-outline-danger bill-remove-btn" data-idx="${idx}" title="Eliminar"><i class="bi bi-trash"></i></button>
                    </td>
                </tr>`;
            });
        }
        
        $('#billDetailsTable tbody').html(html);
        $('#summaryAuxTotal').text(formatCurrency(auxTotal));
        $('#summaryTotal').text(formatCurrency(total));
        $('#summaryAuxDebt').text(formatCurrency(auxTotal));
        $('#summaryDebt').text(formatCurrency(total));
        $('#aux_total').val(auxTotal.toFixed(2));
        $('#total').val(total.toFixed(2));
        $('#aux_debt').val(auxTotal.toFixed(2));
        $('#debt').val(total.toFixed(2));
        $('#bill_details_json').val(JSON.stringify(billDetails));
        $('#amount_rate').val(rate);
    }
    // Actualizar totales al cambiar la tasa
    $('#amount_rate_input').on('input', renderBillDetails);
    $('#addBillDetailBtn').on('click', function () {
        console.log('Click en Agregar al detalle. selectedProduct:', window.selectedProduct);
        if (!window.selectedProduct) {
            Swal.fire({
                icon: 'info',
                title: 'Sin producto',
                text: 'Debes seleccionar un producto primero.'
            });
            return;
        }
        const qty = parseInt($('#product_quantity').val(), 10) || 1;
        const existsIdx = billDetails.findIndex(i => i.product_id === window.selectedProduct.id);
        if (existsIdx >= 0) {
            billDetails[existsIdx].quantity += qty;
        } else {
            billDetails.push({
                product_id: window.selectedProduct.id,
                name: window.selectedProduct.name,
                sale_price: window.selectedProduct.sale_price,
                quantity: qty
            });
        }
        console.log('billDetails después de agregar:', billDetails);
        renderBillDetails();
        $('#product_search').val('');
        $('#product_quantity').val(1);
        window.selectedProduct = null;
        $('#selectedProductLabel').html('<small class="text-muted d-block">Seleccionado:</small><span class="fw-medium text-success">Ninguno</span>');
        
        Swal.fire({
            icon: 'success',
            title: 'Producto agregado',
            text: 'El producto se agregó al detalle.',
            timer: 1500,
            showConfirmButton: false
        });
    });
    $('#billDetailsTable').on('input', '.bill-qty-input', function () {
        const idx = $(this).data('idx');
        const val = parseInt($(this).val(), 10) || 1;
        billDetails[idx].quantity = val;
        renderBillDetails();
    });
    $('#billDetailsTable').on('click', '.bill-remove-btn', function () {
        const idx = $(this).data('idx');
        billDetails.splice(idx, 1);
        renderBillDetails();
    });

    // --- Validación y envío AJAX ---
    $('#billForm').on('submit', function (e) {
        e.preventDefault();
        e.stopPropagation();
        
        const hasSupplier = !!$('#supplier_id').val();
        const hasProducts = billDetails.length > 0;
        
        console.log('Submit del formulario:', {
            hasSupplier,
            hasProducts,
            billDetails,
            supplier_id: $('#supplier_id').val()
        });
        
        if (!hasSupplier && !hasProducts) {
            Swal.fire({
                icon: 'warning',
                title: 'Faltan datos',
                text: 'Debes seleccionar un proveedor y agregar al menos un producto al detalle.'
            });
            return false;
        } else if (!hasSupplier) {
            Swal.fire({
                icon: 'warning',
                title: 'Falta proveedor',
                text: 'Debes seleccionar un proveedor.'
            });
            return false;
        } else if (!hasProducts) {
            Swal.fire({
                icon: 'warning',
                title: 'Faltan productos',
                text: 'Debes agregar al menos un producto al detalle.'
            });
            return false;
        }
        
        $('#bill_details_json').val(JSON.stringify(billDetails));
        
        const formData = $(this).serialize();
        console.log('Enviando formulario por AJAX. Datos:', formData);
        
        $.ajax({
            url: $(this).attr('action'),
            method: 'POST',
            data: formData,
            success: function(response) {
                Swal.fire({
                    icon: 'success',
                    title: 'Éxito',
                    text: 'Factura creada correctamente.',
                    timer: 2000
                }).then(() => {
                    window.location.href = '/admin-fit/bill';
                });
            },
            error: function(xhr) {
                console.error('Error en AJAX:', xhr);
                let errorMessage = 'Error al crear la factura.';
                if (xhr.responseJSON && xhr.responseJSON.errors) {
                    const errors = Object.values(xhr.responseJSON.errors).flat();
                    errorMessage = errors.join('<br>');
                }
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    html: errorMessage
                });
            }
        });
        
        return false;
    });
    // Responsividad: hacer tabla y formulario más amigable en móvil
    $(window).on('resize', function () {
        if (window.innerWidth < 768) {
            $('#billDetailsTable').addClass('table-responsive-sm');
        } else {
            $('#billDetailsTable').removeClass('table-responsive-sm');
        }
    }).trigger('resize');

    // Cerrar modal proveedor solo si la creación fue exitosa (AJAX ejemplo)
    $('#quickSupplierForm').on('submit', function (e) {
        e.preventDefault();
        var $form = $(this);
        var name = $('#quick_supplier_name').val();
        if (!name) return;
        $.post('/admin-fit/bill/supplier-quick-create', $form.serialize()+ '&_token=' + encodeURIComponent(csrfToken), function (resp) {
            if (resp && resp.success) {
                const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('quickSupplierModal'));
                modal.hide();
                $('#supplier_id').val(resp.data.id);
                $('#supplierSelectedLabel').html('<small class="text-muted d-block">Proveedor:</small><span class="fw-bold text-primary">' + resp.data.supplier_name + '</span>');
            } else {
                $('#quickSupplierError').removeClass('d-none').text(resp.message || 'Error al crear proveedor');
            }
        }).fail(function(){
            $('#quickSupplierError').removeClass('d-none').text('Error al crear proveedor');
        });
    });
    // Cerrar modal producto solo si la creación fue exitosa (AJAX ejemplo)
    $('#quickProductForm').on('submit', function (e) {
        e.preventDefault();
        var $form = $(this);
        var name = $('#quick_product_name').val();
        if (!name) return;
        $.post('/admin-fit/bill/product-quick-create', $form.serialize(), function (resp) {
            if (resp && resp.success) {
                const modal = bootstrap.Modal.getOrCreateInstance(document.getElementById('quickProductModal'));
                modal.hide();
                $('#product_search').val(resp.data.product_name);
                window.selectedProduct = {
                    id: resp.data.id,
                    name: resp.data.product_name,
                    price: parseFloat(resp.data.purchase_price),
                    sale_price: parseFloat(resp.data.sale_price)
                };
                $('#selectedProductLabel').html('<small class="text-muted d-block">Seleccionado:</small><span class="fw-medium text-success">' + window.selectedProduct.name + '</span>');
            } else {
                $('#quickProductError').removeClass('d-none').text(resp.message || 'Error al crear producto');
            }
        }).fail(function(){
            $('#quickProductError').removeClass('d-none').text('Error al crear producto');
        });
    });
});
