let t_h_v;

let active_row=false;
let active_obj=false;

let total_ventas = document.getElementById('total_ventas');
let fecha_min = document.getElementById('min');
let fecha_max = document.getElementById('max');
let estaciones = document.getElementById('estaciones');

document.addEventListener('DOMContentLoaded', function () {

    t_h_v = $('#t_ventas').DataTable({

        "processing": true,
        "serverSide": true,
        "deferRender" : true,
        "sAjaxSource": "" + base_url + 'valescred/listar_facturas',

        "fnServerParams": function ( aoData ) {
            aoData.push( { "name": "estaciones", "value": estaciones.value },
                         { "name": "fecha_desde", "value": fecha_min.value},
                         { "name": "fecha_hasta", "value": fecha_max.value},)
        },

        "type": 'POST',

        "columnDefs": [
            {
                targets: 5,
                render:function ( data, type, row, meta ) {

                    if (data == 1) {
                        return '<span class="badge badge-info">Contado</span>';
                    } else {
                        return '<span class="badge badge-warning">Credito</span>';
                    }                    

                }
            },
            {
                targets: 6,
                render:function ( data, type, row, meta ) {
                    let metodo = row[5];
                    let estado = row[6];

                    if (estado == 1 && metodo == 1) {
                        return '<span class="badge badge-success">Pagado</span>';
                    } else if (estado == 1 && metodo == 2) {
                        return '<span class="badge badge-warning">Pendiente</span>';
                    } else if (estado == 2 && metodo == 2) {
                        return '<span class="badge badge-success">Completado</span>';
                    } else {
                        return '<span class="badge badge-danger">Anulado</span>';
                    }
                }
            },            
            {   
                responsivePriority: 30000, 
                targets: -2, 
            },
            { responsivePriority: 30000, targets: -1 },
        ],
        "drawCallback": function () {
                let api = this.api();

                /*$(api.columns(2).footer()).html(
                    formatMoneyGTQ(Number(api.ajax.json().total).toFixed(2))
                )*/
                total_ventas.innerHTML = '<strong>TOTAL VENTAS:</strong> '+ formatMoneyGTQ(Number(api.ajax.json().total).toFixed(2));

            },
        "dom": "<'row'<'col-sm-4'l><'col-sm-4 text-center'B><'col-sm-4'f>>" +
            "<'row'<'col-sm-12'tr>>" +
            "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        buttons,
        language,
        "resonsieve": true,
        "responsive": true,
        "bDestroy": true,
        "iDisplayLength": 10,
        "order": [
            [0, "desc"]
        ],


    });

    t_h_v.on( 'draw', function () {
        $('#t_ventas tbody tr').removeClass('selected');
        activo_buttons(false)
    } );

    $('#t_ventas tbody').on( 'click', 'tr', function (e) {
        let classList = e.currentTarget.classList;
       
        if (classList.contains('selected')) {
            classList.remove('selected');
        }
        else {
           t_h_v.rows('.selected').nodes().each((row) => row.classList.remove('selected'));
            classList.add('selected');
        }
        activo_buttons( t_h_v.row( this ).data()  );
    } );

    estaciones.onchange = function () { t_h_v.draw(); }
    fecha_min.onchange = function () { t_h_v.draw(); }
    fecha_max.onchange = function () { t_h_v.draw(); }


    function activo_buttons(obj)
    {
        active_obj=obj;
        active_row=active_obj.id;

        if($('#t_ventas tbody tr.selected').length==0)
        {
            $('BUTTON.btn-toolbar-status').attr('disabled', 'disabled');
            $('BUTTON.btn-recuperar').hide();
            $('BUTTON.btn-eliminar').show();            
        } else {
            $('BUTTON.btn-toolbar-status').removeAttr('disabled');
            if(active_obj.estado_txt==='pagado' || active_obj.estado_txt==='pendiente') {
                $('BUTTON.btn-anular').show();
            } else {
                $('BUTTON.btn-anular').hide();
            }
            
            if(active_obj.autorizacion_estado===true) {
                $('BUTTON.btn-autorizar').show();
            } else {
                $('BUTTON.btn-autorizar').hide();
            }   
        }
    }
    

    $('#min').change(function (e) {
        t_h_v.draw();
    });
    //Busqueda por Rango de Fechas DataTables - Hasta
    $('#max').change(function (e) {
        t_h_v.draw();
    });
})
function btnAnular(id) {
    Swal.fire({
        title: 'Esta seguro de anular la Venta?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Si!',
        cancelButtonText: 'No'
    }).then((result) => {
        if (result.isConfirmed) {
            const url = base_url + 'ventas/anular/' + id;
            console.log(base_url + 'ventas/anular/' + id)
            const http = new XMLHttpRequest();
            http.open("GET", url, true);
            http.send();
            http.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    const res = JSON.parse(this.responseText);
                    alertas(res.msg, res.icono);
                    t_h_v.ajax.reload();
                }
            }
        }
    })
}
function btnFacturarFel(id)
{
    Swal.fire({
        title: 'Esta seguro de facturar la Venta?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Si!',
        cancelButtonText: 'No'
    }).then((result) => {
        if (result.isConfirmed) {
            const url = base_url + 'ventas/registrarFactura/' + id;
            const http = new XMLHttpRequest();
            http.open("GET", url, true);
            http.send();
            http.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    const res = JSON.parse(this.responseText);
                    if(res.icono=='success')
                    {
                        alertas(res.msg, res.icono);
                        t_h_v.ajax.reload();
                        //generar PDF                        
                    } else {
                        alerta_permanent(res.msg, res.icono);
                    }
                }
            }
        }
    })
}

function formatMoneyGTQ(amount) {
    return new Intl.NumberFormat('es-GT', { style: 'currency', currency: 'GTQ' }).format(amount);
}