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

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

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


                <div id="bonotes_albaranes" class="col-12 d-flex flex-row-reverse mt-4 gap-2">
                    <div id="generar_albaranes" class="btn mt-3 btn-success waves-effect waves-light ml-2">
                        <span class="align-middle d-sm-inline-block d-none me-sm-1"><?= lang('Pedidos.generarAlbaranes') ?></span>
                        <i class="ti ti-player-play ti-xs"></i>
                    </div>

                    <div id="borrar_albaranes" class="btn mt-3 btn-danger waves-effect waves-light ml-2">
                        <span class="align-middle d-sm-inline-block d-none me-sm-1"><?= lang('Pedidos.borrarAlbaranes') ?></span>
                        <i class="ti ti-trash ti-xs"></i>
                    </div>
                </div>
                
            </div> <!-- /.accordion-body -->
        </div>
    </div>
</div>


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

$('#generar_albaranes').on('click', function(){

    var lineasPedido = $('#tableOfLineasPedido').DataTable();
    var presupuestos = lineasPedido.column(0).data().unique().toArray();
    
    $.ajax({
        url: '<?= route_to('crearAlbaranesPedido') ?>',
        type: 'POST',
        data: {
            pedido_id: <?= $pedidoEntity->id ?>,
            presupuestos_id: presupuestos,
            <?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
        },
        success: function(response){
            
            if(response.data.length > 0){
                Object.values(response.data).forEach(function(item){
                    generarAlbaran(item);
                });
            }
        }
    });
})

const deleteLineaBtns = function(data) {
    return `
        <td class="text-right py-0 align-middle">
            <div class="btn-group btn-group-sm">
                <a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete-linea mx-2" data-id="${data.id}"></i></a>
            </div>
        </td>`;
};

