const btnProcesar = document.getElementById('btnProcesar');
const btnProcesar2 = document.getElementById('btnProcesar2');

const id_cliente = document.getElementById('id_cliente');
const id_cliente_badge = document.getElementById('id_cliente_badge');
const buscarCliente = document.getElementById("buscarCliente");


const reset_cliente = document.getElementById("reset_cliente");

const form = document.getElementById('formulario');

const btnClientesHide = document.getElementById('btnClientesHide');
const btnClientesShow = document.getElementById('btnClientesShow');
const areaCliente = document.getElementById('areaCliente');
const areaClienteMinimizado = document.getElementById('areaClienteMinimizado');

const fecha = document.getElementById("fecha");
const tipo = document.getElementById("tipo");
const banco = document.getElementById("banco");
const referencias = document.getElementById("referencias");
const anotacion = document.getElementById("anotacion");

const monto_total = document.getElementById('monto_total');
const saldo_total = document.getElementById('saldo_total');
const abonar_total = document.getElementById('abonar_total');

const area_creditos = document.getElementById('area_creditos');

let showCliente=true;
let selectedCliente=false;
let creditos=[];
let creditos_asignados=[];

document.addEventListener('DOMContentLoaded', function () {
    //cargarDetalle(true)

    //Autocomplete - Jquery UI, Buscar Clientes para la Venta
    $("#buscarCliente").autocomplete({
        minLength: 2,
        source: function (request, response) {
            $.ajax({
                url: base_url + 'creditoventas/buscarCliente',
                dataType: "json",
                data: {
                    q: request.term
                },
                success: function (data) {
                    response(data);
                }
            });
        },
        select: function (event, ui) {

            area_creditos.innerHTML=`<div class="spinner-border spinner-border-sm text-warning mr-1" role="status"><span class="sr-only">Loading...</span></div><span class='text-warning'>Recuperando datos del cliente</span>`

            buscarCliente.disabled = true;
            id_cliente.value = ui.item.id;
            id_cliente_badge.innerHTML = ui.item.id;
            selectedCliente=true;
            btnProcesar.disabled = false;
            btnProcesar2.disabled = false;
            fecha.disabled = false;
            tipo.disabled = false;
            banco.disabled = false;
            referencias.disabled = false;
            anotacion.disabled = false;

            $.ajax({
                url: base_url + 'creditoventas/listar_creditos',
                dataType: "json",
                data: {
                    id: ui.item.id
                },
                success: function (data) {
                    creditos=[...data];             
                    creditos_asignados=[];
    
                    creditos.map((credito,i) => {
                        credito.asignado=false;
                        credito.index=i;
                    });
                    
                    llenar_area_asignados()
                }
            });
            

        },
      
    })

    /* PRECAERGANDO DATOS PARA PRUEBA */

        /*buscarCliente.value='FINCA SANTA CLARA'
        buscarCliente.disabled = true;
        id_cliente.value = 7;
        id_cliente_badge.innerHTML = 7;
        selectedCliente=true;
        btnProcesar.disabled = false;
        btnProcesar2.disabled = false;
        fecha.disabled = false;
        tipo.disabled = false;
        banco.disabled = false;
        referencias.disabled = false;
        anotacion.disabled = false;

        $.ajax({
            url: base_url + 'creditoventas/listar_creditos',
            dataType: "json",
            data: {
                id: 85
            },
            success: function (data) {

                creditos=[...data];             
                creditos_asignados=[];

                creditos.map((credito,i) => {
                    credito.asignado=false;
                    credito.index=i;
                });

                asignar_credito(0);
                asignar_credito(1);
                asignar_credito(2);
                asignar_credito(3);
                asignar_credito(4);
                llenar_area_noasignados()
                //llenar_area_asignados()
                

                
            }
        });
    /* FIN DE DATOS DE PRUEBA */



    reset_cliente.addEventListener('click', resetCliente)
    btnProcesar.addEventListener('click', generarAbono)
    btnProcesar2.addEventListener('click', generarAbono)
    btnClientesHide.addEventListener('click', toggleClientes);
    btnClientesShow.addEventListener('click', toggleClientes); 

    fecha.value = new Date().toISOString().substring(0, 10);

    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function (form) {
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            /*if (form.checkValidity() === false) {
                event.stopPropagation();
                form.classList.add('was-validated');
            } else {
                const url = base_url + 'creditoventas/registrarAbonos';
                const http = new XMLHttpRequest();
                http.open("POST", url, true);
                http.send(new FormData(this));
                http.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        const res = JSON.parse(this.responseText);
                        alertas(res.msg, res.icono);
                        if (res.icono == 'success') {
                            $('#nuevo_cliente').modal('hide');
                        }
                    }
                }
            }*/
           console.log('submit')

        }, false);
    });

})

