<?php include '../includes/session_control.php'; ?>
<?php include '../templates/header.php'; ?>

<h1 class="h3 mb-4 text-gray-800">Crear Cotización</h1>

<?php include '../users/user_selection.php'; ?>

<button type="button" id="createCotizacionBtn" class="btn btn-success btn-block mt-3">Crear</button>
<button type="button" id="updateCotizacionBtn" class="btn btn-primary btn-block mt-3" style="display: none;">Actualizar destinatarios</button>

<div id="cotizacionDetails" style="display: none;">
    <h2 id="cotizacionTitle"></h2>

    <h3>Datos del Cliente</h3>
    <button type="button" id="sendCotizacionBtn" class="btn btn-primary btn-block mt-3">Enviar</button>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Nombre</th>
                <th>Teléfono</th>
                <th>Dirección</th>
                <th>Ciudad</th>
            </tr>
        </thead>
        <tbody id="clienteHeaderTable"></tbody>
    </table>

    <div class="form-group">
        <label for="tipoCotizacionSelect">Tipo de Cotización:</label>
        <select id="tipoCotizacionSelect" class="form-control"></select>
    </div>

    <h3>Detalles de la Cotización</h3>
    <table class="table table-bordered">
        <thead id="detalleCotizacionHeader"></thead>
        <tbody id="cotizacionTable"></tbody>
    </table>
    <div id="totalesCotizacion" style="display: none;">
        <div>Subtotal: <span id="subtotal"></span></div>
        <div>IVA: <span id="iva"></span></div>
        <div>Total: <span id="total"></span></div>
    </div>
    <div class="form-group">
        <label for="observaciones">Observaciones:</label>
        <textarea id="observaciones" class="form-control editable" rows="5">Precio unitario no incluye IVA
- IVA 19%
- Sujeto a disponibilidad de mercancia
- Imágenes solo de Referencia, El producto real puede tener algunas diferencias.
- Precios pueden variar según la cantidad cotizada
- Validez de la oferta: 3 dias habiles
- Tiempo de entrega: 3 días habiles sin marcación  8 dias habiles con marcación despues de aprobada la orden de compra, mas lo que tome la transportadora 
- Envio Se cotiza de acuerdo a las unidades a despachar y Ciudad destino 
-Forma de Pago Contado para pedidos sin marca 
-Con marca 50% para iniciar proceso,  50% restante antes de hacer el Despacho o la entrega</textarea>
    </div>
</div>

<div id="buscadorContainer" style="display: none;">
    <?php include '../marcacion/calculadoramarca.php'; ?>
    <div id="buscadorContent"></div>
</div>
</div>

<!-- Email Modal -->
<div class="modal fade" id="emailModal" tabindex="-1" aria-labelledby="emailModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="emailModalLabel">Enviar Cotización</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="emailForm">
                    <div class="form-group">
                        <label for="email">Correo Electrónico</label>
                        <input type="email" class="form-control" id="email" required>
                    </div>
                    <div class="form-group">
                        <label for="subject">Asunto</label>
                        <input type="text" class="form-control" id="subject" required>
                    </div>
                    <div class="form-group">
                        <label for="message">Cuerpo del Mensaje</label>
                        <textarea class="form-control" id="message" rows="6" required>Buen Día

De acuerdo a su amable solicitud enviamos cotización de los productos requeridos.

Si tienes alguna duda adicional, no dudes en contactarnos.

Cordialmente,

COMPRANET COMERCIO ELECTRONICO S.A.S.

