
<script src="<?= base_url() ?>assets/vendor/libs/jquery/jquery.js"></script>
<script src="<?= base_url(); ?>assets/libs/jquery.number/jquery.number.min.js"></script>



<script type="text/javascript">

	let start 		= 0
	let limit 		= getLimitOnLoad()
	let keyword 	= null
	let type 			= null
	let category 	= null
	let hasNext 	= false
	let page 			= 1

	let carts = []

  // $('input[name="discount"]').number(true, 0);
  // $('input[name="money_pay"]').number(true, 0);

  $('input[name="money_pay"]').on('input', function() {
    // Simpan posisi kursor
    let cursorPosition = this.selectionStart;
    
    // Dapatkan nilai input dan hapus semua titik
    let rawValue = $(this).val().replace(/\./g, '');
    
    // Format angka dengan titik sebagai pemisah ribuan
    let formattedValue = formatNumber(rawValue);
    
    // Update nilai input
    $(this).val(formattedValue);
    
    // Kembalikan posisi kursor (adjust untuk penambahan/pengurangan titik)
    let dotCountBefore = ($(this).val().match(/\./g) || []).length;
    let newCursorPos = cursorPosition + (($(this).val().match(/\./g) || []).length - dotCountBefore);
    
    this.setSelectionRange(newCursorPos, newCursorPos);
  });

  $('input[name="discount"]').on('input', function() {
    // Simpan posisi kursor
    let cursorPosition = this.selectionStart;
    
    // Dapatkan nilai input dan hapus semua titik
    let rawValue = $(this).val().replace(/\./g, '');
    
    // Format angka dengan titik sebagai pemisah ribuan
    let formattedValue = formatNumber(rawValue);
    
    // Update nilai input
    $(this).val(formattedValue);
    
    // Kembalikan posisi kursor (adjust untuk penambahan/pengurangan titik)
    let dotCountBefore = ($(this).val().match(/\./g) || []).length;
    let newCursorPos = cursorPosition + (($(this).val().match(/\./g) || []).length - dotCountBefore);
    
    this.setSelectionRange(newCursorPos, newCursorPos);
  });

  // Fungsi format angka
  function formatNumber(num) {
    return num.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ".");
  }

	function getLimitOnLoad()
	{
		if( (window.innerWidth>=576&&window.innerWidth<765) ){
			return 9
		}else if(window.innerWidth>=765&&window.innerWidth<992){
			return 9
		}else if(window.innerWidth>=992){
			return 12
		}else{
			return 8
		}
	}
	

	$(document).ready(function(){

		loadData()
		loadCart()

	})


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


	 		Swal.fire({
        title: "Pertanyaan?",
        text: "Silakan periksa kembali barang belanjaan pelanggan sebelum melanjutkan checkout, karena transaksi yang sudah diproses tidak dapat dibatalkan!",
        icon: "question",
        showCancelButton: !0,
        confirmButtonColor: "#0349b1",
        cancelButtonText: "Batal",
        confirmButtonText: "Checkout!",
        customClass: {
            container: 'sweetalert-container',
            popup: 'sweetalert-popup'
        }
      }).then((result) => {
        if (result.isConfirmed) {
          


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

					$.ajax({
						url: `<?= base_url() ?>sale/create-order`,
						type: 'POST',
						dataType: 'json',
						data: {
							discount, moneyPay
						},
						success: response => {
							

							if(response.code==200){
								if(response.success){
																	
									iziToast.show({
					          title: 'Berhasil',
					          message: response.message,
					          color: 'green',
					          position: 'topRight'
					        });

									resetForm()
									loadingCart()
									loadCart()

									let el = `<div id="printable-struk" class="receipt" style="background: white; padding: 20px; border-radius: 10px; width: 100%; font-family: Arial, sans-serif; font-size: 13px;">
                    <div style="text-align: center; border-bottom: 1px dashed #aaa; padding-bottom: 10px; margin-bottom: 10px;">
                      <img src="https://cdn-icons-png.flaticon.com/512/1041/1041880.png" alt="Logo Toko" style="width: 40px; margin-bottom: 5px;">
                      <h5 style="margin: 0;">Toko Serba Ada</h5>
                      <div><?= addressApp() ?></div>
                      <small>Selamat datang di toko kami</small><br>
                      <small><?= lateBrand() ?></small>
                    </div>

                    <div class="w-100">
                      <span>No: 2024</span>
                      <div class="d-flex justify-content-between">
                        <span>06:52 2025-09-04</span>  
                        <span>Kasir: <?= session()->get('name') ?></span>
                      </div>
                    </div>

                    <hr style="border-top: 1px dashed #aaa; margin: 10px 0;">`

                    const subTotal			= Number(response.data.subtotal)
                    const discountTotal = Number(response.data.discount)
                    const grandTotal		= Number(response.data.grandtotal)
                    const changeMoney		= Number(response.data.changemoney)
                    const returnMoney		= Number(response.data.returnmoney)

                    if(response.data.items.length>0){
                    	response.data.items.forEach((item,index)=>{

                    		const price = Number(item.product_price)
                    		const total = Number(item.total)

                    		el += `<div class="mb-2">
		                      <strong>${index+1}. ${item.product_name} </strong><br>
		                      <div style="display: flex; justify-content: space-between;">
		                        <span>${item.quantity} x Rp ${price.toLocaleString('id-ID')}</span>
		                        <span>Rp ${total.toLocaleString('id-ID')}</span>
		                      </div>
		                    </div>`
                    	})
                    }

                    

                    el += `
                    <div style="margin-top: 10px;">
                      <strong>Informasi Lainya</strong><br>
                      <div style="display: flex; justify-content: space-between;">
                        <span>Subtotal</span><span>Rp ${subTotal.toLocaleString('id-ID')}</span>
                      </div>
                      <div style="display: flex; justify-content: space-between;">
                        <span>Diskon</span><span>Rp ${discountTotal.toLocaleString('id-ID')}</span>
                      </div>
                      <div style="display: flex; justify-content: space-between;">
                        <span>Total</span><span>Rp ${grandTotal.toLocaleString('id-ID')}</span>
                      </div>
                      <div style="display: flex; justify-content: space-between;">
                        <span>Uang Dibayarkan</span><span>Rp ${changeMoney.toLocaleString('id-ID')}</span>
                      </div>
                      <div style="display: flex; justify-content: space-between;">
                        <span>Kembalian</span><span>Rp ${returnMoney.toLocaleString('id-ID')}</span>
                      </div>
                    </div>

                    <div style="text-align: center; margin-top: 20px;">
                      Terima kasih telah berbelanja di toko kami<br>
                      <span><?= phoneBrand() ?></span>
                    </div>
                  </div>`

									$("#modal_struck").find('.modal-body').html(el)
									$("#modal_struck").modal('show')

								}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: () => {

						}
					})


        } else if (result.dismiss === Swal.DismissReason.cancel) {
          
        }
      });

	})


	$("#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')}`)
		}




	}


	function loadData() {
		
		$.ajax({
			url: `<?= base_url() ?>sale/get-all-product`,
			type: 'POST',
			dataType: 'json',
			data: {
				start,
				limit,
				keyword,
				category,
				type,
			},
			success: response => {
				
				if(response.code==200){
					if(response.success){
						if(response.data.data.length>0){

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

							response.data.data.forEach(row=>{

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

							})
						}else{
							$("#container_product").html(`
                    <div class="col-12 d-flex justify-content-center flex-column align-items-center pt-5">
                      <div>
                        <img src="<?= base_url() ?>assets/images/ic-empty-product.png" style="height: 250px;">
                      </div>
                      <span>Produk yang anda cari tidak di temukan</span>
                    </div>`)
						}


						hasNext = response.data.hasNext

						if(hasNext){
							$('.btn-next').show()
						}else{
							$('.btn-next').hide()
						}


						if(page==1){
							$('.btn-prev').hide()
						}else{
							$('.btn-prev').show()

						}

						$('.page-link-text').html(page)



					}
				}
			},
			error: () => {

			}
		})

	}



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

		const id = $(this).attr('data-id')
		const quantity = $(this).attr('data-quantity')
		const newQuantity = Number(quantity) - 1
		if(newQuantity<=0){

	 		Swal.fire({
        title: "Pertanyaan?",
        text: "Apakah anda yakin ingi menghapus produk ini dari keranjang!",
        icon: "question",
        showCancelButton: !0,
        confirmButtonColor: "#ffab00",
        cancelButtonText: "Batal",
        confirmButtonText: "Ya, Hapus!",
        customClass: {
            container: 'sweetalert-container',
            popup: 'sweetalert-popup'
        }
      }).then((result) => {
        if (result.isConfirmed) {
          updateQuantity(id,newQuantity,"MINUS")
        } else if (result.dismiss === Swal.DismissReason.cancel) {
          
        }
      });

		}else{
			updateQuantity(id,newQuantity,"MINUS")
		}

	})	


	$('#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()
	})	

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

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

			loadingMd()
			loadData()
		}else{
			page = 1
			start = 0
			keyword = ''
			
			loadingMd()
			loadData()
		}

	})

	function createItem(item)
	{


		if(item.discount!=null&&item.discount!=0&&item.discount!=""){

			const priceSale = Number(item.price_sale)
			const price = Number(item.price_sale) - ((Number(item.price_sale)*Number(item.discount))/100)

			return `<div data-id="${item.id}" data-name="${item.name}" data-price_buy="${item.price_buy}" data-price_sale="${item.price_sale}" data-discount="${item.discount}" data-price="${price}" class=" item-product col-sm-4 col-md-4 col-lg-3 col-6">
                  <div class="product-card">
                    <img src="<?= base_url() ?>uploads/goods/${item.image}" class="product-img" alt="Raspberry Tart">
                    <div class="product-title">${item.name}</div>
                    <div class="w-100 ">
                      <div>
                        <div class="mt-n2 mb-0">
                          <span class="label-price">Rp. ${price.toLocaleString('id-ID')}</span>
                        </div>
                        <span>
                          <span class="text-secondary label-price-discount ">Rp. ${priceSale.toLocaleString('id-ID')}</span>
                          <span class="text-danger label-discount">${item.discount}%</span>
                        </span>
                      </div>
                    </div>
                  </div>
                </div>`

		}

		const price = Number(item.price_sale)
		return `<div data-id="${item.id}" data-name="${item.name}" data-price_buy="${item.price_buy}" data-price_sale="${item.price_sale}" data-discount="${item.discount}" data-price="${price}" class=" item-product col-sm-4 col-md-4 col-lg-3 col-6">
          <div class="product-card">
            <img src="<?= base_url() ?>uploads/goods/${item.image}" class="product-img" alt="Raspberry Tart">
            <div class="product-title">${item.name}</div>
            <div class="w-100 ">
              <div>
                <div class="mt-n2 mb-0">
                  <span class="label-price">Rp. ${price.toLocaleString('id-ID')}</span>
                </div>
                <span>
                </span>
              </div>
            </div>
          </div>
        </div>`

	}


	$("#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-lg-4 col-sm-4 col-md-6 col-6">
                      <div class="card-skeleton">
                        <div class="skeleton skeleton-img"></div>
                        <div class="skeleton skeleton-line long mt-3"></div>
                        <div class="skeleton skeleton-line medium"></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 resetForm()
	{
			$('input[name="discount"]').val('')
			$('input[name="money_pay"]').val('')

			$('#label_discount').html(`-`)
			$('#label_money_pay').html(`-`)

			$('#label_change_money').html(`-`)

			calculateTotal()
	}



	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>
 