<div class="accordion accordion-bordered mt-3" id="pagosFacturas">
    <div class="card accordion-item active">
        <h2 class="accordion-header" id="headingPagosFacturas">
            <button type="button" class="accordion-button" data-bs-toggle="collapse" data-bs-target="#accordionPagosFacturaTip" aria-expanded="false" aria-controls="accordionPagosFacturaTip">
                <h3><?= lang("Facturas.pagos") ?></h3>
            </button>
        </h2>
        <div id="accordionPagosFacturaTip" class="accordion-collapse collapse show" data-bs-parent="#pagosFacturas">
            <div class="accordion-body">
                <table id="tableOfLineasPagos" class="table table-striped table-hover" style="width: 100%; grid-template-columns: 1fr 2fr 6fr 1fr 1fr 1fr;"">
                    <thead>
                        <tr>
                            <th style="max-width:30px;"></th>
                            <th></th>
                            <th><?= lang('Facturas.formaPago') ?></th>
                            <th><?= lang('Facturas.notas') ?></th>
                            <th><?= lang('Facturas.fechaVencimiento') ?></th>
                            <th><?= lang('Facturas.fechaCobro') ?></th>
                            <th><?= lang('Facturas.cantidad') ?></th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                    <tfoot>
                        <tr>
                            <td colspan="6" class="text-end">Total cobrado:</td>
                            <td class="text-end"><span id="totalCobrado-sum" class="autonumeric  text-end"></span></td>
                        </tr>
                        <tr>
                            <td colspan="6" class="text-end">Total pendiente:</td>
                            <td class="text-end"><span id="pendienteCobro-sum" class="autonumeric text-end"></span></td>
                        </tr>
                    </tfoot>
                </table>

                <?php if(!(auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor'))) : ?>
                <div id="addPagoRow" class="row">
                    <div class="col-md-12 col-lg-2">    
                        <button  
                                type="button"
                                class="btn btn-label-primary float-start me-sm-3 me-1"
                                name="addPagoFactura"
                                id="addPagoFactura" >

                            <?= lang("Facturas.addPago") ?>
                        </button>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>


<?=$this->section('additionalInlineJs') ?>

const formas_pago = <?= json_encode($facturaEntity->formas_pago) ?>;
var formaPagoLookup = {};
formas_pago.forEach(function(pago) {
  formaPagoLookup[pago.value] = pago.label;
});

const actionBtns_pagos = function(data) {
    <?php if(!(auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor'))) : ?>
    return `
        <div class="btn-group btn-group-sm">
            <a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete-pago mx-2" data-id="${data.id}"></i></a>
            <span class="edit-pago"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit-pago mx-2" data-id="${data.id}"></i></a></span>
            <span class="cancel-pago"></span>
        </div>`;
    <?php else: ?>
    return '';
    <?php endif; ?>
}

const editor_pagos = new $.fn.dataTable.Editor( {
    ajax: {
        url: "<?= route_to('editorOfPagosFacturas') ?>", 
        headers: {
            <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
        },
    },
    table   : "#tableOfLineasPagos",
    idSrc:  'id',
    fields: [ 
        {
            name: "forma_pago_id",
            type: "select",
            options: formas_pago,
        }, 
        {
            name: "notes",
            type: "textarea",
            attr: {
                rows: 5,
                style: "height: 120px;"
            }
        }, 
        {
            name: "total",
            attr: {
                style: "min-width: 65px;",
                class :"autonumeric",
                name: 'total'
            },
        }, 
        {
            name: "fecha_pago_at",
            type: "datetime",
            def: function () {
                return new Date().toISOString().split('T')[0]; // YYYY-MM-DD
            },
            wireFormat: 'YYYY-MM-DD HH:mm:ss',
            displayFormat: 'DD/MM/YYYY',
        }, 
        {
            name: "fecha_vencimiento_at",
            type: "datetime",
            def: () => new Date(),
            def: function () {
                return new Date().toISOString().split('T')[0]; // YYYY-MM-DD
            },
            wireFormat: 'YYYY-MM-DD HH:mm:ss',
            displayFormat: 'DD/MM/YYYY',
        }, 
        {
            name: "id",
            type: "hidden"
        }, 
        {
            name: "factura_id",
            type: "hidden"
        }, 
    ]
});

editor_pagos.on('open',(event)=>{
    $("input.autonumeric").each(function () {
        let autoNumericInstance = AutoNumeric.getAutoNumericElement(this)
        if(autoNumericInstance){
            autoNumericInstance.remove()

        }
        new AutoNumeric(this, {
            digitGroupSeparator: ".",
            decimalCharacter: ",",
            allowDecimalPadding : 'floats',
            decimalPlaces: 2,
            unformatOnSubmit: true,
            decimalPlacesShownOnFocus: 2,
            decimalPlacesShownOnBlur: 2,

        });
    })
})

editor_pagos.on( 'preSubmit', function ( e, d, type ) {
    
    if (d.data) {
        if ( type === 'create'){
            d.data[0]['factura_id'] = <?= $facturaEntity->id ?>;
        }
        else if(type === 'edit' ) {
            for (v in d.data){
                d.data[v]['factura_id'] = <?= $facturaEntity->id ?>;
            }
        }
        Object.keys(d.data).forEach(function (key) {
            // Find all elements with class .autonumeric
            $("input.autonumeric").each(function () {
                let autoNumericInstance = AutoNumeric.getAutoNumericElement(this)
                if (autoNumericInstance) {
                    // Get raw value and update the corresponding field
                    let rawValue = autoNumericInstance.getNumericString();
                    d.data[key][this.name] = rawValue; // Ensure the correct name attribute is used
                }
            });
        });
    }
});


editor_pagos.on( 'postSubmit', function ( e, json, data, action ) {
    
    yeniden(json.<?= csrf_token() ?>);
    tablePagos.clearPipeline();
    tablePagos.draw();
    updateFooterLineas(tableLineas);
});

const autoNumericTotalCobrado = new AutoNumeric('#totalCobrado-sum', 0, {
    decimalPlaces: 2,
    digitGroupSeparator: ',',
    decimalCharacter: '.',
    unformatOnSubmit: true,
    decimalPlacesShownOnFocus: 2,
    decimalPlacesShownOnBlur: 2,
});

const autoNumericPendienteCobro = new AutoNumeric('#pendienteCobro-sum', 0, {
    decimalPlaces: 2,
    digitGroupSeparator: ',',
    decimalCharacter: '.',
    unformatOnSubmit: true,
    decimalPlacesShownOnFocus: 2,
    decimalPlacesShownOnBlur: 2,
});

var tablePagos = $('#tableOfLineasPagos').DataTable({
    processing: true,
    serverSide: true,
    autoWidth: true,
    responsive: true,
    scrollX: true,
    columns: [
        {
            data: null,
            render: actionBtns_pagos,
            className: 'row-edit dt-center'
        },
        {data: "id"},
        {
            data: "forma_pago_id",
            render: function(data, type, row) {
                return formaPagoLookup[data] || data;
            }
        },
        {data: "notes"},
        {
            data: "fecha_vencimiento_at",
            render: function(data, type, row) {
                if(data == null){
                    return '';
                }
                return data!='0000-00-00 00:00:00' ? moment(data).format('DD/MM/YYYY') : '';
            }
        },
        {
            data: "fecha_pago_at",
            render: function(data, type, row) {
                if(data == null){
                    return '';
                }
                return data!='0000-00-00 00:00:00' ? moment(data).format('DD/MM/YYYY') : '';
            }
        },
        {
            data: "total",
            className: "text-end", 
            render : (d) => `<span class="autonumeric-pagos text-end">${d}</span>`
        },
    ],
    order: [[1, "asc"]],
    dom: 't',
    language: {
        url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
    },
    ajax: {
        url: '<?= route_to('dataTableOfPagosFacturas', $facturaEntity->id) ?>',
        method: 'POST',
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        async: true,
    },
    columnDefs: [
        {
            orderable: false,
            searchable: false,
            targets: [0]
        },
        {
            visible: false,
            targets: [1]
        },
        {
            width: '40%', // Ajusta el ancho para la columna de notas
            targets: 3
        },
        {
            width: '10%', // Ajusta el ancho para la columna de notas
            targets: [4, 5, 6]
        },
        
    ],
    drawCallback: function (settings) {
        $("span.autonumeric-pagos").each(function () {
            let autoNumericInstance = AutoNumeric.getAutoNumericElement(this)
            if(autoNumericInstance){
                autoNumericInstance.remove()
            }
            new AutoNumeric(this, {
                digitGroupSeparator: ".",
                decimalCharacter: ",",
                allowDecimalPadding : 'floats',
                decimalPlaces: 2,
                unformatOnSubmit: true,
                decimalPlacesShownOnFocus: 2,
                decimalPlacesShownOnBlur: 2,
                allowDecimalPadding: true,
            });
        });
    },
    footerCallback: function (row, data, start, end, display) {
        var api = this.api();

        var filas = [];
        api.rows().every(function() {
            var data = this.data();
            if (data['fecha_pago_at'] !== undefined && data['fecha_pago_at'] !== null && data['fecha_pago_at'] !== '') {
                filas.push(data); // Agregar la fila a la variable
            }
        });
        var totalPagos = filas
            .reduce(function(a, data) {
                return parseFloat(a) + parseFloat(data['total']); 
            }, 0);

        var filas = [];
        api.rows().every(function() {
            var data = this.data();
            if (data['fecha_pago_at'] === undefined || data['fecha_pago_at'] === null || data['fecha_pago_at'] === '') {
                filas.push(data); // Agregar la fila a la variable
            }
        });
        var totalPendiente = filas
            .reduce(function(a, data) {
                return parseFloat(a) + parseFloat(data['total']); 
            }, 0);

        // Update footer
        autoNumericTotalCobrado.set(totalPagos);
        autoNumericPendienteCobro.set(totalPendiente);

        // call footerCallback of the other table
        if (typeof tableLineas !== 'undefined') {
            updateFooterLineas(tableLineas);
        }
    }
});


function updateFooterLineas(table){

    // Assuming pendiente de pago is totalTotal - totalIVA for this example
    var total_pagos = autoNumericTotalCobrado.getNumber();
    var pendientePago = autoNumericTotal.getNumber() - total_pagos;
    // Se comprueba si pendientePago es un numero o NAN
    if(isNaN(pendientePago)){
        pendientePago = 0;
    }
    autoNumericPendientePago.set(pendientePago);

    $.ajax({
        url: '<?= route_to('updateFacturaTotales', $facturaEntity->id) ?>',
        method: 'POST',
        data: {
            base: autoNumericSubtotal.getNumber(),
            total: autoNumericTotal.getNumber(),
            total_pagos: total_pagos,
            pendiente: pendientePago
        }
    }).done((data, textStatus, jqXHR) => {
        if(autoNumericPendientePago.getNumber() == 0){
            $('#addPagoRow').hide();
        } else {
            $('#addPagoRow').show();
        }
        if(data.estado_pago == 'pagada'){
            $('#estado_pago_text').text('<?= lang('Facturas.pagada') ?>');
            $('#estado_pago_text').css('color', 'green');
        }
        else{
            $('#estado_pago_text').text('<?= lang('Facturas.pendiente') ?>');
            $('#estado_pago_text').css('color', 'red');
        }
    }).fail((jqXHR, textStatus, errorThrown) => {
        popErrorAlert(jqXHR.responseJSON.messages.error)
    })
}


$('#addPagoFactura').on('click', function () {
    const formOptions= {
        submitTrigger: 0,
        submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'
        
    };
    editor_pagos.inlineCreate('end', formOptions);
});


// Activate an inline edit on click of a table cell
$('#tableOfLineasPagos').on( 'click', 'tbody span.edit-pago', function (e) {

    editor_pagos.inline(tablePagos.cells(this.closest('tr'), '*').nodes(), 
    {
    
            cancelHtml: '<a href="javascript:void(0);"><i class="ti ti-x"></i></a>',
            cancelTrigger: 'span.cancel-pago',
            submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>',
            submitTrigger: 'span.edit-pago',
            submit: 'allIfChanged'
        } 
    );
} );


<?=$this->endSection() ?>