
        
<!-- jQuery dulu -->
<script src="<?= base_url() ?>assets/vendor/libs/jquery/jquery.js"></script>

<!-- 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">


  const loadingLdsRing = `<div class="w-100 d-flex justify-content-center aling-items-center py-5">
      <div class="lds-ring-md">
        <div></div>
        <div></div>
        <div></div>
        <div></div>
      </div>
    </div>`
	let start 		= 0
	let limit 		= 10
	let keyword 	= null
	let hasNext 	= false
	let page 			= 1

	let packages 			= []
	let subdistricts 	= []
	let villages 			= []
	let months 				= []

	let category 			= []
	let type 					= []

	function getLimitOnLoad()
	{
		if( window.innerWidth<765 ){
			return 10
		}else{
			return 12
		}
	}
	

	jQuery(document).ready(function($) {

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

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

    $("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 = [];

          $.each(data.data, function(index, item) {
            option.push({
              id: item.id,
              text: item.name,
            });
          });
          return {
            results: option,
            more: more,
          };
        },
      },
    });


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

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

    $("select[name=village_sm]").select2({
      dropdownParent: $("#village_sm").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 = [];

          $.each(data.data, function(index, item) {
            option.push({
              id: item.id,
              text: item.name,
            });
          });
          return {
            results: option,
            more: more,
          };
        },
      },
    });

		// loadData()
		

	})

	// MD
	$("select[name=package]").on('change',function(e) {

		const id = $(this).val()
		const label = $(this).find('option:selected').text()
		
		if(id!=''&&id!=null){

			if(packages.length>0){
				let noExits = true
				packages.forEach(item=>{
					if(Object.keys(item).length>0){
						if(parseInt(item.id)==parseInt(id)){
							noExits = false
						}
					}
				})

				if(noExits){
					packages.push({
						id, label
					})		
				}

			}else{
				packages.push({
					id, label
				})
			}
		}

		$("select[name='package']").val(null).trigger('change');
		showLabelsPackage()

	})


	// SM
	$("select[name=package_sm]").on('change',function(e) {

		const id = $(this).val()
		const label = $(this).find('option:selected').text()
		
		if(id!=''&&id!=null){

			if(packages.length>0){
				let noExits = true
				packages.forEach(item=>{
					if(Object.keys(item).length>0){
						if(parseInt(item.id)==parseInt(id)){
							noExits = false
						}
					}
				})

				if(noExits){
					packages.push({
						id, label
					})		
				}

			}else{
				packages.push({
					id, label
				})
			}
		}

		$("select[name='package_sm']").val(null).trigger('change');
		showLabelsPackage()

	})


	// MD
	$("select[name=subdistrict]").on('change',function(e) {

		const id = $(this).val()
		const label = $(this).find('option:selected').text()
		
		if(id!=''&&id!=null){

			if(subdistricts.length>0){
				let noExits = true
				subdistricts.forEach(item=>{
					if(Object.keys(item).length>0){
						if(parseInt(item.id)==parseInt(id)){
							noExits = false
						}
					}
				})

				if(noExits){
					subdistricts.push({
						id, label
					})		
				}

			}else{
				subdistricts.push({
					id, label
				})
			}
		}
		
		$("select[name='subdistrict']").val(null).trigger('change');
		showLabelsSubdistrict()

	})

	// SM	
	$("select[name=subdistrict_sm]").on('change',function(e) {

		const id = $(this).val()
		const label = $(this).find('option:selected').text()
		
		if(id!=''&&id!=null){

			if(subdistricts.length>0){
				let noExits = true
				subdistricts.forEach(item=>{
					if(Object.keys(item).length>0){
						if(parseInt(item.id)==parseInt(id)){
							noExits = false
						}
					}
				})

				if(noExits){
					subdistricts.push({
						id, label
					})		
				}

			}else{
				subdistricts.push({
					id, label
				})
			}
		}
		
		$("select[name='subdistrict_sm']").val(null).trigger('change');
		showLabelsSubdistrict()

	})


	// MD
	$("select[name=village]").on('change',function(e) {

		const id = $(this).val()
		const label = $(this).find('option:selected').text()
		
		if(id!=''&&id!=null){

			if(villages.length>0){
				let noExits = true
				villages.forEach(item=>{
					if(Object.keys(item).length>0){
						if(parseInt(item.id)==parseInt(id)){
							noExits = false
						}
					}
				})

				if(noExits){
					villages.push({
						id, label
					})		
				}

			}else{
				villages.push({
					id, label
				})
			}
		}
		
		$("select[name='village']").val(null).trigger('change');
		showLabelsVillage()

	})

	// SM
	$("select[name=village_sm]").on('change',function(e) {

		const id = $(this).val()
		const label = $(this).find('option:selected').text()
		
		if(id!=''&&id!=null){

			if(villages.length>0){
				let noExits = true
				villages.forEach(item=>{
					if(Object.keys(item).length>0){
						if(parseInt(item.id)==parseInt(id)){
							noExits = false
						}
					}
				})

				if(noExits){
					villages.push({
						id, label
					})		
				}

			}else{
				villages.push({
					id, label
				})
			}
		}
		
		$("select[name='village_sm']").val(null).trigger('change');
		showLabelsVillage()

	})



	function showLabelsPackage()
	{

		$(".parent_packages").html('')

		if(packages.length>0){
				packages.forEach((item,index)=>{
					if(Object.keys(item).length>0){
						$(".parent_packages").append(`<span class="badge bg-label-primary d-flex align-items-center py-1 me-1 mb-2" style="font-size: 12px; display: inline-flex !important; width: fit-content;">
	              <span>${item.label}</span>
	              <i class='bx bx-x' data-index="${index}" ></i>
	            </span>`)
					}

				})
		}
	}


	function showLabelsSubdistrict()
	{

		$(".parent_subdistricts").html('')

		if(subdistricts.length>0){
				subdistricts.forEach((item,index)=>{
					if(Object.keys(item).length>0){
						$(".parent_subdistricts").append(`<span class="badge bg-label-primary d-flex align-items-center py-1 me-1 mb-2" style="font-size: 12px; display: inline-flex !important; width: fit-content;">
	              <span>${item.label}</span>
	              <i class='bx bx-x' data-index="${index}" ></i>
	            </span>`)
					}

				})
		}
	}


	function showLabelsVillage()
	{

		$(".parent_villages").html('')

		if(villages.length>0){
				villages.forEach((item,index)=>{
					if(Object.keys(item).length>0){
						$(".parent_villages").append(`<span class="badge bg-label-primary d-flex align-items-center py-1 me-1 mb-2" style="font-size: 12px; display: inline-flex !important; width: fit-content;">
	              <span>${item.label}</span>
	              <i class='bx bx-x' data-index="${index}" ></i>
	            </span>`)
					}

				})
		}
	}


	$(".parent_packages").delegate('.bx-x','click',function(e) {

		e.preventDefault()

		const index = $(this).attr('data-index')

		packages[index] = {}
		showLabelsPackage()

	})


	$(".parent_subdistricts").delegate('.bx-x','click',function(e) {

		e.preventDefault()

		const index = $(this).attr('data-index')

		subdistricts[index] = {}
		showLabelsSubdistrict()

	})

	$(".parent_villages").delegate('.bx-x','click',function(e) {

		e.preventDefault()

		const index = $(this).attr('data-index')

		villages[index] = {}
		showLabelsVillage()


		loadingMd()
		const villages_ = villages.filter(item=>{
			return Object.keys(item).length>0
		})

		let startDate = $('input[name="start_date_sm"]').val()
		if(window.innerWidth>=765){
			startDate = $('input[name="start_date"]').val()
		}

		if(Object.keys(villages_).length<=0||startDate==null||startDate==""){
			resetForm()
		}else{
			loadData()
		}



	})

	function loadData() {
		
		const packages_ = packages.filter(item=>{
			return Object.keys(item).length>0
		})

		const subdistricts_ = subdistricts.filter(item=>{
			return Object.keys(item).length>0
		})

		const villages_ = villages.filter(item=>{
			return Object.keys(item).length>0
		})


		let startDate = $('input[name="start_date_sm"]').val()
		let endDate		= $('input[name="end_date_sm"]').val()

		if(window.innerWidth>=765){
			startDate = $('input[name="start_date"]').val()
			endDate		= $('input[name="end_date"]').val()
		}


		$.ajax({
			url: `<?= base_url() ?>payment/get-all-data-pay-customer`,
			type: 'POST',
			dataType: 'json',
			data: {
				start,
				limit,
				keyword,
				startDate,
				endDate,
				packages: packages_,
				subdistricts: subdistricts_,
				villages: villages_,
			},
			success: response => {
				
				if(response.code==200){
					if(response.success){
						if(response.data.length>0){

							setCountResultData(response.data.length)

							$("#container_product").html('')

							response.data.forEach(row=>{

								$("#container_product").append(createItem(row))

							})
						}else{

							setCountResultData(0)

							$("#container_product").html(`<div class="col-12 d-flex justify-content-center align-items-center flex-column">
                      <img src="<?= base_url() ?>assets/images/ic-empty-payment.png" style="width: 330px;" class="mb-n5">
                      <p class="mb-0">Data Yang Anda Cari Tidak Ada</p>
                      <p class="mb-0">Silahkan lakukan filter atau seraching data </p>
                    </div>`)
						}



					}
				}
			},
			error: () => {

			}
		})

	}

	function setCountResultData(count)
	{
			if(window.innerWidth>=765){
				$('.label-total-data').html(`Total Pelanggan Yang Ditemukan Ada <strong class="">${count}</strong> Data`)

			}else{
				$('.label-total-data').html(`Total ${count} Data`)
			}
	}


	$(".searching").on('input',function() {

		const villages_ = villages.filter(item=>{
			return Object.keys(item).length>0
		})

		let startDate = $('input[name="start_date_sm"]').val()
		if(window.innerWidth>=765){
			startDate = $('input[name="start_date"]').val()
		}

		if(Object.keys(villages_).length<=0||startDate==null||startDate==""){
				iziToast.show({
          title: 'Gagal',
          message: 'Silahkan lakukan filter desa dan bulan terlebih dahulu',
          color: 'red',
          position: 'topCenter'
        });
        return
		}



		const searching = $(this).val()
		if(searching.trim()!=''){
			page = 1
			start = 0
			keyword = searching

			loadingMd()
			loadData()
		}else{
			keyword = null
			loadingMd()
			loadData()
		
		}

	})

	$(".btn_show").on('click',function(e) {
		e.preventDefault()


		const villages_ = villages.filter(item=>{
			return Object.keys(item).length>0
		})

		let startDate = $('input[name="start_date_sm"]').val()
		if(window.innerWidth>=765){
			startDate = $('input[name="start_date"]').val()
		}

		if(startDate==null||startDate==""){
				iziToast.show({
          title: 'Gagal',
          message: 'Silahkan pilih bulan terlebih dahulu',
          color: 'red',
          position: 'topCenter'
        });
        return
		}

		if(Object.keys(villages_).length<=0){
				iziToast.show({
          title: 'Gagal',
          message: 'Silahkan pilih desa terlebih dahulu',
          color: 'red',
          position: 'topCenter'
        });
        return
		}


		setFilterIsActive(true)

		loadingMd()
		loadData()
		$('#modal_filter').modal('hide')

		showParentSeaching(true)

	})

	function setFilterIsActive(isTrue)
	{
		if(isTrue){
			$(".btn_filter").removeClass('filter-btn')
			$(".btn_filter").addClass('filter-btn-active')
		}else{
			$(".btn_filter").removeClass('filter-btn-active')
			$(".btn_filter").addClass('filter-btn')

		}
	}

	function resetForm()
	{

			packages 			= []
			subdistricts 	= []
			villages 			= []
			keyword 			= null

			setFilterIsActive(false)
			loadingMd()

			$(".label-total-data").html(``)

			$(".searching").val('')
			$(".parent_packages").html('')
			$(".parent_subdistricts").html('')
			$(".parent_villages").html('')

			$("#container_product").html(`<div class="col-12 d-flex justify-content-center align-items-center flex-column">
        <img src="<?= base_url() ?>assets/images/ic-empty-payment.png" style="width: 330px;" class="mb-n5">
        <p class="mb-0">Data Masih Kosong</p>
        <p class="mb-0 text-center">Silahkan lakukan filter desa dan bulan terlebih dahulu</p>
      </div>`)

			showParentSeaching(false)
			
	}


	function showParentSeaching(isShow)
	{

			if(isShow){
				
				if(window.innerWidth<765){

					$(".parent-filter-hide").removeClass('d-flex')
					$(".parent-filter-hide").addClass('d-none')

					$(".parent-filter-show").removeClass('d-none')
					$(".parent-filter-show").addClass('d-flex')

				}else{

					$(".parent-filter-show").removeClass('d-none')
					$(".parent-filter-show").addClass('d-flex')

				}
			}else{
				if(window.innerWidth<765){
					
					$(".parent-filter-hide").removeClass('d-none')
					$(".parent-filter-hide").addClass('d-flex')

					$(".parent-filter-show").removeClass('d-flex')
					$(".parent-filter-show").addClass('d-none')

				}else{
					$(".parent-filter-show").removeClass('d-flex')
					$(".parent-filter-show").addClass('d-md-none')
				}
			}

	}

	
	document.getElementById('modal_filter').addEventListener('hidden.bs.modal', event => {
	  
		const villages_ = villages.filter(item=>{
			return Object.keys(item).length>0
		})

		let startDate = $('input[name="start_date_sm"]').val()
		if(window.innerWidth>=765){
			startDate = $('input[name="start_date"]').val()
		}

			if(startDate==null||startDate==""||Object.keys(villages_).length<=0){
				setFilterIsActive(false)
					
			}else{
				setFilterIsActive(true)
			}

  });


	document.getElementById('modal_detail').addEventListener('hidden.bs.modal', event => {
	  
		month = []

  });


	function createItem(item)
	{

			const total = Number(item.price) * Number(item.countHasntPay)

			return `<div data-id="${item.id}" class="item-customer col-12 col-md-6">
                      <div class="card w-100">
                        <div class="w-100 row mx-0 px-0">
                          <div class="col-2 py-3">
                            <div class="d-flex justify-content-center align-items-center" style="border-radius: 50%; background-color: #f2efef; width: 50px; height: 50px;">
                              <i class="bx bx-user" style="font-size: 30px;"></i>
                            </div>
                          </div>
                          <div class="col-10 d-flex justify-content-between  ps-3">
                            <div class="d-flex flex-column pt-3">
                              <span class="fw-semibold">${item.name}</span>
                              <span class="" style="font-size: 12px;">${item.phone}</span>
                            </div>
                            <div class="d-flex flex-column justify-content-between align-items-end">
                              <div class="mb-3 " style="padding-top: 15px;">
                                <span class="badge bg-label-warning" style="font-size: 10px;">${item.village}</span>
                              </div>
                              <span class="mb-2 text-success" style="font-size: 14px;">
                                Rp. ${total.toLocaleString('id-ID')}
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>`

	}


	$(".btn_filter").on('click',function(e) {
		e.preventDefault()

		$('#modal_filter').modal('show')

	})



	$('#container_product').delegate('.item-customer','click',function() {

		const id 	= $(this).attr('data-id')

		months 		= []
		$("#modal_detail").modal('show')


		$.ajax({
			url: `<?= base_url() ?>payment/get-all-data-customer`,
			type: 'POST',
			dataType: 'json',
			data: {
				id,
			},
			success: response => {
				
				if(response.code==200){
					if(response.success){
						if(Object.keys(response.data).length>0){

							const row  = response.data
							
							let el = `
							<form id="add_pay">
							<div class="modal-header">
                <h1 class="modal-title fs-4">Detail Pelanggan</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
              <div class="modal-body px-0">
              	<input type="hidden" name="hide_id" style="width: 0; height: 0; opacity: 0; z-index: 0;" value="${row.id}">
								<table class="table w-100">
	                  <tr>
	                    <td style="width: 20%;">Nama</td>
	                    <td>: ${row.name}</td>
	                  </tr>
	                  <tr>
	                    <td>Kecamatan</td>
	                    <td>: <span class="badge bg-danger">${row.subdistrict_name}</span> </td>
	                  </tr>
	                  <tr>
	                    <td>Desa</td>
	                    <td>: <span class="badge bg-warning">${row.village_name}</span> </td>
	                  </tr>
	                  <tr>
	                    <td>Nomor Telepon</td>
	                    <td>: ${row.phone}</td>
	                  </tr>
	                  <tr>
	                    <td>Paket Internet</td>
	                    <td>: ${row.package_name}</td>
	                  </tr>
	                </table>
	                <div class="mt-2">
	                  <p class="card-header">Detail Pembayaran (<?= date('Y') ?>)</p>
	                </div>

	                <div class="px-3" style="overflow-y: scroll; height: 250px;">
	                  <table class="table w-100">`

	               let elPay = ''
	               if(row.pays.length>0){
	               		row.pays.forEach((item,index)=>{

	               			const total = Number(item.total)
	               			elPay += `<tr>
	                      <td class="ps-1" style="width: 2%; text-align: center;">
	                        ${index+1}
	                      </td>
	                      <td>
	                        <strong>${item.monthName}</strong> <br>
	                        <span class="${ item.have ? 'text-success' : 'text-danger' }">Rp. ${total.toLocaleString('id-ID')}</span>
	                      </td>
	                      <td style="width: 10%;">
	                        <div class="form-check d-flex justify-content-center">
	                          <input class="form-check-input change-payment" data-id="${item.month}" type="checkbox" ${item.have ? 'checked disabled readonly' : ''} >
	                        </div>
	                      </td>
	                    </tr>`

	               		})
	               }

               el += elPay
               el += ` 
                  </table>
                  </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                <button type="submit" class="btn btn-primary" >Simpan</button>
              </div>

            </form>`

							$("#modal_detail").find('.modal-content').html(el)


						}else{
							$("#modal_detail").find('.modal-content').html(``)
						}



					}
				}
			},
			error: () => {

			}
		})




	})	



	$("#modal_detail").delegate('.change-payment','change',function() {

		const month = $(this).attr('data-id')
		
		if ($(this).prop('checked')) {
		    months.push(month)
		} else {
		    deleteMonths(month)
		}

	})



	function deleteMonths(val)
	{

		
		if(months.length>0){
			months.forEach((item,index)=>{
				
				if(Number(item)==Number(val)){
					months[index] = ''
				}

			})
		}
	}

	$(document).on('submit', '#add_pay', function(e) {
	    e.preventDefault();
	    
			const id = $(this).find('input[name="hide_id"]').val()
			const months_ = months.filter(row=>{
				return row != ''
			})

			

			$.ajax({
				url: `<?= base_url() ?>payment/save-pay`,
				type: 'POST',
				dataType: 'json',
				data: {
					id,
					month: months_.sort()
				},
				success: response => {
					

					if(response.code==200){
						if(response.success){

							iziToast.show({
			          title: 'Berhasil',
			          message: response.message,
			          color: 'green',
			          position: 'topRight'
			        });

							if(response.data.length>0){

								// susun nota

							}

							loadingMd()
							loadData()
							$("#modal_detail").modal('hide')
							months = [];

						}else{
							iziToast.show({
			          title: 'Gagal',
			          message: response.message,
			          color: 'red',
			          position: 'topCenter'
			        });
						}
					}else{
						iziToast.show({
		          title: 'Gagal',
		          message: 'Terjadi kesalahan. pastikan anda terkoneksi dengan internet',
		          color: 'red',
		          position: 'topCenter'
		        });
					}


					calculateTotal()

				},
				error: () => {
					iziToast.show({
	          title: 'Gagal',
	          message: 'Terjadi kesalahan. pastikan anda terkoneksi dengan internet',
	          color: 'red',
	          position: 'topCenter'
	        });
				}
			})

	});















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

		const discount = parseRupiahToNumber($('input[name="discount"]').val())
		
		$('#label_discount').html(`Rp. ${discount.toLocaleString('id-ID')}`)

		calculateTotal()


		$("#modal_discount").modal('hide')
	})


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

		const moneyPay = parseRupiahToNumber($('input[name="money_pay"]').val())

		$('#label_money_pay').html(`Rp. ${moneyPay.toLocaleString('id-ID')}`)

		calculateTotal()

		$("#modal_money_pay").modal('hide')
	})


	$("#set_discount").on('click',function(e) {
		e.preventDefault()


		const discount = parseRupiahToNumber($('	#label_discount').html())
		
		if(discount!=0){
			$('input[name="discount"]').val(discount.toLocaleString('id-ID'))
		}else{
			$('input[name="discount"]').val('')
		}


		$("#modal_discount").modal('show')

	})


	$("#set_money_pay").on('click',function(e) {
		e.preventDefault()


		const moneyPay = parseRupiahToNumber($('	#label_money_pay').html())
		
		if(moneyPay!=0){
			$('input[name="money_pay"]').val(moneyPay.toLocaleString('id-ID'))
		}else{
			$('input[name="money_pay"]').val('')
		}


		$("#modal_money_pay").modal('show')

	})


	$('.category-btn').on('click',function(e) {
		e.preventDefault()

		type = $(this).attr('data-type')
		const value = $(this).attr('data-value')

		if(category==value){
			category = null

			$(this).removeClass('active')

		}else{
			category = value
			$('.category-btn').removeClass('active')

			$(this).addClass('active')

		}


		page = 1
		start = 0
		keyword = null

		loadingMd()
		loadData()

	})


	function loadCart() {
		
		$.ajax({
			url: `<?= base_url() ?>sale/get-all-cart`,
			type: 'POST',
			dataType: 'json',
			data: {
			},
			success: response => {
				

				if(response.code==200){
					if(response.success){

						carts = response.data
						$("#label_count_product_cart").html(response.data.length)

						if(response.data.length>0){

							$("#container_cart").html('')

							response.data.forEach(row=>{

								const price = Number(row.product_price)

								$("#container_cart").append(`<div class="item-card mb-2">
                    <img src="<?= base_url() ?>uploads/goods/${row.image}" class="item-image" alt="Raspberry Tart">
                    
                    <div class="item-info">
                      <div>${row.product_name}</div>
                      <div class="item-price">Rp. ${price.toLocaleString('id-ID')}</div>
                    </div>

                    <div class="qty-control">
                      <button class="qty-btn btn-minus" data-id="${row.id}" data-quantity="${row.quantity}" >−</button>
                      <div>${row.quantity}</div>
                      <button class="qty-btn btn-plus" data-id="${row.id}" data-quantity="${row.quantity}">+</button>
                    </div>
                  </div>`)

							})
						}else{

							resetForm()

							$("#container_cart").html(`
                    <div class="col-12 w-100 d-flex justify-content-center flex-column align-items-center">
                      <div>
                        <img src="<?= base_url() ?>assets/images/ic-empty-cart.png" style="height: 250px;">
                      </div>
                      <span>Tidak ada produk pada keranjang anda</span>
                    </div>`)
						}




					}
				}


				calculateTotal()

			},
			error: () => {

			}
		})

	}
	

	function calculateTotal()
	{

		let subTotal = 0
		let grandTotal = 0

		if(carts.length>0){
			carts.forEach(item=>{
				subTotal += (Number(item.product_price)*Number(item.quantity))
			})
		}

		const discount_ = $('#label_discount').html()
		const discount  = discount_ != '-' ? parseRupiahToNumber(discount_) : 0 

		grandTotal += subTotal
		grandTotal -= discount

		$("#label_sub_total").html(`Rp. ${subTotal.toLocaleString('id-ID')}`)
		$("#label_grand_total").html(`Rp. ${grandTotal.toLocaleString('id-ID')}`)

		const  moneyPay_ = $('#label_money_pay').html()
		const  moneyPay = moneyPay_ != '-' ? parseRupiahToNumber(moneyPay_) : 0 

		if(moneyPay>1){

			const changeMoney =  moneyPay - grandTotal
			$("#label_change_money").html(`Rp. ${changeMoney.toLocaleString('id-ID')}`)
		}




	}





	$('#container_cart').delegate('.btn-plus','click',function() {

		const id = $(this).attr('data-id')
		const quantity = $(this).attr('data-quantity')
		const newQuantity = Number(quantity) + 1

		updateQuantity(id,newQuantity,"PLUS")

	})	


	function updateQuantity(id,quantity,type)
	{



		$.ajax({
			url: `${baseUrl}sale/change-quantity`,
			type: 'post',
			dataType: 'json',
			data: {
				id,quantity,type
			},
			success: response => {
					
				if(response.code==200){
					if(response.success){

						iziToast.show({
		          title: 'Berhasil',
		          message: response.message,
		          color: 'green',
		          position: 'topRight'
		        });

						loadingCart()
						loadCart()

					}else{
						iziToast.show({
		          title: 'Gagal',
		          message: response.message,
		          color: 'red',
		          position: 'topCenter'
		        });
					}
				}else{
					iziToast.show({
	          title: 'Gagal',
	          message: 'Terjadi kesalahan. pastikan anda terkoneksi dengan internet',
	          color: 'red',
	          position: 'topCenter'
	        });
				}

			},
			error: () => {
				iziToast.show({
          title: 'Gagal',
          message: 'Terjadi kesalahan. pastikan anda terkoneksi dengan internet',
          color: 'red',
          position: 'topCenter'
        });
			}
		})


	}


	$('.btn-next').on('click',function() {

		page++
		start += limit
		hasNext = false
		
		loadingMd()
		loadData()
	})	


	$('.btn-prev').on('click',function() {

		page--
		start -= limit
		hasNext = false
		
		loadingMd()
		loadData()
	})	



	$("#container_product").delegate('.item-product','click',function(e) {
		e.preventDefault()

		const id = $(this).attr('data-id')
		const name = $(this).attr('data-name')
		const price_buy = $(this).attr('data-price_buy')
		const price_sale = $(this).attr('data-price_sale')
		const discount = $(this).attr('data-discount')
		const price = $(this).attr('data-price')


		$.ajax({
			url: `${baseUrl}sale/add-to-cart`,
			type: 'post',
			dataType: 'json',
			data: {
				id,name,price_buy,price_sale,discount,price
			},
			success: response => {
					
				if(response.code==200){
					if(response.success){

						iziToast.show({
		          title: 'Berhasil',
		          message: response.message,
		          color: 'green',
		          position: 'topRight'
		        });

						loadingCart()
						loadCart()

					}else{
						iziToast.show({
		          title: 'Gagal',
		          message: response.message,
		          color: 'red',
		          position: 'topCenter'
		        });
					}
				}else{
					iziToast.show({
	          title: 'Gagal',
	          message: 'Terjadi kesalahan. pastikan anda terkoneksi dengan internet',
	          color: 'red',
	          position: 'topCenter'
	        });
				}

			},
			error: () => {
				iziToast.show({
          title: 'Gagal',
          message: 'Terjadi kesalahan. pastikan anda terkoneksi dengan internet',
          color: 'red',
          position: 'topCenter'
        });
			}
		})

	})



	function loadingCart()
	{

		$('#container_cart').html('')
		for(let i = 1; i <= 8; i++){
			
			$('#container_cart').append(`<!-- Skeleton loading card -->
            <div class="item-card mb-2 d-flex align-items-center p-2 rounded" style="gap: 12px;">
              <!-- Gambar Placeholder -->
              <div class="rounded" style="
                width: 60px;
                height: 60px;
                background: linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%);
                background-size: 200% 100%;
                animation: shimmer 1.2s infinite;
              "></div>

              <!-- Info Text Placeholder -->
              <div class="flex-grow-1">
                <div style="
                  width: 70%;
                  height: 14px;
                  margin-bottom: 8px;
                  border-radius: 4px;
                  background: linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%);
                  background-size: 200% 100%;
                  animation: shimmer 1.2s infinite;
                "></div>
                <div style="
                  width: 40%;
                  height: 14px;
                  border-radius: 4px;
                  background: linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%);
                  background-size: 200% 100%;
                  animation: shimmer 1.2s infinite;
                "></div>
              </div>

              <!-- Qty Placeholder -->
              <div class="d-flex align-items-center" style="gap: 6px;">
                <div style="
                  width: 24px;
                  height: 24px;
                  border-radius: 50%;
                  background: linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%);
                  background-size: 200% 100%;
                  animation: shimmer 1.2s infinite;
                "></div>
                <div style="
                  width: 16px;
                  height: 14px;
                  border-radius: 4px;
                  background: linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%);
                  background-size: 200% 100%;
                  animation: shimmer 1.2s infinite;
                "></div>
                <div style="
                  width: 24px;
                  height: 24px;
                  border-radius: 50%;
                  background: linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%);
                  background-size: 200% 100%;
                  animation: shimmer 1.2s infinite;
                "></div>
              </div>
            </div>`)
		}

	}


	function loadingMd()
	{
		$('#container_product').html('')
		for(let i = 1; i <= limit; i++){
			
			$('#container_product').append(`<div class="col-12 col-md-6">
                        <div class="card w-100">
                          <div class="w-100 row mx-0 px-0">
                            <div class="col-2 py-3">
                              <div class="skeleton skeleton-circle mx-auto"></div>
                            </div>
                            <div class="col-10 d-flex justify-content-between ps-3">
                              <div class="d-flex flex-column pt-3 w-75">
                                <div class="skeleton skeleton-line skeleton-md"></div>
                                <div class="skeleton skeleton-line skeleton-sm"></div>
                              </div>
                              <div class="d-flex flex-column justify-content-between align-items-end w-25 pt-3">
                                <div class="skeleton skeleton-line skeleton-sm mb-3" style="height: 16px;"></div>
                                <div class="skeleton skeleton-line skeleton-sm mb-2" style="height: 14px;"></div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>`)
		}
	}

	function loadingSm() {
		
	}


	$("#btn_add").on('click',function(e){
		e.preventDefault()
		
		$("#modal_add").modal('show')
		// loading
		$("#modal_add").find('.modal-content').load(baseUrl+'category/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').load(url)


	})



	function parseRupiahToNumber(str) {
	  const cleaned = str.replace(/[^0-9]/g, '');
	  return parseInt(cleaned, 10) || 0;
	}

	$(document).on('click', '#btnPrintStruk', function (e) {
	 	e.preventDefault()
      const content = $(document).find('#printable-struk').clone(); // 
		  const win = window.open('', '_blank', 'width=800,height=800');

		  win.document.open();
		  win.document.write(`
		    <html>
		      <head>
		        <title>Print Struk</title>
		        <style>
		          @media print {
		            @page {
		              size: 158mm auto;
		              margin: 0;
		            }
		            body {
		              font-family: Arial, sans-serif;
		              font-size: 14px;
		              padding: 10px;
		            }
		            .receipt {
		              width: 100%;
		            }
		          }
		        </style>
		      </head>
		      <body>${content.html()}</body>
		    </html>
		  `);
		  win.document.close();

		  // Tunggu konten dimuat sebelum print
		  win.onload = function () {
		    win.focus();
		    win.print();
		    win.close();
		  };



  });

  $("#go_to_cart").on('click',function(e) {

  	e.preventDefault()

  	window.location.href=`<?= base_url() ?>sale/cart`


  })

</script>



                <!-- END CONTENT -->
            </div>
 