<?=$this->include('themes_commonPartialsBs/select2bs5') ?>
<?=$this->include('themes_commonPartialsBs/datatables') ?>
<?=$this->include('themes_commonPartialsBs/sweetalert') ?>
<?=$this->extend('themes'.config('Basics')->theme['name'].'/AdminLayout/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('ComunidadesAutonomas.comunidadAutonomaList') ?></h3>
           </div><!--//.card-header -->
            <div class="card-body">
				<?= view('themes_commonPartialsBs/_alertBoxes'); ?>

					<table id="tableOfComunidadesautonomas" class="table table-striped table-hover" style="width: 100%;">
						<thead>
							<tr>
								<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
								<th><?=lang('ComunidadesAutonomas.id')?></th>
								<th><?= lang('ComunidadesAutonomas.nombre') ?></th>
								<th><?= lang('Paises.pais') ?></th>
								<th><?= lang('ComunidadesAutonomas.createdAt') ?></th>
								<th><?= lang('ComunidadesAutonomas.updatedAt') ?></th>
								<th class="text-nowrap"><?= lang('Basic.global.Action') ?></th>
							</tr>
						</thead>
						<tbody>

						</tbody>
					</table>
            </div><!--//.card-body -->
            <div class="card-footer">
				<?=anchor(route_to('newComunidadAutonoma'), lang('Basic.global.addNew').' '.lang('ComunidadesAutonomas.comunidadAutonoma'), ['class'=>'btn btn-primary float-end']); ?>
            </div><!--//.card-footer -->
        </div><!--//.card -->
    </div><!--//.col -->
</div><!--//.row -->

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


<?=$this->section('additionalInlineJs') ?>
    
            const lastColNr = $('#tableOfComunidadesautonomas').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">
                            <button class="btn btn-sm btn-warning btn-edit me-1" data-id="${data.id}"><?= lang('Basic.global.edit') ?></button>
                            <button class="btn btn-sm btn-danger btn-delete ms-1" data-id="${data.id}"><?= lang('Basic.global.Delete') ?></button>
                        </div>
                        </td>`;
            };
            theTable = $('#tableOfComunidadesautonomas').DataTable({
                processing: true,
                serverSide: true,
                autoWidth: true,
                responsive: true,
                scrollX: true,
                lengthMenu: [ 5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500 ],
                pageLength: 10,
                lengthChange: true,
                
                stateSave: true,
                order: [[1, 'asc']],
                language: {
                    url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
                },
                ajax : $.fn.dataTable.pipeline( {
                    url: '<?= route_to('dataTableOfComunidadesAutonomas') ?>',
                    method: 'POST',
                    headers: {'X-Requested-With': 'XMLHttpRequest'},
                    async: true,
                }),
                columnDefs: [
                    {
                        orderable: false,
                        searchable: false,
                        targets: [0,lastColNr]
                    }
                ],
                columns : [
                    { 'data': actionBtns },
					{ 'data': 'id' },
					{ 'data': 'nombre' },
					{ 'data': 'pais' },
					{ 'data': 'created_at' },
					{ 'data': 'updated_at' },
                    { 'data': actionBtns }
                ]
            });

    
        theTable.on( 'draw.dt', function () {
        
                const dateCols = [4, 5];
            const shortDateFormat = '<?= convertPhpDateToMomentFormat('mm/dd/YYYY')?>';
            const dateTimeFormat = '<?= convertPhpDateToMomentFormat('mm/dd/YYYY h:i a')?>';
            
            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);
                        const md = moment(d);
                        const usingThisFormat = dateStrLen > 11 ? dateTimeFormat : shortDateFormat;
                        const formattedDateStr = md.format(usingThisFormat);
                        cell.innerHTML = formattedDateStr;
                    }
                });
            }
    });

$(document).on('click', '.btn-edit', function(e) {
        window.location.href = `<?= route_to('comunidadAutonomaList') ?>/${$(this).attr('data-id')}/edit`;
    });
    
$(document).on('click', '.btn-delete', function(e) {
        Swal.fire({
            title: '<?= lang('Basic.global.sweet.sureToDeleteTitle', [mb_strtolower(lang('ComunidadesAutonomas.comunidad autonoma'))]) ?>',
            text: '<?= lang('Basic.global.sweet.sureToDeleteText') ?>',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            confirmButtonText: '<?= lang('Basic.global.sweet.deleteConfirmationButton') ?>',
            cancelButtonText: '<?= lang('Basic.global.Cancel') ?>',
            cancelButtonColor: '#d33'
        })
        .then((result) => {
            const dataId = $(this).data('id');
            const row = $(this).closest('tr');
            if (result.value) {
                $.ajax({
                    url: `<?= route_to('comunidadAutonomaList') ?>/${dataId}`,
                    method: 'DELETE',
                }).done((data, textStatus, jqXHR) => {
                    Toast.fire({
                        icon: 'success',
                        title: data.msg ?? jqXHR.statusText,
                    });
                    
                    theTable.clearPipeline();
                    theTable.row($(row)).invalidate().draw();
                }).fail((jqXHR, textStatus, errorThrown) => {
                    Toast.fire({
                        icon: 'error',
                        title: jqXHR.responseJSON.messages.error,
                    });
                })
            }
        });
    });
                                
    

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