function llenar_area_noasignados()
{
    let html=`
        <button class='btn btn-warning btn-sm' onclick='llenar_area_asignados()'><i class="fa-solid fa-left-long mr-1"></i>REGRESAR</button>
        <button class='btn btn-success btn-sm' onclick='asignar_seleccionados()' id='btn_asignar_seleccionados' disabled><i class="fa-solid fa-plus mr-1"></i>AGREGAR</button>
        <hr class='mb-3'>
    `;

    let asignados=creditos.filter(credito=>credito.asignado==false)

    if(asignados.length>0)
    {
        html+=`<div class="table-responsive">
            <table class="table table-hover table-sm" style="width: 100%;" id='t_creditos_noasignados'>
                <thead class="thead-dark">
                    <tr>
                        <th>
                            <button class='btn btn-success' onclick='marcar_todos()' style='padding:0px;padding-left:3px;padding-right:3px;' title='Marcar Todos'><i class="fa-solid fa-square-check"></i></button>
                            <button class='btn btn-danger' onclick='desmarcar_todos()' style='padding:0px;padding-left:3px;padding-right:3px;' title='Marcar Todos'><i class="fa-regular fa-square"></i></button>
                        </th>
                        <th class='d-table-cell d-md-none'>Facturas</th>
                        <th class='d-none d-md-table-cell'># Factura</th>
                        <th class='d-none d-md-table-cell'># ID Interno</th>
                        <th class='d-none d-md-table-cell'>Fecha</th>
                        <th class='text-right d-none d-md-table-cell'>Total</th>
                        <th class='text-right d-none d-md-table-cell'>Saldo</th>
                        <th class='d-none d-md-table-cell'>&nbsp;</th>
                    </tr>
                </thead>
                <tbody>`;
        asignados.forEach(credito => {

            let fecha=credito.fecha.split('-').reverse().join('/');

            html+=`
                <tr onclick='marcar_credito(this)'>
                    <td class='align-middle'>
                        <i class="fa-solid fa-square iconcheckbox"></i>
                        <input type='checkbox' class='d-none' value='${credito.index}'/>
                    </td>
                    <td class='align-middle d-table-cell d-md-none'>
                        <strong># Factura:</strong> ${credito.numero}<br/>
                        <strong>ID Interno</strong> ${credito.idinterno}<br/>
                        <strong>Fecha</strong> ${fecha}<br/>
                        <strong>Total</strong> ${credito.total}<br/>
                        <strong>Saldo</strong> ${credito.saldo}<br/>
                        <td class='text-right d-none d-md-table-cell'><button class='btn btn-success btn-sm' onclick='asignar_credito(${credito.index});llenar_area_asignados()'><i class="fa-solid fa-plus"></i></button></td>
                    </td>
                    <td class='align-middle d-none d-md-table-cell'>${credito.numero}</td>
                    <td class='align-middle d-none d-md-table-cell'>${credito.idinterno}</td>
                    <td class='align-middle d-none d-md-table-cell'>${fecha}</td>
                    <td class='text-right align-middle d-none d-md-table-cell'>Q.${credito.total}</td>
                    <td class='text-right align-middle d-none d-md-table-cell'>Q.${credito.saldo}</td>
                    <td class='text-right d-none d-md-table-cell'><button class='btn btn-success btn-sm' onclick='asignar_credito(${credito.index});llenar_area_asignados()'><i class="fa-solid fa-plus"></i></button></td>
                </tr>`;
        });
        html+=`</tbody></table></div>`;

    } else {
        html+=`<div class="alert alert-danger" role="alert">
        <strong>No hay facturas para asignar</strong>
        </div>`;
    }

    area_creditos.innerHTML=html;
}

