<?=$this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?=$this->extend('themes/vuexy/main/defaultlayout') ?>
<?=$this->section('content');  ?>
<div class="row">
    <div class="col-md-12">

        <div class="card card-info">
            <div class="card-header">
                <h3 class="card-title"><?=lang('Facturas.facturasList') ?></h3>
           </div><!--//.card-header -->
            <div class="card-body">
				<?= view('themes/_commonPartialsBs/_alertBoxes'); ?>

					<table id="tableOfFacturas" class="table table-striped table-hover" style="width: 100%;">
						<thead>
							<tr>
								<th><?= lang('Facturas.idFactura') ?></th>
                                <th><?= lang('Facturas.numeroFactura') ?></th>
                                <th><?= lang('Facturas.fechaFactura') ?></th>
                                <th><?= lang('Facturas.cliente') ?></th>
                                <th><?= lang('Facturas.base') ?></th>
                                <th><?= lang('Facturas.total') ?></th> 
                                <th><?= lang('Facturas.pendiente') ?></th>
                                <th><?= lang('Facturas.credito') ?></th>
                                <th><?= lang('Facturas.estado') ?></th>
                                <th><?= lang('Facturas.estadoPago') ?></th>
                                <th><?= lang('Facturas.formaPago') ?></th>
                                <th><?= lang('Facturas.vencimiento') ?></th>
                                <th><?= lang('Facturas.dias') ?></th>
                                <th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
							</tr>
						</thead>
						<tbody>

						</tbody>
					</table>
            </div><!--//.card-body -->
            <div class="card-footer">
				
            </div><!--//.card-footer -->
        </div><!--//.card -->
    </div><!--//.col -->
</div><!--//.row -->

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