function generarAlbaran(item){

    // Crear los elementos necesarios
    const accordion = $('<div>', {
        class: 'accordion accordion-bordered mt-3 accordion-albaran',
        id: 'accordioAlbaran' + item.albaran.id,
        albaran: item.albaran.id
    });

    const card = $('<div>', {
        class: 'card accordion-item active'
    });

    const header = $('<h2>', {
        class: 'accordion-header',
        id: 'headingAlbaran' + item.albaran.id
    });

    const button = $('<button>', {
        type: 'button',
        class: 'accordion-button collapsed',
        'data-bs-toggle': 'collapse',
        'data-bs-target': '#accordionAlbaranTip' + item.albaran.id,
        'aria-expanded': 'false',
        'aria-controls': 'accordionAlbaranTip'  + item.albaran.id,
        'albaran': item.albaran.id,
    }).css({
        'background-color': '#F0F8FF'
    });

    const h3 = $('<h5>').html(item.albaran.numero_albaran); 

    const collapseDiv = $('<div>', {
        id: 'accordionAlbaranTip' + item.albaran.id,
        class: 'accordion-collapse collapse',
        'data-bs-parent': '#accordioAlbaran' + item.albaran.id
    });

    const body = $('<div>', {
        class: 'accordion-body'
    });

    const cabecera = 
    `
        <div class="col-12 d-flex justify-content-between mb-3">
            <div class="col-6 d-flex flex-row">
                <div class="col-2">
                    <label><?= lang('Pedidos.fecha') ?>:</label>
                </div>
                <div class="col-2">
                    <label>${item.albaran.fecha_albaran}</label>
                </div>
            </div>  
            <div class="col-6 d-flex flex-row-reverse">
                <div class="col-2">
                    <label style="text-align: right; display:block">${item.albaran.pedido_id}</label>    
                </div>
                <div class="col-2">
                    <label style="text-align: right"><?= lang('Pedidos.pedido') ?>:</label>    
                </div>
            </div>  
        </div>
        <div class="col-12 d-flex justify-content-between mb-3">
            <div class="col-6 d-flex flex-row">
                <div class="col-2">
                    <label><?= lang('Pedidos.cliente') ?>:</label>
                </div>
                <div class="col-4">
                    <label>${$('#cliente').val()}</label>
                </div>
            </div>  
            <div class="col-6 d-flex flex-row-reverse">
                <div class="col-2">
                    <label style="text-align: right; display:block">${item.albaran.numero_albaran}</label>    
                </div>
                <div class="col-2">
                    <label style="text-align: right"><?= lang('Pedidos.albaran') ?>:</label>    
                </div>
            </div>  
        </div>
        <div class="col-12 d-flex justify-content-between mb-3">
            <div class="col-1">
                <label><?= lang('Pedidos.att') ?>:</label>
            </div>
            <div class="col-11">
                <input id="att_${item.albaran.id}" class="cambios-albaran form-control" albaran_id=${item.albaran.id} value="${item.albaran.att_albaran}" class="form-control"></input>
            </div>
        </div>
        <div class="col-12 d-flex justify-content-between mb-3">
            <div class="col-1">
                <label><?= lang('Pedidos.direccion') ?>:</label>
            </div>
            <div class="col-11">
                <input id="direccion_${item.albaran.id}" albaran_id=${item.albaran.id} value="${item.albaran.direccion_albaran}" class="cambios-albaran form-control"></input>
            </div>
        </div>
    `;

    const table = $('<table>', 
        { id: 'tablaAlbaran' + item.albaran.id, width:'100%', class: 'table table-responsive table-striped table-hover' })
        .css({
            'width': '100%',
        }).append(
        $('<thead>').append(
            $('<tr>').append(
                $('<th>').css({'max-width':'20px'}),
                $('<th>'),
                $('<th>', { class:'lp-header', scope: 'col' }).css({'font-size':'smaller'}).text('Unidades'),
                $('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('Título'),
                $('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('ISBN'),
                $('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('Ref. Cliente'),
                $('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('Cajas'),
                $('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('Ej./Cajas'),
                $('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('€/u'),
                $('<th>', { class:'lp-header',scope: 'col' }).css({'font-size':'smaller'}).text('Subtotal')
            )
        ),
        $('<tbody>'),
        $('<tfoot>').append(
            $('<tr>').append(
                $('<th>', { colspan: '9', style: 'text-align:right' }).text('')    
            )
        ),
    );

    let isChecked = item.albaran.mostrar_precios == 1 ? 'checked' : '';
    const botones_albaran = 
    `   
        <div class="row mt-1">
            <div id="div_mostrar_precios_${item.albaran.id}"  class="col-2 d-flex flex-row gap-2">
                <div class="d-flex align-items-center">
                    <label><?= lang('Pedidos.mostrarPrecios') ?>:</label>
                </div>
                <div class="d-flex align-items-center">
                    <input type="checkbox" id="mostrar_precios" name="mostrar_precios" albaran_id=${item.albaran.id}  class="mostrar-precios custom-control-input" ${isChecked} >
                </div>
            </div>
            <div id="bonotes_albaran_${item.albaran.id}"  class="col-10 d-flex flex-row-reverse gap-2">
                <div id="borrar_albaran_${item.albaran.id}" class="borrar-albaran  btn mt-3 button-albaran btn-label-danger waves-effect waves-light ml-2">
                    <span class="align-middle d-sm-inline-block d-none me-sm-1"><?= lang('Pedidos.borrarAlbaran') ?></span>
                    <i class="ti ti-trash ti-xs"></i>
                </div>

                <div id="imprimir_albaran_${item.albaran.id}"  class="imprimir-albaran btn mt-3 btn-label-secondary button-albaran  waves-effect waves-light ml-2">
                    <span class="align-middle d-sm-inline-block d-none me-sm-1"><?= lang('Pedidos.imprimirAlbaran') ?></span>
                    <i class="ti ti-printer ti-xs"></i>
                </div>
                <div id="nueva_linea_albaran_${item.albaran.id}"  class="nueva-linea-albaran btn mt-3 btn-label-secondary button-albaran waves-effect waves-light ml-2">
                    <span class="align-middle d-sm-inline-block d-none me-sm-1"><?= lang('Pedidos.nuevaLinea') ?></span>
                    <i class="ti ti-plus ti-xs"></i>
                </div>
                <div id="add_iva_albaran_${item.albaran.id}"  class="add-iva-albaran btn mt-3 btn-label-secondary button-albaran waves-effect waves-light ml-2">
                    <span class="align-middle d-sm-inline-block d-none me-sm-1"><?= lang('Pedidos.addIva') ?></span>
                    <i class="ti ti-plus ti-xs"></i>
                </div>
            </div>
        </div>
    `;

    // Armar la estructura
    button.append(h3);
    header.append(button);
    card.append(header);
    collapseDiv.append(body);
    body.append(cabecera);
    body.append(table);
    body.append(botones_albaran);
    card.append(collapseDiv);
    accordion.append(card);

    // Agregar el elemento al accordioAlbaranes
    $('#bonotes_albaranes').before(accordion); 

    

    const datatableAlbaran = new DataTable('#tablaAlbaran' + item.albaran.id,{
        scrollX: true,
        searching: false,
        paging: false,
        info: false,
        ordering: false,
        responsive: true,
        select: false,
        dom: 't',
        language: {
            url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
        },
        columns: [
            { data: 'id'},
            {
                data: deleteLineaBtns,
                className: 'dt-center'
            },
            {   
                data: 'cantidad', 
                render: function ( data, type, row, meta ) {
             
                    var input = $('<input>', {
                        id:  'cantidad_' + row.id,
                        name: 'cantidad_' + row.id,
                        class: 'lp-cell lp-input albaran_linea',
                        albaran: item.albaran.numero_albaran,
                        type: 'text',
                        value: data,
                        linea: row.id
                    }).css({
                        'text-align': 'center',
                        'font-size': 'smaller',
                        'max-width': '50px'
                    });
                    return input.prop('outerHTML');
                }
            },
            {   
                data: 'titulo', 
                render: function ( data, type, row, meta ) {
             
                    var input = $('<input>', {
                        id:  'titulo_' + row.id,
                        name: 'titulo_' + row.id,
                        class: 'lp-cell lp-input albaran_linea',
                        albaran: item.albaran.numero_albaran,
                        type: 'text',
                        value: data,
                        linea: row.id
                    }).css({
                        'text-align': 'center',
                        'font-size': 'smaller',
                        'min-width': '300px'
                    });
                    return input.prop('outerHTML');
                }
            },
            {   
                data: 'isbn', 
                render: function ( data, type, row, meta ) {
             
                    var input = $('<input>', {
                        id:  'isbn_' + row.id,
                        name: 'isbn_' + row.id,
                        class: 'lp-cell lp-input albaran_linea',
                        albaran: item.albaran.numero_albaran,
                        type: 'text',
                        value: data,
                        linea: row.id
                    }).css({
                        'text-align': 'center',
                        'font-size': 'smaller'
                    });
                    return input.prop('outerHTML');
                }
            },
            {   
                data: 'ref_cliente', 
                render: function ( data, type, row, meta ) {
             
                    var input = $('<input>', {
                        id:  'ref_cliente_' + row.id,
                        name: 'ref_cliente_' + row.id,
                        class: 'lp-cell lp-input albaran_linea',
                        albaran: item.albaran.numero_albaran,
                        type: 'text',
                        value: data,
                        linea: row.id
                    }).css({
                        'text-align': 'center',
                        'font-size': 'smaller'
                    });
                    return input.prop('outerHTML');
                }
            },
            {   
                data: 'cajas', 
                render: function ( data, type, row, meta ) {
             
                    var input = $('<input>', {
                        id:  'cajas_' + row.id,
                        name: 'cajas_' + row.id,
                        class: 'lp-cell lp-input albaran_linea',
                        albaran: item.albaran.numero_albaran,
                        type: 'text',
                        value: data,
                        linea: row.id
                    }).css({
                        'text-align': 'center',
                        'font-size': 'smaller',
                        'max-width': '50px'
                    });
                    return input.prop('outerHTML');
                }
            },
            {   
                data: 'ejemplares_por_caja', 
                render: function ( data, type, row, meta ) {
             
                    var input = $('<input>', {
                        id:  'ejemplares_por_caja_' + row.id,
                        name: 'ejemplares_por_caja_' + row.id,
                        class: 'lp-cell lp-input albaran_linea',
                        albaran: item.albaran.numero_albaran,
                        type: 'text',
                        value: data,
                        linea: row.id
                    }).css({
                        'text-align': 'center',
                        'font-size': 'smaller',
                        'max-width': '50px'
                    });
                    return input.prop('outerHTML');
                }
            },
            {   
                data: 'precio_unidad', 
                render: function ( data, type, row, meta ) {
             
                    value = parseFloat(data).toFixed(4);
                    var input = $('<input>', {
                        id:  'precio_unidad_' + row.id,
                        name: 'precio_unidad_' + row.id,
                        class: 'lp-cell lp-input albaran_linea',
                        albaran: item.albaran.numero_albaran,
                        type: 'text',
                        value: value,
                        linea: row.id
                    }).css({
                        'text-align': 'center',
                        'font-size': 'smaller',
                        'max-width': '50px'
                    });
                    return input.prop('outerHTML');
                }
            },
            {   
                data: 'total', 
                render: function ( data, type, row, meta ) {
             
                    var input = $('<input>', {
                        id:  'total_' + row.id,
                        name: 'total_' + row.id,
                        class: 'lp-cell lp-input albaran_linea',
                        albaran: item.albaran.numero_albaran,
                        type: 'text',
                        value: data,
                        linea: row.id
                    }).css({
                        'text-align': 'center',
                        'font-size': 'smaller',
                        'max-width': '50px'
                    });
                    return input.prop('outerHTML');
                }
            }
        
        ],
        columnDefs: [
            { targets: [0], visible: false, searchable: false },
            { targets: [1], orderable: false },
            { targets: [2, 3, 4, 5, 6, 7, 8, 9], className: 'dt-center' }
        ],
        initComplete: function(settings){
            var numColumns = this.api().columns().count();
            if(item.albaran.mostrar_precios == 0){
                this.api().column(numColumns - 1).visible(false);
                this.api().column(numColumns - 2).visible(false);
            } else {
                this.api().column(numColumns - 1).visible(true);
                this.api().column(numColumns - 2).visible(true);
            }

        },
        footerCallback: function (row, data, start, end, display) {
            
            /*
            let api = this.api();
            var numColumns = api.columns().count();
    
            if(item.albaran.mostrar_precios == 1){
               
                // Remove the formatting to get integer data for summation
                let intVal = function (i) {
                    return typeof i === 'string'
                        ? i.replace(/[\$,]/g, '') * 1
                        : typeof i === 'number'
                        ? i
                        : 0;
                };
        
                // Total over all pages
                total = api
                    .column(9)
                    .data()
                    .reduce((a, b) => intVal(a) + intVal(b), 0);
        
                // Update footer
                api.column(numColumns-1).footer().innerHTML =
                    'Total: ' + total.toFixed(2);
            }
            else{
                api.column(numColumns-1).footer().innerHTML = '';
            }
            */
        },
    });

    // Añadir la nueva fila a la tabla
    if(Array.isArray(item.lineas)) {
        item.lineas.forEach(function(linea) {
            datatableAlbaran.row.add(linea).draw(); 
        });
    }
}

$(document).on('click', '.accordion-button', function(){

    var albaran_id = $(this).attr('albaran');
    var table = $('#tablaAlbaran' + albaran_id).DataTable();    
    table.columns.adjust();
}); 

$(document).on('change', '.cambios-albaran', function(){
    
    var elementId = $(this).attr('id');

    data = {
        <?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
    };
    data[elementId.split('_')[0] + '_albaran'] = $(this).val();

    var albaran_id = $(this).attr('albaran_id');
    var url = '<?= route_to('actualizarAlbaran', ':id') ?>'; 
    url = url.replace(':id', albaran_id );

    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        success: function(response){
            
            if('error' in response){
                
            }
        }
    });

});

$(document).on('change', '.mostrar-precios', function(){
    
    var checked = $(this).prop('checked');
    
    var albaran_id = $(this).attr('albaran_id');
    var table = $('#tablaAlbaran' + albaran_id).DataTable();    
    
    var url = '<?= route_to('actualizarAlbaran', ':id') ?>'; 
    url = url.replace(':id', albaran_id );

    $.ajax({
        url: url,
        type: 'POST',
        data: {
            mostrar_precios: checked?1:0,
            <?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
        },
        success: function(response){
            
            if('error' in response){
                if(response.error == 0){
                    if(checked){
                        table.column(9).visible(true);
                        table.column(8).visible(true);
                    } else {
                        table.column(9).visible(false);
                        table.column(8).visible(false);
                    }
                }
            }
        }
    });
});

$(document).on('click', '.btn-delete-linea', function(){
    var elementId = $(this).attr('id');
    var domTable = $(this).closest('table'); 
    var table = domTable.DataTable(); 
    const row = $(this).closest('tr');
    var url = '<?= route_to('borrarAlbaranLinea') ?>'; 

    $.ajax({
        url: url,
        type: 'POST',
        data: {
            id: $(this).attr('data-id'),
            <?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
        },
        success: function(response){
            
            if('error' in response){
                if(response.error == 0){
                    table.row($(row)).remove().draw();
                }
            }
        }
    });
});

$(document).on('change', '.albaran_linea', function(){

    var elementId = $(this).attr('id');

    data = {
        <?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
    };
    data[elementId.split('_').slice(0, -1).join('_')] = $(this).val();

    var linea_id = $(this).attr('linea');
    var url = '<?= route_to('actualizarLineaAlbaran', ':id') ?>'; 
    url = url.replace(':id', linea_id );

    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        success: function(response){
            
            if('error' in response){
                
            }
        }
    });

});

$(document).on('click', '#borrar_albaranes', function(){
    
        asyncConfirmDialogWithParams(
            "Borrar albaranes",
            "¿Está seguro de borrar los albaranes? Esta acción no se puede deshacer.",
            borrar_albaranes, function(){}, [])
    
     
});

function borrar_albaranes(){

    // seleccionan todos los accordion dentro del body del accordion accordioAlbaranes
    $('.accordion-albaran').each(function() {
        // Aquí puedes trabajar con cada acordeón interno encontrado
        var albaran_id = $(this).attr('albaran');
        var url = '<?= route_to('borrarAlbaran', ':id') ?>';     
        url = url.replace(':id', albaran_id );
        $.ajax({
            url: url,
            type: 'GET',
            success: function(response){
                if(response){
                    if('error' in response){
                        if(response.error == 0){
                            $('#accordioAlbaran' + albaran_id).remove();
                        }
                    }
                }
            }
        }); 
    });
}


function borrar_albaran(albaran_id){

    var url = '<?= route_to('borrarAlbaran', ':id') ?>';     
    url = url.replace(':id', albaran_id );
    $.ajax({
        url: url,
        type: 'GET',
        success: function(response){
            if(response){
                if('error' in response){
                    if(response.error == 0){
                        $('#accordioAlbaran' + albaran_id).remove();
                    }
                }
            }
        }
    });
}


$(document).on('click', '.borrar-albaran', function(){

    var albaran_id = $(this).attr('id').split('_').slice(-1)[0];
    
    asyncConfirmDialogWithParams(
            "Borrar albarán",
            "¿Está seguro de borrar el albarán? Esta acción no se puede deshacer.",
            borrar_albaran, function(){}, [albaran_id])
});

$(document).on('click', '.nueva-linea-albaran', function(){
    
    var albaran_id = $(this).attr('id').split('_').slice(-1)[0];
    var url = '<?= route_to('addAlbaranLinea', ':id') ?>';     
    url = url.replace(':id', albaran_id );
    $.ajax({
        url: url,
        type: 'GET',
        success: function(response){
            if(response){
                if('error' in response){
                    if(response.error == 0){
                        var table = $('#tablaAlbaran' + albaran_id).DataTable(); 
                        table.row.add(response.data).draw();
                    }
                }
            }
        }
    }); 
});

$(document).on('click', '.add-iva-albaran', function(){
    
    var albaran_id = $(this).attr('id').split('_').slice(-1)[0];
    var url = '<?= route_to('addIVA', ':id') ?>';     
    url = url.replace(':id', albaran_id );
    data = {
        albaran_id: albaran_id,
        <?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
    };
    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        success: function(response){
            if(response){
                if('error' in response){
                    if(response.error == 0){
                        var table = $('#tablaAlbaran' + albaran_id).DataTable(); 
                        table.row.add(response.data).draw();
                    }
                }
            }
        }
    }); 
});

$(document).on('click', '.imprimir-albaran', function(){
    
    var albaran_id = $(this).attr('id').split('_').slice(-1)[0];
    
    //NACHO AQUI
    window.open('<?= site_url('print-albaran/generar/') ?>' + albaran_id, '_blank');

});

$.ajax({
    url: '<?= route_to('getAlbaranes', $pedidoEntity->id) ?>',
    type: 'GET',
    success: function(response){
        
        if(response.data.length > 0){
            Object.values(response.data).forEach(function(item){
                generarAlbaran(item);
            });
        }
    }
});
<?=$this->endSection() ?>