function llenar_area_asignados()
{
    let html=`<button class='btn btn-warning btn-sm' onclick='llenar_area_noasignados()'><i class="fa-solid fa-plus mr-1"></i>BUSCAR FACTURAS</button><hr class='mb-3'>`;

    if(creditos_asignados.length>0)
    {
        html+=`<div class="table-responsive">
            <table class="table table-hover table-sm" style="width: 100%;" id='t_creditos_noasignados'>
                <thead class="thead-dark">
                    <tr>
                        <th># Factura</th>
                        <th># ID Interno</th>
                        <th>Fecha</th>
                        <th class='text-right'>Total</th>
                        <th class='text-right'>Saldo</th>
                        <th class='text-right' style='width:150px;'>Abonar</th>                        
                        <th>&nbsp;</th>
                    </tr>
                </thead>
                <tbody>`;
        creditos_asignados.forEach((credito,index) => {

            let fecha=credito.fecha.split('-').reverse().join('/');

            html+=`
                <tr >
                    <td class='align-middle'>${credito.numero}</td>
                    <td class='align-middle'>${credito.idinterno}</td>
                    <td class='align-middle'>${fecha}</td>
                    <td class='text-right align-middle'>Q.${credito.total}</td>
                    <td class='text-right align-middle'>Q.${credito.saldo}</td>
                    <td class='text-right align-middle'>
                        <input type="number" class="form-control text-right bg-warning ml-5" value='${credito.saldo}' min='0' max='${credito.saldo}' step="1" onchange="actualizar_abono(this,${index})" id='abono_${credito.index}' style='width:110px;'/>
                    </td>

                    <td class='text-right' style='width:50px;'><button class='btn btn-danger btn-sm' onclick='eliminar_asignacion_credito(${credito.index}, ${index});llenar_area_asignados()'><i class="fa-solid fa-trash-can"></i></button></td>
                </tr>`;
        });
        html+=`</tbody></table></div>`;

    } else {
        html+=`<div class="alert alert-danger" role="alert">
        <strong>No hay facturas asignadas</strong>
        </div>`;
    }

    area_creditos.innerHTML=html;
    totalizar_abonos();
}

function actualizar_abono(object,index)
{
    creditos_asignados[index].abono=object.value;
    totalizar_abonos();
}

function totalizar_abonos()
{
    let abono=0;
    creditos_asignados.forEach(credito=>{
        abono+=parseFloat(credito.abono);
    })

    abonar_total.value=abono.toFixed(2);
}

function marcar_credito(object)
{
    let icon=object.querySelector('.iconcheckbox');
    let checkbox=object.querySelector('input[type="checkbox"]');
    let button_agregar=document.querySelector('BUTTON#btn_asignar_seleccionados');

    if(checkbox.checked===true)
    {
        object.classList.remove('bg-primary')
        checkbox.checked=false;
        icon.classList.remove('fa-square-check');
        icon.classList.add('fa-square');        
    } else {
        object.classList.add('bg-primary')
        checkbox.checked=true;
        icon.classList.remove('fa-square');
        icon.classList.add('fa-square-check');
    }


    if(document.querySelectorAll('TABLE#t_creditos_noasignados TBODY TR TD input[type="checkbox"]:checked').length>0)
    {
        button_agregar.disabled=false;
    } else {
        button_agregar.disabled=true;
    }
}

function marcar_todos()
{
    let rows=document.querySelectorAll('TABLE#t_creditos_noasignados TBODY TR');
    let button_agregar=document.querySelector('BUTTON#btn_asignar_seleccionados');

    rows.forEach(row=>{
        let icon=row.querySelector('.iconcheckbox');
        let checkbox=row.querySelector('input[type="checkbox"]');
        row.classList.remove('bg-primary');
        row.classList.add('bg-primary');
        icon.classList.remove('fa-square');
        icon.classList.add('fa-square-check');        
        checkbox.checked=true;
    })

    if(document.querySelectorAll('TABLE#t_creditos_noasignados TBODY TR TD input[type="checkbox"]:checked').length>0)
    {
        button_agregar.disabled=false;
    } else {
        button_agregar.disabled=true;
    }    
}