<?=$this->section('additionalInlineJs') ?>
    
    const lastColNr = $('#tableOfFacturas').find("tr:first th").length - 1;
    const actionBtns = function(data) {
        if(data.estado == 'borrador'){
            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-pencil ti-sm btn-edit mx-2" data-id="${data.id}"></i></a>
                    </div>
                </td>`;
        }
        else{
            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-eye ti-sm btn-edit mx-2" data-id="${data.id}"></i></a>
                </div>
            </td>`;
        }
    };

    theTable = $('#tableOfFacturas').DataTable({
        processing: true,
        serverSide: true,
        autoWidth: true,
        responsive: true,
        scrollX: true,
        lengthMenu: [ 5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500 ],
        pageLength: 250,
        lengthChange: true,
        "dom": 'lfBrtip',
        buttons: [
            {
                text: 'Exportar Excel Contaplus',
                action: function (e, dt, button, config) {
                    var searchValue = theTable.search(); // Captura el valor del campo de búsqueda
                    var ajaxParams = theTable.ajax.params(); // Captura otros parámetros de la tabla

                    console.log(searchValue);

                    /*
                    $.ajax({
                        url: '/ruta/exportarExcel', // URL del servidor para manejar la exportación
                        type: 'POST',
                        data: {
                            search: searchValue,
                            extraParams: ajaxParams
                        },
                        xhrFields: {
                            responseType: 'blob' // Para manejar la descarga del archivo
                        },
                        success: function(blob, status, xhr) {
                            // Crear un enlace temporal para descargar el archivo
                            var link = document.createElement('a');
                            var url = window.URL.createObjectURL(blob);
                            link.href = url;
                            link.download = 'datos_personalizados.xlsx';
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                            window.URL.revokeObjectURL(url);
                        }
                    });
                    */
                }
            },
            {
                text: 'Exportar Lineas a Excel',
                action: function (e, dt, button, config) {
                    var searchValue = theTable.search(); // Captura el valor del campo de búsqueda
                    var ajaxParams = theTable.ajax.params(); // Captura otros parámetros de la tabla

                    console.log(searchValue);

                }
            },
            {
                text: 'Exportar Girosgit ',
                action: function (e, dt, button, config) {
                    var searchValue = theTable.search(); // Captura el valor del campo de búsqueda
                    var ajaxParams = theTable.ajax.params(); // Captura otros parámetros de la tabla

                    console.log(searchValue);

                }
            }
        ],
        stateSave: true,
        order: [[0, 'asc']],
        language: {
            url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
        },
        ajax : $.fn.dataTable.pipeline( {
            url: '<?= route_to('dataTableOfFacturas') ?>',
            method: 'POST',
            data: function(d, settings){
                d.cliente_id = "<?= $cliente_id ?>";
            },
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            async: true,
        }),
        columnDefs: [
            {
                orderable: false,
                searchable: false,
                targets: [lastColNr]
            }
        ],
        columns : [
            { 'data': 'id' },
            { 'data': 'numero' },
            { 'data': 'fecha_factura_at' },
            { 'data': 'cliente' },
            { 'data': 'base' },
            { 'data': 'total' },
            { 'data': 'pendiente' },
            { 'data': 'creditoAsegurado' ,
                render: function(data, type, row, meta) {
                    switch(data){
                        case "0":
                            return '<?= lang('Basic.global.no') ?>';
                            break;

                        case "1":
                            return '<?= lang('Basic.global.yes') ?>';
                            break;

                        default:
                            return '--';    // Debug
                            break;

                    }
                },
            },
            { 'data': 'estado',
                render: function(data, type, row, meta) {
                    switch(data){
                        case "borrador":
                            return '<?= lang('Facturas.borrador') ?>';
                            break;

                        case "validada":
                            return '<?= lang('Facturas.validada') ?>';
                            break;

                        default:
                            return '--';    // Debug
                            break;

                    }
                }
            },
            { 'data': 'estado_pago',
                render: function(data, type, row, meta) {
                    switch(data){
                        case "pendiente":
                            return '<?= lang('Facturas.pendiente') ?>';
                            break;

                        case "pagada":
                            return '<?= lang('Facturas.pagada') ?>';
                            break;

                        case "insolvente":
                            return '<?= lang('Facturas.insolvente') ?>';
                            break;

                        default:
                            return '--';    // Debug
                            break;

                    }
                }
            },
            { 'data': 'forma_pago',
                render: function(data, type, row, meta) {
                    switch(data){
                        case "cheque":
                            return '<?= lang('Facturas.cheque') ?>';
                            break;

                        case "compensada":
                            return '<?= lang('Facturas.compensada') ?>';
                            break;

                        case "confirming":
                            return '<?= lang('Facturas.confirming') ?>';
                            break;

                        case "giroDomiciliado":
                            return '<?= lang('Facturas.giroDomiciliado') ?>';
                            break;

                        case "pagare":
                            return '<?= lang('Facturas.pagare') ?>';
                            break;

                        case "transferencia":
                            return '<?= lang('Facturas.transferencia') ?>';
                            break;
                        
                        default:
                            return data;    // Debug
                            break;

                    }
                }
            },
            { 'data': 'vencimiento' },
            { 'data': 'dias_vencimiento' },
            { 'data': actionBtns }
        ]
    });

    theTable.on( 'draw.dt', function () {
        if(<?= $cliente_id ?> != -1){
            theTable.column(3).visible(false);
            theTable.column(7).visible(false);
            theTable.column(8).visible(false);
            theTable.column(9).visible(false);
            theTable.column(10).visible(false);
            theTable.column(11).visible(false);
            theTable.column(12).visible(false);
        }
    });

    
    $(document).on('click', '.btn-edit', function(e) {
        var url = '<?= route_to('editarFactura', ':id') ?>'; 
        url = url.replace(':id', `${$(this).attr('data-id')}` );
        window.location.href = url;
    });

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


<?=$this->section('css') ?>
    <link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
<?=$this->endSection() ?>


<?= $this->section('additionalExternalJs') ?>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/dataTables.buttons.min.js") ?>"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.js") ?>"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.html5.min.js") ?>"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.print.min.js") ?>"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/jszip/jszip.min.js") ?>"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/pdfmake.min.js") ?>" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/vfs_fonts.js") ?>"></script>
<?=$this->endSection() ?>

