<?=$this->include('themes/_commonPartialsBs/select2bs5') ?>
<?=$this->include('themes/_commonPartialsBs/datatables') ?>
<?=$this->include('themes/_commonPartialsBs/sweetalert') ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?= $this->extend('themes/backend/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('Presupuestos.presupuestoCosidotapablandaList') ?></h3>
				<?=anchor(route_to('newCosidotapablanda'), lang('Basic.global.addNew').' '.lang('Presupuestos.presupuesto'), ['class'=>'btn btn-primary ']); ?>
           </div><!--//.card-header -->
            <div class="card-body">
				<?= view('themes/_commonPartialsBs/_alertBoxes'); ?>

					<table id="tableOfPresupuestos" class="table table-striped table-hover" style="width: 100%;">
						<thead>
							<tr>
								<th><?=lang('Presupuestos.id')?></th>
								<th><?= lang('Presupuestos.created_at') ?></th>
								<th><?= lang('Clientes.cliente') ?></th>
								<th><?= lang('Presupuestos.comercial') ?></th>
								<th><?= lang('Presupuestos.titulo') ?></th>
								<th><?= lang('Paises.pais') ?></th>
								<th><?= lang('Presupuestos.incRei') ?></th>
								<th class='noFilter'><?= lang('Presupuestos.paginas') ?></th>
								<th class='noFilter'><?= lang('Presupuestos.tirada') ?></th>
								<th class='noFilter'><?= lang('Presupuestos.totalPresupuesto') ?></th>
								<th><?= lang('Presupuestos.presupuestoEstado') ?></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 = $('#tableOfPresupuestos').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-pencil ti-sm btn-edit mx-2" data-id="${data.id}"></i></a>
				<a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="${data.id}" data-bs-toggle="modal" data-bs-target="#confirm2delete"></i></a>
			</div>
		</td>`;
};
	
// Setup - add a text input to each footer cell
$('#tableOfPresupuestos thead tr').clone(true).appendTo('#tableOfPresupuestos thead');
$('#tableOfPresupuestos thead tr:eq(1) th').each(function (i) {
	if (!$(this).hasClass("noFilter")) {
		var title = $(this).text();
		if(i==1){

			$(this).html('<input id="bs-rangepicker-range" type="text" class="form-control " style="min-width:100px;max-width:120px;font-size:0.8rem !important;"  />');
			var bsRangePickerRange = $('#bs-rangepicker-range')
			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{
			$(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>');
	}

});


theTable = $('#tableOfPresupuestos').DataTable({
	orderCellsTop: true,
	fixedHeader: true,
	processing: true,
	serverSide: true,
	autoWidth: true,
	responsive: true,
	scrollX: true,
	lengthMenu: [ 5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500 ],
	pageLength: 50,
	lengthChange: true,
	"dom": 'lBrtip',
	"buttons": [
		'colvis', 'copy', 'csv', 'excel', 'print', {
			extend: 'pdfHtml5',
			orientation: 'landscape',
			pageSize: 'A4'
		}
	],
	stateSave: false,
	order: [[1, 'asc']],
	language: {
		url: "//cdn.datatables.net/plug-ins/1.13.4/i18n/<?= config('Basics')->i18n ?>.json"
	},
	ajax : $.fn.dataTable.pipeline( {
		url: '<?= route_to('dataTableOfCosidotapablanda') ?>',
		method: 'POST',
		headers: {'X-Requested-With': 'XMLHttpRequest'},
		async: true,
	}),
	columnDefs: [
		{
			orderable: false,
			searchable: false,
			targets: [lastColNr]
		}
	],
	columns : [
		{ 'data': 'id' },
		{ 'data': 'fecha' },
		{ 'data': 'cliente' },
		{ 'data': 'comercial' },
		{ 'data': 'titulo' },
		{ 'data': 'pais' },
		{ 'data': 'inc_rei' },
		{ 'data': 'paginas' },
		{ 'data': 'tirada' },
		{ 'data': 'total_presupuesto' },
		{ 'data': 'estado' ,
			'render': function ( data, type, row, meta ) {
                if(data=='borrador')
                    return '<?= lang('Presupuestos.presupuestoEstadoBorrador') ?>';
                else if(data=='aceptado')
                    return '<?= lang('Presupuestos.presupuestoEstadoAceptado') ?>';
                }
            },
		{ 'data': actionBtns }
	]
});

    
theTable.on( 'draw.dt', function () {
	
	const dateCols = [1];
	const priceCols = [9];
	
	for (let coln of dateCols) {
		theTable.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();
			}
		});
	}
	
	for (let coln of priceCols) {
		theTable.column(coln, { page: 'current' }).nodes().each( function (cell, i) {
			cell.innerHTML = parseFloat(cell.innerHTML).toFixed(2);

		});
	}
});


$(document).on('click', '.btn-edit', function(e) {
	window.location.href = `/presupuestos/cosidotapablanda/edit/${$(this).attr('data-id')}`;
});


$(document).on('click', '.btn-delete', function(e) {
	$(".btn-remove").attr('data-id', $(this).attr('data-id'));
});


$(document).on('click', '.btn-remove', function(e) {
	const dataId = $(this).attr('data-id');
	const row = $(this).closest('tr');
	if ($.isNumeric(dataId)) {
		$.ajax({
			url: `/presupuestos/cosidotapablanda/delete/${dataId}`,
			method: 'GET',
		}).done((data, textStatus, jqXHR) => {
			$('#confirm2delete').modal('toggle');
			theTable.clearPipeline();
			theTable.row($(row)).invalidate().draw();
			popSuccessAlert(data.msg ?? jqXHR.statusText);
		}).fail((jqXHR, textStatus, errorThrown) => {
			popErrorAlert(jqXHR.responseJSON.messages.error)
		})
	}
});


    

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


<?=$this->section('css') ?>
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.3/css/buttons.<?=config('Basics')->theme['name'] == 'Bootstrap5' ? 'bootstrap5' : 'bootstrap4' ?>.min.css">
	<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/fixedheader/3.1.7/css/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="https://cdn.datatables.net/buttons/2.2.3/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.<?=config('Basics')->theme['name'] == 'Bootstrap5' ? 'bootstrap5' : 'bootstrap4' ?>.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.3/js/buttons.print.min.js"></script>
	<script src="https://cdn.datatables.net/buttons/2.2.3/js/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="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.0/jszip.min.js" integrity="sha512-xcHCGC5tQ0SHlRX8Anbz6oy/OullASJkEhb4gjkneVpGE3/QGYejf14CUO5n5q5paiHfRFTa9HKgByxzidw2Bw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.5/pdfmake.min.js" integrity="sha512-rDbVu5s98lzXZsmJoMa0DjHNE+RwPJACogUCLyq3Xxm2kJO6qsQwjbE5NDk2DqmlKcxDirCnU1wAzVLe12IM3w==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.5/vfs_fonts.js" integrity="sha512-cktKDgjEiIkPVHYbn8bh/FEyYxmt4JDJJjOCu5/FQAkW4bc911XtKYValiyzBiJigjVEvrIAyQFEbRJZyDA1wQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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

