<!-- Baru Select2 -->
<link href="<?= base_url(); ?>assets/libs/select2/select2.min.css" rel="stylesheet" />
<script src="<?= base_url(); ?>assets/libs/select2/select2.min.js"></script>



<script type="text/javascript">
	

	$(document).ready(function(){


	    $("select[name=year]").select2({
	      dropdownParent: $("#year").parent(),
	      width: '100%',
	      data: generateYearOptions(),
	      placeholder: "Pilih Tahun"
	    });


	    $("select[name=village]").select2({
	      dropdownParent: $("#village").parent(),
	      width: '100%',
	      ajax: {
	        url: baseUrl+'area/village/get-all-village-name',
	        type: 'post',
	        dataType: 'json',
	        data: function(params) {
	          return {
	            name: params.term,
	            page: params.page,
	            limit: 30,
	            parentId: null
	          };
	        },
	        processResults: function(data, params) {
	          var more = (params.page * 30) < data.total;
	          var option = [];
	          	option.push({
	              id: "ALL",
	              text: "Semua Desa",
	            });
	          $.each(data.data, function(index, item) {
	            option.push({
	              id: item.id,
	              text: item.name,
	            });
	          });
	          return {
	            results: option,
	            more: more,
	          };
	        },
	      },
	    });

		function generateYearOptions() {
		  const currentYear = new Date().getFullYear();
		  const startYear = currentYear - 25;
		  const years = [];
		  
		  for (let year = currentYear; year >= startYear; year--) {
		    years.push({
		      id: year,
		      text: year.toString()
		    });
		  }
		  
		  return years;
		}


		loadData()
	})


	
	function loadData() {
		$('#datatable').DataTable({
			"pageLength": 10,
			"serverSide": true,
			"processing": true,
			"scrollX": true,
			"order": [
				[0, "desc"]
			],
			"columnDefs": [
				{
					targets: [0,5],
					className: "text-center"
				},
				{
					orderable: false,
					targets: [1,2,3,4,5]
				},
				{
					width: '5%',
					targets: [0]
				},
				{
					width: '30%',
					targets: [1]
				},
				{
					width: '10%',
					targets: [2]
				},
				{
					width: '17.5%',
					targets: [3]
				},
				{
					width: '22.5%',
					targets: [4]
				},
				{
					width: '15%',
					targets: [4]
				},
			],
			"ajax": {
				url: baseUrl + 'customer/get-all-data',
				type: 'POST',
				data: {
				},
			},
			"columns": [{
					data: "no"
				},
				{
					data: "name"
				},
				{
					data: "village_name"
				},
				{
					data: "phone"
				},
				{
					data: "package_name"
				},				
				{
					data: "option"
				},
			],
			"destroy": true,
			"initComplete": function () {

					if(window.innerWidth<768){

			        	$('.dataTables_filter')
			            .addClass('d-flex align-items-center')
			            .append(`
			            	<div class="btn-group">
				                <button class="btn btn-sm btn-filter-sm ms-2 d-md-none d-inline-block"
				                	data-bs-toggle="dropdown" aria-expanded="false">
				                    <i class='bx bx-slider'></i>
				                </button>

		                      <ul class="dropdown-menu">

		                        <li><a data-type="PDF" class="btn-export dropdown-item" href="javascript:void(0);">Export PDF</a></li>

		                        <li><a data-type="EXCEL" class="btn-export dropdown-item" href="javascript:void(0);">Export Excel</a></li>

		                      </ul>
		                    </div>

			            `);
					}

				    $('.dataTables_paginate').addClass('mt-3');

				    updatePaginationIcons();

		    },
		    "drawCallback": function(settings) {
	            // Panggil fungsi ini setiap kali tabel di-redraw
	            updatePaginationIcons();
	        }
		})
	}



	$("#btn_add").on('click',function(e){
		e.preventDefault()
		
		$("#modal_add").modal('show')
		// loading
		$("#modal_add").find('.modal-content').html(loadingLdsRing)
		$("#modal_add").find('.modal-content').load(baseUrl+'customer/add')
	})

	$("#datatable").delegate(".datatable-edit", "click", function (e) {
		  var url = $(this).attr("data-link");
		  e.preventDefault()
			
			$("#modal_edit").modal('show')
			// loading
			$("#modal_edit").find('.modal-content').html(loadingLdsRing)
			$("#modal_edit").find('.modal-content').load(url)

	})


	$("#datatable").delegate(".datatable-detail", "click", function (e) {
		  var url = $(this).attr("data-link");
		  e.preventDefault()
			
			$("#modal_detail").modal('show')
			// loading
			$("#modal_detail").find('.modal-content').html(loadingLdsRing)
			$("#modal_detail").find('.modal-content').load(url)


	})


	// Fungsi untuk mengupdate ikon pagination
	function updatePaginationIcons() {
	    $('.paginate_button.previous').empty()
	        .addClass('d-flex justify-content-center align-items-center')
	        .html("<i class='bx bx-chevron-left' style='font-size: 26px;'></i>");
	        
	    $('.paginate_button.next').empty()
	        .addClass('d-flex justify-content-center align-items-center')
	        .html("<i class='bx bx-chevron-right' style='font-size: 26px;'></i>");
	}


	$(document).delegate('.btn-export','click',function(e){

		const type = $(this).attr('data-type')
		$("#modal_filter_export").modal('show')		
		$('input[name="type_export"]').val(type)
		

	})


	$("#export_data").on('submit',function(e) {
		e.preventDefault()

		const type = $('input[name="type_export"]').val()
		const year = $('select[name="year"]').val()
		const village = $('select[name="village"]').val()

		// Validasi
		if (!year || year === "") {

			iziToast.show({
	          title: 'Gagal',
	          message: 'Silakan pilih tahun terlebih dahulu',
	          color: 'red',
	          position: 'topCenter'
	        });
		  	return false;
		}

		if (!village || village === "") {

		  	iziToast.show({
	          title: 'Gagal',
	          message: 'Silakan pilih desa terlebih dahulu',
	          color: 'red',
	          position: 'topCenter'
	        });
		  	return false;
		}

		// $("#modal_filter_export").modal('hide')
		window.open(`<?= base_url() ?>customer/export/${type}/${year}/${village}`, '_blank');

	})

</script>