<div class="accordion accordion-bordered mt-3" id="lineasFactura">

    <div class="card accordion-item active">
        <h2 class="accordion-header" id="headingLineasFacturas">
            <button type="button" class="accordion-button" data-bs-toggle="collapse" data-bs-target="#accordionLineasFacturaTip" aria-expanded="false" aria-controls="accordionLineasFacturaTip">
                <h3><?= lang("Facturas.lineas") ?></h3>
            </button>
        </h2>

        <div id="accordionLineasFacturaTip" class="accordion-collapse collapse show" data-bs-parent="#accordioLineasFactura">
            <div class="accordion-body">

                <table id="tableOfLineasFactura" class="table table-striped table-hover" style="width: 100%;grid-template-columns: 1fr 1fr 6fr 1fr 1fr 1fr;">
                    <thead>
                        <tr>
                            <th style="max-width:60px;"></th>
                            <th>id</th>
                            <th></th>
                            <th></th>
                            <th ></th>
                            <th style="width: 10%;"><?= lang('Facturas.unidades') ?></th>
                            <th ><?= lang('Facturas.concepto') ?></th>
                            <th style="width: 10%;"><?= lang('Facturas.iva') ?></th>
                            <th style="width: 10%;"><?= lang('Facturas.subtotal') ?></th>
                            <th></th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="8" style="text-align:right">Subtotal:</td>
                            <td class="autonumeric text-end" id="subtotal-sum"></td>
                            <td></td>
                            <td></td>
                        </tr>
                        <tr class="d-none">
                            <td colspan="8" style="text-align:right">IVA (4%):</td>
                            <td class="autonumeric text-end" id="total-iva-sum-4"></td>
                            <td></td>
                            <td></td>
                        </tr>
                        <tr class="d-none">
                            <td colspan="8" style="text-align:right">IVA (21%):</td>
                            <td class="autonumeric text-end" id="total-iva-sum-21"></td>
                            <td></td>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="8" style="text-align:right">Total:</td>
                            <td class="autonumeric text-end" id="total-sum"></td>
                            <td></td>
                            <td></td>
                        </tr>
                        <tr>
                            <td <?= ($facturaEntity->serie_id == 7 || $facturaEntity->serie_id == 9)? "style='display:none;'":"" ?> colspan="8" style="text-align:right">Pendiente de pago:</td>
                            <td class="autonumeric text-end" <?= ($facturaEntity->serie_id == 7 || $facturaEntity->serie_id == 9)? "style='display:none;'":"" ?> id="pendiente-pago"></td>
                            <td></td>
                            <td></td>
                        </tr>
                    </tfoot>
                </table>
                <?php if($facturaEntity->estado =='borrador') : ?>
                    <div 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="addLineaFactura"
                                    id="addLineaFactura" >

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


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

const actionBtns = function(data) {
    <?php if ($facturaEntity->estado != 'borrador') : ?> 
        if (data.pedido_id != null) {
            return `
                <div class="text-right py-0 align-middle">
                    <div class="row">
                        <button type="button" class="btn btn-sm btn-primary btn-view_pedido" data-id="${data.pedido_id}">Ver pedido</button>
                    </div>
                </div>
            `;
        } else {
            return ``;
        }
    <?php else: ?>
        if (data.pedido_id === null) {
            return `
                <div class="text-right py-0 align-middle">
                    <div class="row mb-2">
                        <div class="btn-group btn-group-sm">
                            <a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="${data.id}"></i></a>
                            <span class="edit"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="${data.id}"></i></a></span>
                            <span class="cancel"></span>
                        </div>
                    </div>
                </div>
            `;
        } else {
            return `
                <div class="text-right py-0 align-middle">
                    <div class="row mb-2 align-middle">
                        <div class="btn-group btn-group-sm">
                            <a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="${data.id}"></i></a>
                            <span class="edit"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="${data.id}"></i></a></span>
                            <span class="cancel"></span>
                        </div>
                    </div>
                    <div class="row">
                        <button type="button" class="btn btn-sm btn-primary btn-view_pedido" data-id="${data.pedido_id}">Ver pedido</button>
                    </div>
                </div>
            `;
        }
    <?php endif; ?>
};

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

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

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

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

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