function desmarcar_todos()
{
    let rows=document.querySelectorAll('TABLE#t_creditos_noasignados TBODY TR');
    let button_agregar=document.querySelector('BUTTON#btn_asignar_seleccionados');

    rows.forEach(row=>{
        let icon=row.querySelector('.iconcheckbox');
        let checkbox=row.querySelector('input[type="checkbox"]');
        row.classList.remove('bg-primary');
        icon.classList.remove('fa-square-check');
        icon.classList.add('fa-square');
        checkbox.checked=false;
    })

    if(document.querySelectorAll('TABLE#t_creditos_noasignados TBODY TR TD input[type="checkbox"]:checked').length>0)
    {
        button_agregar.disabled=false;
    } else {
        button_agregar.disabled=true;
    }

}

function asignar_seleccionados()
{
    objects=document.querySelectorAll('TABLE#t_creditos_noasignados TBODY TR TD input[type="checkbox"]:checked');
    if(objects.length>0)
    {
        objects.forEach(object=>{ asignar_credito(object.value) })
        llenar_area_asignados()
    }
}

function asignar_credito(index)
{
    creditos[index].asignado=true;
    creditos[index].abono=creditos[index].saldo;
    creditos_asignados.push({...creditos[index]})
}

function eliminar_asignacion_credito(index,rindex)
{
    creditos[index].asignado=false;
    creditos_asignados.splice(rindex,1)
}

function resetCliente()
{
    buscarCliente.disabled = false;
    buscarCliente.value='';
    id_cliente.value = 1;
    id_cliente_badge.innerHTML = '';
    selectedCliente=false;
    btnProcesar.disabled = true;
    btnProcesar2.disabled = true;
    fecha.disabled = true;
    tipo.disabled = true;
    banco.disabled = true;
    referencias.disabled = true;
    anotacion.disabled = true;    
    area_creditos.innerHTML=`<i class="fa-solid fa-check-double text-warning mr-1"></i><span class='text-warning'>Seleccione el cliente</span>`;
    creditos=[];
    creditos_asignados=[];
    totalizar_abonos();
}

function toggleClientes()
{
    showCliente=!showCliente;

    if(showCliente===true)
    {
        btnClientesHide.classList.remove("d-none")
        btnClientesShow.classList.add("d-none")
        areaCliente.classList.remove("d-none")
        areaClienteMinimizado.classList.add("d-none")
    } else {
        btnClientesHide.classList.add("d-none")
        btnClientesShow.classList.remove("d-none")
        areaCliente.classList.add("d-none")
        areaClienteMinimizado.classList.remove("d-none")

        let nombre_cliente=buscarCliente.value;

        if(nombre_cliente.toString().trim()=='')
        {
            nombre_cliente='No seleccionado';
        } else {
            nombre_cliente+=`<span class="badge bg-success ml-1">${id_cliente.value}</span>`;
        }

        areaClienteMinimizado.innerHTML=`
            <p class='mb-0'>
            <span class='mr-1'><strong>Cliente:</strong> ${nombre_cliente}</span>
            </p>`
    }  
}

function generarAbono(e) {
    e.preventDefault();

    btnProcesar.disabled = true;
    btnProcesar2.disabled = true;

    Swal.fire({
        title: 'Esta seguro de procesar los pagos o abonos?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Si!',
        cancelButtonText: 'No'
    }).then((result) => {

        if (result.isConfirmed) {

            if (creditos_asignados.length < 1) {
                alertas('No hay productos para proceder con el pago o abono', 'warning');
                btnProcesar.disabled = false;
                btnProcesar2.disabled = false;
                return false;
            } else {
                const url = base_url + 'creditoventas/generarAbono';
                const data = new FormData();
                data.append('id_cliente', id_cliente.value);
                data.append('fecha', fecha.value);
                data.append('tipo', tipo.value);
                data.append('banco', banco.value);
                data.append('referencias', referencias.value);
                data.append('observaciones', anotacion.value);
                data.append('monto', abonar_total.value);
                
                data.append('creditos', JSON.stringify(creditos_asignados));
                
                const http = new XMLHttpRequest();
                http.open("POST", url, true);
                http.send(data);
                http.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        
                        const res = JSON.parse(this.responseText);
                        alertas(res.msg, res.icono);
                        setTimeout(() => { window.location.href=base_url + 'creditoventas/abonos'; }, 1000);
/*                        btnProcesar.disabled = false;
                        btnProcesar2.disabled = false;
                        console.log(res);*/
                    }
                }

            }

        } else {
            btnProcesar.disabled = false;
            btnProcesar2.disabled = false;
        }
    })
}