Bogotá D.C. – Colombia
Página Web: http://www.compranet.com.co
No imprima este correo a menos que sea absolutamente necesario. El medio ambiente es responsabilidad de todos.</textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">Enviar correo</button>
                    <button type="button" id="viewPdfBtn" class="btn btn-secondary mt-2">Ver</button> <!-- Botón para ver el PDF -->
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        // Si en la URL viene ?id=, cargar cotización existente
        const urlParams = new URLSearchParams(window.location.search);
        const cotizacionId = urlParams.get('id');

        if (cotizacionId) {
            $('#cotizacionTitle').text('Cotización No ' + cotizacionId);
            $('#createCotizacionBtn').hide();
            $('#updateCotizacionBtn').show();
            $('#cotizacionDetails').show();
            $('#buscadorContainer').show();

            localStorage.removeItem('precioFinalMarca');
            localStorage.removeItem('tecnicaTipoRango');

            // 1. Cargar cliente
            updateClienteDetails(cotizacionId);

            // 2. Cargar tipos de cotización y detalles
            loadTiposCotizacion(cotizacionId, function() {
                loadCotizacionDetails(cotizacionId);
            });

            // 3. Cargar el buscador también
            let idIngreso = cotizacionId;
            let idTabla = 'tb_cotizacion_detalle';
            let urlBuscador = '../cotizaciones/buscadorcotizaciones.php';

            $.get(urlBuscador, {
                idIngreso: idIngreso,
                idTabla: idTabla
            }, function(response) {
                $('#buscadorContent').html(response);
            }).fail(function(xhr, status, error) {
                console.log("Error loading buscador: " + xhr.status + " " + xhr.statusText);
            });
        }



        $('#createCotizacionBtn').click(function() {
            let idUsuario = $('#userEmail').val();
            let idTercero = $('#terceroSelect').val() || null;
            let idFacturacion = $('#facturacionSelect').val() || null;
            let observaciones = $('#observaciones').val();

            $.ajax({
                url: '../cotizaciones/create_cotizacion.php',
                type: 'POST',
                data: {
                    idUsuario: idUsuario,
                    idTercero: idTercero,
                    idFacturacion: idFacturacion,
                    observaciones: observaciones
                },
                dataType: 'json',
                success: function(response) {
                    if (response.cotizacionId) {
                        let cotizacionId = response.cotizacionId;
                        let data = response.cotizacion;
                        $('#cotizacionTitle').text('Cotización No ' + cotizacionId);
                        $('#createCotizacionBtn').hide();
                        $('#updateCotizacionBtn').show();
                        let headerContent = `
                            <tr>
                                <td>${data.nombre || ''} ${data.apellido || ''}</td>
                                <td>${data.telefono || ''}</td>
                                <td>${data.direccion || ''}, ${data.direccionLinea2 || ''}</td>
                                <td>${data.Ciudad || ''}, ${data.Departamento || ''}</td>
                            </tr>
                        `;
                        $('#clienteHeaderTable').html(headerContent);
                        $('#cotizacionDetails').show();

                        localStorage.removeItem('precioFinalMarca');
                        localStorage.removeItem('tecnicaTipoRango');

                        let idIngreso = cotizacionId;
                        let idTabla = 'tb_cotizacion_detalle';
                        let urlBuscador = '../cotizaciones/buscadorcotizaciones.php';

                        console.log("URL Buscador: " + urlBuscador);

                        $.get(urlBuscador, {
                            idIngreso: idIngreso,
                            idTabla: idTabla
                        }, function(response) {
                            console.log("Buscador response: ", response);
                            $('#buscadorContent').html(response);
                        }).fail(function(xhr, status, error) {
                            console.log("Error loading buscador: " + xhr.status + " " + xhr.statusText);
                        });

                        $('#buscadorContainer').show();

                        loadTiposCotizacion(cotizacionId, function() {
                            loadCotizacionDetails(cotizacionId);
                        });

                        // Attach event listener for observaciones field
                        $('#observaciones').on('blur', function() {
                            let newObservaciones = $(this).val();
                            $.ajax({
                                url: '../cotizaciones/update_observaciones.php',
                                type: 'POST',
                                data: {
                                    cotizacionId: cotizacionId,
                                    observaciones: newObservaciones
                                },
                                success: function(response) {
                                    console.log('Observaciones updated successfully.');
                                },
                                error: function(xhr, status, error) {
                                    console.log(xhr.responseText);
                                }
                            });
                        });
                    } else {
                        console.log("Error: No se pudo crear la cotización.");
                    }
                },
                error: function(xhr, status, error) {
                    console.log(xhr.responseText);
                }
            });
        });

        $('#updateCotizacionBtn').click(function() {
            let cotizacionId = $('#cotizacionTitle').text().split(' ')[2];
            let idUsuario = $('#userEmail').val();
            let idTercero = $('#terceroSelect').val() || null;
            let idFacturacion = $('#facturacionSelect').val() || null;
            let observaciones = $('#observaciones').val();

            $.ajax({
                url: '../cotizaciones/update_cotizacion.php',
                type: 'POST',
                data: {
                    cotizacionId: cotizacionId,
                    idUsuario: idUsuario,
                    idTercero: idTercero,
                    idFacturacion: idFacturacion,
                    observaciones: observaciones
                },
                success: function(response) {
                    console.log(response);
                    updateClienteDetails(cotizacionId);
                },
                error: function(xhr, status, error) {
                    console.log(xhr.responseText);
                }
            });

            // Attach event listener for observaciones field
            $('#observaciones').on('blur', function() {
                let newObservaciones = $(this).val();
                $.ajax({
                    url: '../cotizaciones/update_observaciones.php',
                    type: 'POST',
                    data: {
                        cotizacionId: cotizacionId,
                        observaciones: newObservaciones
                    },
                    success: function(response) {
                        console.log('Observaciones updated successfully.');
                    },
                    error: function(xhr, status, error) {
                        console.log(xhr.responseText);
                    }
                });
            });
        });

        function updateClienteDetails(cotizacionId) {
            $.ajax({
                url: '../cotizaciones/get_cliente_details.php',
                type: 'GET',
                data: {
                    cotizacionId: cotizacionId
                },
                dataType: 'json',
                success: function(data) {
                    let headerContent = `
                <tr>
                    <td>${data.nombre || ''} ${data.apellido || ''}</td>
                    <td>${data.telefono || ''}</td>
                    <td>${data.direccion || ''}, ${data.direccionLinea2 || ''}</td>
                    <td>${data.Ciudad || ''}, ${data.Departamento || ''}</td>
                </tr>
            `;
                    $('#clienteHeaderTable').html(headerContent);

                    // Precargar selects de usuario, tercero, facturacion
                    if (data.idUsuario) {
                        $('#userEmail').val(data.idUsuario).trigger('change');
                    }
                    if (data.idTercero) {
                        $('#terceroSelect').val(data.idTercero).trigger('change');
                    }
                    if (data.idFacturacion) {
                        $('#facturacionSelect').val(data.idFacturacion).trigger('change');
                    }

                    // Precargar observaciones
                    if (data.observaciones) {
                        $('#observaciones').val(data.observaciones);
                    }

                    $('#cotizacionDetails').show();
                },
                error: function(xhr, status, error) {
                    console.log(xhr.responseText);
                }
            });
        }


        function loadCotizacionDetails(cotizacionId) {
            $.ajax({
                url: '../cotizaciones/get_cotizacion_details.php',
                type: 'GET',
                data: {
                    cotizacionId: cotizacionId
                },
                dataType: 'json',
                success: function(data) {
                    let tipoCotizacionId = $('#tipoCotizacionSelect').val();
                    let tableContent = '';
                    let subtotal = 0;
                    let iva = 0;

                    // Definir el encabezado de la tabla
                    let tableHeader = `
                        <tr>
                            <th>Referencia</th>
                            <th>Imagen</th>
                            <th>Producto</th>
                            <th class="qty-col">Cant. Precio</th>
                            
                            <th class="price-col">Subtotal</th>
                            <th class="price-col">IVA</th>
                            <th class="price-col">Total</th>
                            <th>Observaciones</th>
                            <th>Stock</th>
                            <th>Última Act.</th>
                            <th>VerEx</th>
                            <th>ImagenWP</th>
                            <th>Eliminar</th>
                        </tr>
                    `;

                    data.forEach(item => {
                        let productoLink = `https://compranet.com.co/?p=${item.wp_id}`;
                        let imagenUrl = item.linkImagen.replace('J:/images', 'https://sistema.compranet.com.co/images/');
                        let precioUnitario = parseFloat(item.precioVenta); // sin IVA
                        let cantidad = parseFloat(item.cantidad);
                        let impuestoPorcentaje = parseFloat(item.Impuesto); // ya como decimal: 0.19

                        let ivaUnitario = +(precioUnitario * impuestoPorcentaje).toFixed(2);
                        let subtotalItem = +(precioUnitario * cantidad).toFixed(2);
                        let ivaItem = +(ivaUnitario * cantidad).toFixed(2);
                        let totalItem = +(subtotalItem + ivaItem).toFixed(2);


                        if (tipoCotizacionId == 1) {
                            subtotal = +(subtotal + subtotalItem).toFixed(2);
                            iva = +(iva + ivaItem).toFixed(2);
                        }


                        tableContent += `
                            <tr>
                                <td>${item.referenciaCPN}</td>
                                <td><img src="${imagenUrl}" alt="Imagen" style="width: 50px; height: 50px;"></td>
                                <td><a href="${productoLink}" target="_blank">${item.Producto} - ${item.txtColor}</a></td>
                                <td contenteditable="true" class="editable qty-col" data-field="cantidad" data-id="${item.id}" style="background-color: #d1ecf1; text-align: right;">${item.cantidad}</td>
                                <td contenteditable="true" class="editable price-col" data-field="precioVenta" data-id="${item.id}" style="background-color: #d1ecf1; text-align: right;">${item.precioVenta.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                                <td class="price-col">${subtotalItem.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                                <td class="price-col">${ivaItem.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                                <td class="price-col">${totalItem.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                                <td contenteditable="true" class="editable" data-field="observaciones" data-id="${item.id}" style="background-color: #d1ecf1;">${item.observaciones}</td>
                                <td>${item.inventario}</td>
                                <td>${item.fechaActualizacion}</td>
                                <td><button class="btn btn-link" onclick="window.open('${item.urlExterna}', '_blank')">VerEx</button></td>
                                <td><button class="btn btn-link" onclick="openImagenWP(${item.id})">ImagenWP</button></td>
                                <td><button class="btn btn-danger delete-item" data-id="${item.id}">Eliminar</button></td>
                            </tr>
                        `;
                    });

                    // Insertar el encabezado y el contenido de la tabla
                    $('#detalleCotizacionHeader').html(tableHeader);
                    $('#cotizacionTable').html(tableContent);

                    if (tipoCotizacionId == 1) {
                        let total = subtotal + iva;
                        $('#totalesCotizacion').html(`
                            <tr>
                                <td colspan="5"></td>
                                <td>Subtotal</td>
                                <td>${subtotal.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                            </tr>
                            <tr>
                                <td colspan="5"></td>
                                <td>IVA</td>
                                <td>${iva.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                            </tr>
                            <tr>
                                <td colspan="5"></td>
                                <td>Total</td>
                                <td>${total.toLocaleString('es-CO', { style: 'currency', currency: 'COP', minimumFractionDigits: 0 })}</td>
                            </tr>
                        `).show();
                    } else {
                        $('#totalesCotizacion').hide();
                    }

                    $('#cotizacionDetails').show();

                    $('.editable').blur(function() {
                        let field = $(this).data('field');
                        let id = $(this).data('id');
                        let value = $(this).text();

                        $.ajax({
                            url: '../cotizaciones/update_cotizacion_detalle.php',
                            type: 'POST',
                            data: {
                                field: field,
                                id: id,
                                value: value
                            },
                            success: function(response) {
                                console.log('Detalle de cotización actualizado.');
                                loadCotizacionDetails(cotizacionId);
                            },
                            error: function(xhr, status, error) {
                                console.log(xhr.responseText);
                            }
                        });
                    });

                    $('.editable').keydown(function(event) {
                        if (event.key === 'Enter') {
                            event.preventDefault();
                            $(this).blur();
                        }
                    });

                    $('.delete-item').click(function() {
                        let id = $(this).data('id');
                        $.ajax({
                            url: '../cotizaciones/delete_cotizacion_detalle.php',
                            type: 'POST',
                            data: {
                                id: id
                            },
                            success: function(response) {
                                console.log('Producto eliminado.');
                                loadCotizacionDetails(cotizacionId);
                            },
                            error: function(xhr, status, error) {
                                console.log(xhr.responseText);
                            }
                        });
                    });
                },
                error: function(xhr, status, error) {
                    console.log(xhr.responseText);
                }
            });
        }

        function loadTiposCotizacion(cotizacionId, callback) {
            $.ajax({
                url: '../cotizaciones/get_tipos_cotizacion.php',
                type: 'GET',
                data: {
                    cotizacionId: cotizacionId
                },
                dataType: 'json',
                success: function(data) {
                    let options = data.tipos.map(tipo => `<option value="${tipo.id}">${tipo.nombre}</option>`).join('');
                    $('#tipoCotizacionSelect').html(options);
                    $('#tipoCotizacionSelect').val(data.tipoCotizacionId || 1);
                    if (callback) {
                        callback();
                    }
                },
                error: function(xhr, status, error) {
                    console.log(xhr.responseText);
                }
            });
        }

        $('#tipoCotizacionSelect').change(function() {
            let cotizacionId = $('#cotizacionTitle').text().split(' ')[2];
            let tipoCotizacionId = $(this).val();

            $.ajax({
                url: '../cotizaciones/update_tipo_cotizacion.php',
                type: 'POST',
                data: {
                    cotizacionId: cotizacionId,
                    tipoCotizacionId: tipoCotizacionId
                },
                success: function(response) {
                    console.log('Tipo de cotización actualizado.');
                    loadCotizacionDetails(cotizacionId);
                },
                error: function(xhr, status, error) {
                    console.log(xhr.responseText);
                }
            });
        });

        window.openImagenWP = function(idDetalleCotizacion) {
            var modal = document.createElement('div');
            modal.style.display = 'block';
            modal.style.position = 'fixed';
            modal.style.zIndex = '1';
            modal.style.left = '0';
            modal.style.top = '0';
            modal.style.width = '100%';
            modal.style.height = '100%';
            modal.style.overflow = 'auto';
            modal.style.backgroundColor = 'rgb(0,0,0)';
            modal.style.backgroundColor = 'rgba(0,0,0,0.4)';
            modal.style.paddingTop = '60px';

            var modalContent = document.createElement('div');
            modalContent.style.backgroundColor = '#fefefe';
            modalContent.style.margin = '5% auto';
            modalContent.style.padding = '20px';
            modalContent.style.border = '1px solid #888';
            modalContent.style.width = '80%';

            var iframe = document.createElement('iframe');
            iframe.src = `../cotizaciones/imgwhatsapp.php?id_cotizacion_detalle=${idDetalleCotizacion}`;
            iframe.style.width = '100%';
            iframe.style.height = '500px';
            iframe.style.border = 'none';

            var closeButton = document.createElement('span');
            closeButton.innerHTML = '&times;';
            closeButton.style.color = '#aaa';
            closeButton.style.float = 'right';
            closeButton.style.fontSize = '28px';
            closeButton.style.fontWeight = 'bold';
            closeButton.style.cursor = 'pointer';
            closeButton.onclick = function() {
                modal.style.display = 'none';
            };

            modalContent.appendChild(closeButton);
            modalContent.appendChild(iframe);
            modal.appendChild(modalContent);

            document.body.appendChild(modal);
        };

        // Ensure we don't bind the click handler multiple times (avoid duplicate emails)
        $('#sendCotizacionBtn').off('click.sendCotizacion').on('click.sendCotizacion', function() {
            let cotizacionId = $('#cotizacionTitle').text().split(' ')[2];
            let templateType = $('#tipoCotizacionSelect').val();

            $.ajax({
                url: '../cotizaciones/generate_pdf.php',
                type: 'POST',
                data: {
                    cotizacionId: cotizacionId,
                    templateType: templateType
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Populate email modal fields with email from response
                        $('#email').val(response.email); // Set the email field with the fetched email
                        $('#subject').val('Cotización No: ' + cotizacionId);
                        $('#emailModal').modal('show');

                        // Mostrar el botón de ver PDF
                        $('#viewPdfBtn').off('click').on('click', function() {
                            window.open(response.pdfurl, '_blank');
                        });

                        // Unbind any previous submit event to prevent multiple submissions
                        $('#emailForm').off('submit').on('submit', function(event) {
                            event.preventDefault();
                            let $submitBtn = $('#emailForm').find('button[type="submit"]');
                            // Prevent double submissions
                            if ($submitBtn.prop('disabled')) return;
                            $submitBtn.prop('disabled', true);

                            let email = $('#email').val();
                            let subject = $('#subject').val();
                            let message = $('#message').val();
                            let pdfFilePath = response.pdf;

                            $.ajax({
                                url: '../cotizaciones/send_email.php',
                                type: 'POST',
                                data: {
                                    email: email,
                                    subject: subject,
                                    message: message,
                                    pdfFilePath: pdfFilePath
                                },
                                dataType: 'json', // Ensure the response is parsed as JSON
                                success: function(response) {
                                    if (response.success) {
                                        alert('Correo enviado exitosamente.');
                                        $('#emailModal').modal('hide');
                                    } else {
                                        alert('Error al enviar el correo.');
                                        $submitBtn.prop('disabled', false);
                                    }
                                },
                                error: function(xhr, status, error) {
                                    console.log(xhr.responseText);
                                    alert('Error al enviar el correo.');
                                    $submitBtn.prop('disabled', false);
                                }
                            });
                        });
                    } else {
                        alert('Error al generar la cotización en PDF.');
                    }
                },
                error: function(xhr, status, error) {
                    console.log(xhr.responseText);
                }
            });
        });



    });
</script>
<?php include '../templates/footer.php'; ?>