var editor_lineas = new $.fn.dataTable.Editor( {
    ajax: {
        url: "<?= route_to('editorOfLineasFacturas') ?>", 
        headers: {
            <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
        },
    },
    table   : "#tableOfLineasFactura",
    idSrc:  'id',
    fields: [ 
        {
            name: "cantidad",
            attr: {
            type: "text",
            name : "cantidad",
            class :"autonumeric"
        }
        }, {
            name: "descripcion",
            type: "textarea",
            attr: {
                rows: 5,
                style: "height: 120px;"
            }
        }, {
            name: "iva",
            attr: {
            type: "text",
            name : "iva",
            class :"autonumeric"
        }
        }, {
            name: "pedido_linea_impresion_id",
            type: "hidden"
        }, {
            name: "pedido_maquetacion_id",
            type: "hidden"
        }, {
            name: "id",
            type: "hidden"
        }, {
            name: "base",
            type: "hidden"
        }, 
    ]
} );


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

        }
        new AutoNumeric(this, {
            decimalCharacter: ",",
            digitGroupSeparator: ".",
            allowDecimalPadding : 'floats',
            decimalPlaces: 2,
            unformatOnSubmit: true,
        });
    })
    })
editor_lineas.on('preSubmit', (e, d, type) => {
    if (d.data) {
        if ( type === 'create'){
            d.data[0]['factura_id'] = <?= $facturaEntity->id ?>;
            d.data[0]['old_cantidad'] = null;
        }
        else if(type === 'edit' ) {
            for (v in d.data){
                d.data[v]['factura_id'] = <?= $facturaEntity->id ?>;
                d.data[v]['old_cantidad'] = old_cantidad;
            }
        }
        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_lineas.on( 'preEdit', function ( e, json, data, id ) {
    
    old_cantidad = data.cantidad;
    
});


editor_lineas.on( 'postSubmit', function ( e, json, data, action ) {
    
    yeniden(json.<?= csrf_token() ?>);
});

editor_lineas.on( 'submitSuccess', function ( e, json, data, action ) {
    
    tableLineas.clearPipeline();
    tableLineas.draw();
});


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

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


var tableLineas = $('#tableOfLineasFactura').DataTable({
    processing: true,
    serverSide: true,
    autoWidth: true,
    responsive: true,
    scrollX: true,
    columns: [
        {
            data: actionBtns,
            className: 'row-edit dt-center'
        },
        {data: "id"},
        {data: "pedido_linea_impresion_id"},
        {data: "pedido_maquetacion_id"},
        {data: "pedido_id"},
        {data: "cantidad",render : (d) => `<span class="autonumeric">${d}</span>`},
        {
            data: "descripcion",
            render: function (data, type, row, meta) {
                
                if(row.pedido_linea_impresion_id != null && <?= (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) ? 0 : 1 ?>){
                    
                    // se convierten a float data.total_aceptado y subtotal
                    var total_aceptado = parseFloat(row.total_aceptado);
                    var subtotal = parseFloat(row.base);

                    var error_text = '';
                    if(total_aceptado != subtotal){
                        error_text = 'El total del pedido ('+ total_aceptado + '€) no coincide con la línea ('+ subtotal + '€)';
                    }

                    var returned_data = `
                        <div>
                            ${data}
                        </div>

                        <div class="mt-5">
                            
                            <span style="color: red;" id="error-${meta.row}">${error_text}</span>
                        </div>

                        <div class="row mt-2">
                            <div style="margin-top: auto;" class="col-md-12 col-lg-2 px-4">
                                <label for="total-aceptado_-${meta.row}">Total aceptado</label>
                                <input readonly class="autonumeric-datatable-lineas" style="max-width: 110px;" type="text" id="total-aceptado_${meta.row}" value="${row.total_aceptado}">
                            </div>
                    `;

                    if (row.tirada_flexible === "1"){
                        returned_data += `
                                <div style="margin-top: auto;" class="col-md-12 col-lg-2 px-4">
                                    <label for="descuento-tf_${meta.row}">Descuento tirada flexible</label>
                                    <input readonly style="max-width: 110px;" type="text" id="descuento-tf_${meta.row}" value="${row.descuento_tirada_flexible}">
                                </div>
                                <div style="margin-top: auto;" class="col-md-12 col-lg-2 px-4">
                                    <label for="tirada-albaran_${meta.row}">Tirada albarán</label>
                                    <input readonly style="max-width: 110px;" type="text" id="tirada-albaran_${meta.row}" value="${row.cantidad_albaran}">
                                </div> 
                        `;
                        if(row.cantidad<row.cantidad_albaran){
                            returned_data += `
                                    
                                    <div style="margin-top: auto;" class="col-md-12 col-lg-2 px-4">
                                    <button  
                                            type="button"
                                            class="btn btn-label-primary float-start me-sm-3 me-1 btn-excedentes"
                                            name="btn-excedentes_${meta.row}"
                                            id="btn-excedentes_${meta.row}" 
                                            data-row="${meta.row}"
                                        >
                                        <span class="ti-xs ti ti-circle-plus me-1"></span>    
                                        Excedentes
                                    </button>
                                    </div>
                                </div>   
                            `;
                        }
                        else{
                            returned_data += `
                                </div>   
                            `;
                        }
                    }
                    else{
                        returned_data += `
                            </div>
                        `;
                    }

                    return returned_data;
                }
                else{
                    return `
                        <div>
                            ${data}
                        </div>
                        `;
                }
            }
        },
        {data: "iva", className: "text-end", render : (d) => `<span class="autonumeric-facturas text-end">${d}</span>`},
        {data: "base", className: "text-end", render : (d) => `<span class="autonumeric-facturas text-end">${d}</span>`},
        {data: "total_iva", className: "text-end",render : (d) => `<span class="autonumeric-facturas text-end">${d}</span>`},
        {data: "total", className: "text-end", render : (d) => `<span class="autonumeric-facturas text-end">${d}</span>`},
    ],
    order: [[1, "asc"]],
    dom: 't',
    language: {
        url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
    },
    ajax : $.fn.dataTable.pipeline( {
        url: '<?= route_to('dataTableOfLineasFacturas', $facturaEntity->id) ?>',
        method: 'POST',
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        async: true,
    }),
    columnDefs: [
        {
            orderable: false,
            searchable: false,
            targets: [0]
        },
        {
            visible: false,
            targets: [1, 2, 3, 4, 9, 10]
        }

    ], 
    drawCallback: function() {
        $(this.api().table().container()).find('table').css('width', '100%');
        this.api().columns.adjust();

        $('.autonumeric-datatable-lineas').each(function() {
            if (!$(this).data('autoNumeric')) {
                new AutoNumeric(this, {
                    decimalPlaces: 2,
                    digitGroupSeparator: '.',
                    decimalCharacter: ',',
                    unformatOnSubmit: true
                });
            }
        });

        $("span.autonumeric-facturas").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) {
        const table = this.api();

        const totalSubtotal = table.column(8).data().reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
        
        const data_table = table.rows().data();
        const totalIVA_4 = data_table.reduce((sum, row) => {
            if (parseInt(row['iva']) === 4) {
                return sum + parseFloat(row['total_iva']) || 0;
            }
            return sum;
            }, 0);
        const totalIVA_21 = data_table.reduce((sum, row) => {
            if (parseInt(row['iva']) === 21) {
                return sum + parseFloat(row['total_iva']) || 0;
            }
            return sum;
            }, 0);
        
        const totalTotal = table.column(10).data().reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
 
        autoNumericSubtotal.set(totalSubtotal);
        autoNumericIVA_4.set(totalIVA_4);
        if(totalIVA_4 == 0){
            $('#total-iva-sum-4').closest('tr').addClass('d-none');
        }
        else{
            $('#total-iva-sum-4').closest('tr').removeClass('d-none');
        }
        autoNumericIVA_21.set(totalIVA_21);
        if(totalIVA_21 == 0){
            $('#total-iva-sum-21').closest('tr').addClass('d-none');
        }
        else{
            $('#total-iva-sum-21').closest('tr').removeClass('d-none');
        }
        autoNumericTotal.set(totalTotal);

        var total_pagos = autoNumericTotalCobrado.getNumber();
        var pendientePago = totalTotal - total_pagos;
    
        if (isNaN(pendientePago)) pendientePago = 0;

        autoNumericPendientePago.set(pendientePago);

        $.ajax({
            url: '<?= route_to('updateFacturaTotales', $facturaEntity->id) ?>',
            method: 'POST',
            data: {
                base: totalSubtotal,
                total: totalTotal,
                total_pagos: total_pagos,
                pendiente: pendientePago,
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v
            }
        }).done(function (data) {
            if (data.estado_pago === 'pagada') {
                $('#estado_pago_text').text('<?= lang('Facturas.pagada') ?>').css('color', 'green');
            } else {
                $('#estado_pago_text').text('<?= lang('Facturas.pendiente') ?>').css('color', 'red');
            }
        }).fail(function (jqXHR) {
            popErrorAlert(jqXHR.responseJSON.messages.error);
        });
    }

});


// Delete row
$(document).on('click', '.btn-delete', function(e) {
    
    const dataId = $(this).attr('data-id');
    const row = $(this).closest('tr');
    if ($.isNumeric(dataId)) {
        asyncConfirmDialogWithParams(
            "Borrar Linea de Factura",
            "¿Está seguro de borrar la línea? Esta acción no se puede deshacer.",
            deleteConfirmedLinea, function(){}, [dataId, row])
    }
});


function deleteConfirmedLinea(params){
    var factura_linea_id = params[0];
    var row = params[1];
    const row_data = tableLineas.row($(row)).data();

    if(row_data.pedido_linea_impresion_id != null){
        var url = '<?= route_to('deleteLineaPedidoImpresion') ?>';
        $.ajax({
            url: url,
            method: 'POST',
            data: {
                factura_id: <?= $facturaEntity->id ?>,
                pedido_linea_impresion_id: row_data.pedido_linea_impresion_id,
                cantidad: row_data.cantidad,
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v
            }
        }).done((data, textStatus, jqXHR) => {
            tablelineas.clearPipeline().footerCallback().draw();
            $('#tableOfLineasPagos').DataTable().clearPipeline().footerCallback().draw();
           
        }).fail((jqXHR, textStatus, errorThrown) => {
            popErrorAlert(jqXHR.responseJSON.messages.error)
        })    
    }


    var url = '<?= route_to('deleteLineaFactura', ':id') ?>';
    url = url.replace(':id', factura_linea_id );
    $.ajax({
            url: url,
            method: 'GET',
        }).done((data, textStatus, jqXHR) => {
            $('#tableOfLineasFactura').DataTable().clearPipeline();
            $('#tableOfLineasFactura').DataTable().row($(row)).invalidate().draw();
        }).fail((jqXHR, textStatus, errorThrown) => {
            popErrorAlert(jqXHR.responseJSON.messages.error)
        })
}

$(document).on('click', '.btn-view_pedido', function(e) {
    var pedido_id = $(this).data('id');
    var url = '<?= route_to('editarPedido', ':id') ?>';
    url = url.replace(':id', pedido_id );
    
    window.open(url, '_blank');
});


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


$(document).on('click', '.btn-excedentes', function(e) {
    const row = $(this).data('row');
    const row_data = tableLineas.row(row).data();
    
    const pedido_id = row_data.pedido_id;

    var pedido_linea_impresion_id = null;
    var pedido_linea_maquetacion_id = null;
    
    if(row_data.pedido_linea_impresion_id != null){
        pedido_linea_impresion_id = row_data.pedido_linea_impresion_id
    }
    else{
        pedido_linea_maquetacion_id = row_data.pedido_maquetacion_id
    }

    var factura_id = <?= $facturaEntity->id ?>;

    var url = '<?= route_to('addLineaExcedentes', ':factura_id') ?>';
    url = url.replace(':factura_id', factura_id );
    
    $.ajax({
        url: url,
        method: 'POST',
        data: {
            pedido_id: pedido_id,
            pedido_linea_impresion_id: pedido_linea_impresion_id,
            pedido_linea_maquetacion_id: pedido_linea_maquetacion_id,
            descripcion: row_data.descripcion,
            iva: row_data.iva,
            descuento: row_data.descuento_tirada_flexible,
            cantidad: parseInt(row_data.cantidad_albaran)-parseInt(row_data.cantidad),
            <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v
        }
    }).done((data, textStatus, jqXHR) => {
        $('#tableOfLineasFactura').DataTable().clearPipeline();
        $('#tableOfLineasFactura').DataTable().draw();
    }).fail((jqXHR, textStatus, errorThrown) => {
        popErrorAlert(jqXHR.responseJSON.messages.error)
    })
});

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