<?=$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('Pedidos.pedidosList') ?></h3>
           </div><!--//.card-header -->
            <div class="card-body">
				<?= view('themes/_commonPartialsBs/_alertBoxes'); ?>
                    <div class="row">
                        <div class="form-check form-check-inline">
                            <input type="checkbox" class="form-check-input" id="showTotal" name="showTotal">
                            <label for="showTotal" class="form-check-label">
                                <?= lang('Pedidos.showTotal') ?>
                            </label>
                        </div>  
                    </div>

					<table id="tableOfPedidos" class="table table-striped table-hover" style="width: 100%;">
						<thead>
							<tr>
								<th><?= lang('Pedidos.id') ?></th>
                                <th><?= lang('Pedidos.fecha') ?></th>
                                <th><?= lang('Pedidos.fecha_entrega') ?></th>
                                <th><?= lang('Pedidos.cliente') ?></th>
                                <th><?= lang('Pedidos.comercial') ?></th>
                                <th><?= lang('Pedidos.titulo') ?></th> 
                                <th><?= lang('Pedidos.ubicacion') ?></th>
                                <th><?= lang('Pedidos.inc_rei') ?></th>
                                <th class='noFilter'><?= lang('Pedidos.num_paginas') ?></th>
                                <th class='totalizador'><?= lang('Pedidos.tiradas') ?></th>
                                <th class='totalizador'><?= lang('Pedidos.total_presupuesto') ?></th>
                                <th><?= lang('Pedidos.estado') ?></th>
                                <th class="noFilter 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 = $('#tableOfPedidos').find("tr:first th").length - 1;
    const actionBtns = 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-eye ti-sm btn-edit mx-2" data-id="${data.id}"></i></a>
                </div>
            </td>`;
    };

// Setup - add a text input to each footer cell
$('#tableOfPedidos thead tr').clone(true).appendTo('#tableOfPedidos thead');
$('#tableOfPedidos thead tr:eq(1) th').each(function (i) {
	if (!$(this).hasClass("noFilter")) {
		var title = $(this).text();
        if($(this).hasClass("totalizador")){
            if(i==9){
                $(this).html('<span id="total_tirada" class="autonumeric-int"></span><br><span id="total_tirada_2" class="mostrar-totales autonumeric-int d-none"></span>');
            }
            else if(i==10){
                $(this).html('<span id="total_aceptado" class="autonumeric"></span>€<br><span id="total_aceptado_2" class="mostrar-totales autonumeric d-none"></span><span class="mostrar-totales d-none">€</span>');
            }
        }
        else{
            if(i==1 || i==2){
                name = 'bs-rangepicker-range_' + i;
                $(this).html('<input id="'+name+'" type="text" class="form-control " style="min-width:100px;max-width:120px;font-size:0.8rem !important;"  />');
                var bsRangePickerRange = $('#' + name);
                bsRangePickerRange.daterangepicker({
                ranges: {
                    '<?= lang('datePicker.hoy') ?>': [moment(), moment()],
                    '<?= lang('datePicker.ayer') ?>': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    '<?= lang('datePicker.ultimos7') ?>': [moment().subtract(6, 'days'), moment()],
                    '<?= lang('datePicker.ultimos30') ?>': [moment().subtract(29, 'days'), moment()],
                    '<?= lang('datePicker.esteMes') ?>': [moment().startOf('month'), moment().endOf('month')],
                    '<?= lang('datePicker.ultimoMes') ?>': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                },
                opens: 'right',
                language: '<?= config('Basics')->i18n ?>',
                "locale": {
                    "customRangeLabel": "<?= lang('datePicker.personalizar') ?>",
                    "format": "YYYY-MM-DD",
                    "separator": " ",
                    "applyLabel": "<?= lang('datePicker.aplicar') ?>",
                    "cancelLabel": "<?= lang('datePicker.limpiar') ?>",

                },
                "alwaysShowCalendars": true,
                autoUpdateInput: false,

                });

                bsRangePickerRange.on('apply.daterangepicker', function(ev, picker) {
                    $(this).val(picker.startDate.format('YYYY-MM-DD') + ' ' + picker.endDate.format('YYYY-MM-DD'));
                    theTable
                        .column(i)
                        .search(this.value)
                        .draw();
                });

                bsRangePickerRange.on('cancel.daterangepicker', function(ev, picker) {
                    $(this).val('');
                    theTable
                        .column(i)
                        .search(this.value)
                        .draw();
                });

            }
            else if (i == 11) {

                if("<?= $estadoPedidos ?>" == "" || "<?= $estadoPedidos ?>" == "todos"){
                
                    $(this).html('<select class="form-control" style="min-width:100px;max-width:120px;font-size:0.8rem !important;"></select>');

                    // Agregar opciones al selector
                    var selector = $('select', this);
                    
                    selector.append('<option value="">Todos</option>'); // Opción vacía
                    selector.append('<option value="validacion"><?= lang('Pedidos.validacion') ?></option>');
                    selector.append('<option value="produccion"><?= lang('Pedidos.produccion') ?></option>');
                    selector.append('<option value="finalizado"><?= lang('Pedidos.finalizado') ?></option>');
                    selector.append('<option value="enviado"><?= lang('Pedidos.enviado') ?></option>');
                    selector.append('<option value="cancelado"><?= lang('Pedidos.cancelado') ?></option>');
                    
                    selector.on('change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
                        theTable.column(i).search(val).draw();
                    });
                }
                else{
                    $(this).html('<span></span>');
                }
            }
            else{
                $(this).html('<input type="text" class="form-control " style="min-width:100px;max-width:120px;font-size:0.8rem !important;"  />');

                $('input', this).on('change clear', function () {
                    if (theTable.column(i).search() !== this.value) {
                        theTable
                            .column(i)
                            .search(this.value)
                            .draw();
                    }
                });
            }
        }
	}
	else {
		$(this).html('<span></span>');
	}
});

    var theTable = $('#tableOfPedidos').DataTable({
        select: {
            style: 'multi',
            info: false
        },
        orderCellsTop: true,
        fixedHeader: true,
        processing: true,
        serverSide: true,
        autoWidth: true,
        responsive: true,
        searching: true,
        scrollX: true,
        lengthMenu: [ 5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500 ],
        pageLength: 100,
        lengthChange: true,
        "dom": '<"mb-3"l>Brtip',
        "buttons": [
            'colvis', 'copy', 'csv', 'excel', 'print', {
                extend: 'pdfHtml5',
                orientation: 'landscape',
                pageSize: 'A4'
            }
        ],
        stateSave: false,
        order: [[0, 'desc']],
        language: {
            url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
        },
        ajax : $.fn.dataTable.pipeline( {
            url: '<?= route_to('dataTableOfPedidos') ?>',
            method: 'POST',
            data: function(d, settings){
                d.estado= "<?= $estadoPedidos ?>";
                d.showTotal= $('#showTotal').is(':checked')? "1":"0";
                d.cliente_id = "<?= $cliente_id ?>";
            },
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            async: true,
        }),
        columnDefs: [
            {
                orderable: false,
                searchable: true,
                targets: [lastColNr]
            }
        ],
        columns : [
            { 'data': 'id' },
            { 'data': 'fecha' },
            { 'data': 'fecha_entrega' },
            { 'data': 'cliente' },
            { 'data': 'comercial' },
            { 'data': 'titulo' },
            { 'data': 'ubicacion' },
            { 'data': 'inc_rei' },
            { 'data': 'paginas',render : (d) => `<span class="autonumeric">${d}</span>` },
            { 'data': 'tirada',render : (d) => `<span class="autonumeric">${d}</span>` },
            { 'data': 'total_presupuesto',render : (d) => `<span class="autonumeric">${d}</span>`},
            { 'data': 'estado',
                render: function(data, type, row, meta) {
                    switch(data){
                        case "validacion":
                            return '<?= lang('Pedidos.validacion') ?>';
                            break;

                        case "produccion":
                            return '<?= lang('Pedidos.produccion') ?>';
                            break;

                        case "finalizado":
                            return '<?= lang('Pedidos.finalizado') ?>';
                            break;

                        case "enviado":
                            return '<?= lang('Pedidos.enviado') ?>';
                            break;

                        case "cancelado":
                            return '<?= lang('Pedidos.cancelado') ?>';
                            break;

                        default:
                            return data;    // Debug
                            break;

                    }
                }
            },
            { 'data': actionBtns }
        ],
        drawCallback: function (settings) {

            var api = this.api();

            $('#total_tirada').text(settings.json.extra.total_tirada??0);
            $('#total_tirada_2').text(settings.json.extra.total_tirada2??0);
            $('#total_aceptado').text(settings.json.extra.total??0);
            $('#total_aceptado_2').text(settings.json.extra.total2??0);
            AutoNumeric.multiple('.autonumeric', { decimalPlaces: 2 });
            AutoNumeric.multiple('.autonumeric-int', { decimalPlaces: 0 });
        
            const dateCols = [1,2];
            const priceCols = [10];
            
            for (let coln of dateCols) {
                api.column(coln, { page: 'current' }).nodes().each( function (cell, i) {
                    const datestr = cell.innerHTML;
                    const dateStrLen = datestr.toString().trim().length;
                    if (dateStrLen > 0) {
                        let dateTimeParts= datestr.split(/[- :]/); // regular expression split that creates array with: year, month, day, hour, minutes, seconds values
                        dateTimeParts[1]--; // monthIndex begins with 0 for January and ends with 11 for December so we need to decrement by one
                        const d = new Date(...dateTimeParts); // new Date(datestr);
                        cell.innerHTML = d.toLocaleDateString();
                    }
                });
            }
            if(<?= $cliente_id ?> != -1){
                api.column(3).visible(false);
            }
            else{
                api.column(3).visible(true);
            }
        },
        "rowCallback": function(row, data, index) {
            if('<?= $estadoPedidos ?>' == 'todos'){
                if (data['estado'] === "cancelado") {
                    $(row).css('background-color', '#ffcccc'); // Rojo claro
                } else if (data['estado'] === "validacion") {
                    $(row).css('background-color', '#fff5cc'); // Amarillo claro
                } else if (data['estado'] === "finalizado") {
                    $(row).css('background-color', '#ccffcc'); // Verde claro
                }
            }
        }
    });

    



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

    theTable.on('click', 'tbody tr', function (e) {
        e.currentTarget.classList.toggle('selected');
    });

    $('#showTotal').on('change', function() {
        if($('#showTotal').is(':checked')){
            $('.mostrar-totales').removeClass('d-none');
        }
        else{
            $('.mostrar-totales').addClass('d-none');
        }
        theTable.clearPipeline();
        theTable.ajax.reload(null, false);
        //theTable.draw();
    });

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


<?=$this->section('css') ?>
    <link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
	<link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/fixedheader/fixedHeader.dataTables.min.css") ?>">
	<link rel="stylesheet" href="<?= site_url('themes/vuexy/vendor/libs/bootstrap-daterangepicker/bootstrap-daterangepicker.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/select/dataTables.select.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/buttons/buttons.colVis.min.js") ?>"></script>
	<script src="<?= site_url('themes/vuexy/vendor/libs/moment/moment.js') ?>"></script>
	<script src="<?= site_url('themes/vuexy/vendor/libs/bootstrap-daterangepicker/bootstrap-daterangepicker.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() ?>

