/home2/kerimkazan/dvf/assets/theme.js
function printSale(saleId) {
    // AJAX isteği yaparak ilgili satış bilgilerini alın
    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: { type: "print_forms", saleId: saleId },
        dataType: "json",
        success: function (response) {
            if (response.status) {
                // Satış bilgileri başarılı bir şekilde alındı
                var sale = response.sale;
                var saleProducts = response.saleProducts;

                // Yazdırma işlemi için bir pop-up penceresi oluşturun
                var printWindow = window.open('', '_blank');

                // Yazdırma işlemi için pop-up penceresinin içeriğini oluşturun
                printWindow.document.open();
                printWindow.document.write('<html><head><title>Satış Raporu</title>');
                printWindow.document.write('<link rel="stylesheet" type="text/css" href="yazdir3.css">');
                printWindow.document.write('<link rel="stylesheet" type="text/css" href="assets/fontawesome/css/all.min.css">');
                
                printWindow.document.write('</head><body>');

                // Satış raporu içeriğini oluşturun
                printWindow.document.write('<div class="print">');

                printWindow.document.write('<div class="row mb-5">');
                printWindow.document.write('<div class="col-6">');
				
                printWindow.document.write('<img src="qr.png" alt="QR Code" class="qr-code">');
                printWindow.document.write('<h1 style="font-size:24px;">' + response.brand + '</h1>');
                printWindow.document.write('</div>');
                printWindow.document.write('<div class="col-6 text-start">');
                printWindow.document.write('<i class="fa fa-map"></i> ' + response.address + '<br>');
                printWindow.document.write('<i class="fa fa-phone"></i> ' + response.phone + '<br>');
                printWindow.document.write('<i class="fa fa-envelope"></i> ' + response.email);
                printWindow.document.write('</div>');
                printWindow.document.write('</div>');

                printWindow.document.write('<div style="padding-left:5px;" class="mb-2">');
                printWindow.document.write('<b>Customer:</b> <span class="sale_customer style="font-size:20px">' + sale.customer + '</span><br><br>');
                printWindow.document.write('<b>DATE:</b> <span class="sale_date">' + sale.date + '</span>');
                printWindow.document.write('</div>');

                printWindow.document.write('<table class="table">');
                printWindow.document.write('<thead><tr><th>Product</th><th>Quantity</th><th>Price</th><th>Amount</th></tr></thead>');
                printWindow.document.write('<tbody class="print_products">');
                for (var i = 0; i < saleProducts.length; i++) {
                    var product = saleProducts[i];
                    printWindow.document.write('<tr>');
                    printWindow.document.write('<td>' + product.name + ' (' + product.variant + ')' + '</td>');
                    printWindow.document.write('<td>' + product.quantity + '</td>');
                    printWindow.document.write('<td>' + product.sale_price + '</td>');
                    printWindow.document.write('<td>' + product.total_price + '</td>');
                    printWindow.document.write('</tr>');
                }
                printWindow.document.write('</tbody>');
                printWindow.document.write('</table>');

                printWindow.document.write('<div class="mt-2 mb-2 float-end">');
                printWindow.document.write('<b style="font-size:20px;width:100px;display:inline-block;">Amount:</b> <span class="total_price" style="font-size:20px">' + sale.total + '</span> <p style="font-size:20px;width:100px;display:inline-block;">€</p>');
                printWindow.document.write('<b style="font-size:20px;width:100px;display:inline-block;">Discount:</b> <span class="total_discount" style="font-size:20px">' + sale.discounted + '</span> <p style="font-size:20px;width:100px;display:inline-block;">€</p>');
                printWindow.document.write('<b style="font-size:20px;width:100px;display:inline-block;">Total:</b> <span class="net_total_price" style="font-size:20px">' + sale.total_price + '</span> <p style="font-size:20px;width:100px;display:inline-block;">€</p>');
                printWindow.document.write('</div>');

                

                printWindow.document.write('</div>'); // .print

                printWindow.document.write('</body></html>');
                printWindow.document.close();

                // CSS dosyasının yüklenmesini bekleyin ve yazdırma işlemini başlatın
                printWindow.onload = function () {
                    printWindow.print();
                };
            } else {
                // Hata durumunda gerekli işlemleri burada yapabilirsiniz
                console.error(response.msg);
            }
        },
        error: function (xhr, status, error) {
            // AJAX hatası durumunda gerekli işlemleri burada yapabilirsiniz
            console.error(error);
        }
    });
}




function sale_calculate()
{
	var form_data = $('.sale_form').serialize();
	
	 $.ajax({
		type: 'POST',
		url: ajax_url,
		data: 'type=sale_form_calculate&'+form_data+'',
		dataType: 'json',
		success: function(data)
		{
			$.each(data.products, function(k, product) {
				
				  $('.product_total_'+product.rand+'').val(product.total_price);
			});
			
			$('.total_price').html(data.total);
			$('.net_total_price').html(data.net_total);
			$('.total_discount').html(data.discount);
			$('.print_products').html(data.products_html);
			$('.sale_date').html(data.date);
			$('.sale_customer').html(data.customer);
			
		}
	});
}

$(document).ready(function() 
{
	
	$( '.select2' ).select2( {
		width: '100%',
		placeholder: $( this ).data( 'placeholder' ),
	} );
	
	
   $('.sale_form').on('change keyup paste', ':input', function(e) {
		
		
		sale_calculate();
		
   });
	var $_GET = {};
	
	document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
    }

		$_GET[decode(arguments[1])] = decode(arguments[2]);
	});
	if($_GET["date"])
	{

		var tarihler = $_GET["date"].split(" - ");
		var st = tarihler[0];
		var ed = tarihler[1];
	}
	else
	{
		var st = "01.01.2023";
		var ed = "01.01.2024";
	}

	$('.daterange-ranges').daterangepicker(
            {
				showCustomRangeLabel:false,
				startDate:st,
				endDate:ed,
                minDate: '01.01.2023',
                maxDate: '30.12.2025',
                dateLimit: { days: 60 },
				autoApply: true,
                ranges: {
                  'Bugün': [moment(), moment()],
                    'Dün': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    'Son 1 Hafta': [moment().subtract(6, 'days'), moment()],
                    'Son 1 Ay': [moment().subtract(29, 'days'), moment()],
                    'Bu Ay': [moment().startOf('month'), moment().endOf('month')],
                    'Geçen Ay': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                },
                opens: 'right',
                applyClass: 'btn-sm bg-slate-600',
                cancelClass: 'btn-sm btn-light',
				locale: {
				format: 'DD.MM.YYYY',
                applyLabel: 'Uygula',
                cancelLabel: 'Kapat',
                startLabel: 'Başlangıç',
                endLabel: 'Bitiş',
                daysOfWeek: ['Paz', 'Pzt', 'Sal', 'Çar', 'Per', 'Cm','Cmts'],
                monthNames: ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık']
				}
            },
            function(start, end) {
                $('.daterange-ranges span').html(start.format('DD.MM.YYYY') + ' - ' + end.format('DD.MM.YYYY'));
            }
        );

       
	   
	if ($('.datatable').length)
	{
        
	    var table = $(".datatable").DataTable({
		dom: "<'datatable_header'<l><B><f>><'row'<'col-sm-12'tr>><'datatable_footer'<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>>",
        charset: "UTF-8",
          buttons: {            
                buttons: [
					{
                        extend: 'colvis',
                        className: 'btn btn-light',
						text: '<i class="fas fa-th-list"></i> Görünüm'
                    },
                    {
                        extend: 'copy',
                        className: 'btn btn-light',
						text: '<i class="fa fa-copy"></i> Kopyala'
                    },
                    {
                        extend: 'excel',
                        className: 'btn btn-light',
						text: '<i class="fas fa-table"></i> Excel'
                    },
					{
				    extend: 'print',
					 customize: function ( win ) {
                    $(win.document.body)
                        .css( 'font-size', '10pt' );
 
                    $(win.document.body).find( 'table' )
                        .addClass( 'compact' )
                        .css( 'font-size', 'inherit' );
					},
                    text: '<i class="fa fa-print"></i> Yazdır',
                    className: 'btn btn-light',
                    exportOptions: {
                        columns: ':visible'
                    }
					}
                ]
            },
			
			aaSorting:[],
			language:
			{
				"sDecimal":        ",",
				"sEmptyTable":     "Tabloda herhangi bir veri mevcut değil",
				"sInfo":           "_TOTAL_ kayıttan _START_ - _END_ arasındaki kayıtlar gösteriliyor",
				"sInfoEmpty":      "Kayıt yok",
				"sInfoFiltered":   "(_MAX_ kayıt içerisinden bulunan)",
				"sInfoPostFix":    "",
				"sInfoThousands":  ".",
				"sLengthMenu":     "_MENU_ Görüntüle",
				"sLoadingRecords": "Yükleniyor...",
				"searchPlaceholder": "Arama...",
				"sProcessing":     "İşleniyor...",
				"sSearch":         "",
				"sZeroRecords":    "Eşleşen kayıt bulunamadı",
				"oPaginate": {
					"sFirst":    "İlk",
					"sLast":     "Son",
					"sNext":     "Sonraki",
					"sPrevious": "Önceki"
				},
				"oAria": {
					"sSortAscending":  ": artan sütun sıralamasını aktifleştir",
					"sSortDescending": ": azalan sütun sıralamasını aktifleştir"
				},
				"select": {
					"rows": {
						"_": "%d kayıt seçildi",
						"0": "",
						"1": "1 kayıt seçildi"
					}
				},
				buttons: {
						copyTitle: 'Kopyalama İşlemi',
						copySuccess: {
							1: "Satırlar kopyalandı.",
							_: "%d satır kopyalandı."
						}
					}
			}
		}).buttons().container().appendTo(".dataTables_wrapper .col-md-6:eq(0)");
		
		$(".dataTables_length select").addClass("form-select form-select-sm");
		
		$("div.dataTables_filter input").focus();
	  
	}
	
});

$(document).on('click', '.delete', function (e) {
	
   e.preventDefault();
   var url = $(this).attr('href');
   
   Swal.fire({
	  icon:"question",
	  customClass: {
		confirmButton: 'btn btn-danger me-2',
		cancelButton: 'btn btn-success me-2'
	  },
	  buttonsStyling: false,
	  html: 'Bu içeriği silmek istediğinizden  eminmisiniz ?',
	  showCancelButton: true,
	  confirmButtonText: 'Evet',
	  cancelButtonText: 'Hayır',
	}).then((result) => {
	  if (result.isConfirmed) {
		
		window.location.href=url;
		
	  }
	});
   
          

	
});

$(document).on('click', '.add_variant', function (e) {
	
   e.preventDefault();
   var clone = $('.product_variant_clone').html();
   
   $('.product_variants').append('<div class="product_variant">'+clone+'</div>');
   
   
          

	
});

$(document).on('click', '.variant_remove', function (e) {
	
   e.preventDefault();
   $(this).closest('.product_variant').remove();
   
   
          

	
});







$(document).on('click', '.sale_product_remove', function (e) {
	
   $(this).closest('.sale_product').remove();
   
   sale_calculate();


	
});


$(document).on('submit', '.sale_form', function (e) {
	
   e.preventDefault();
   
   
   var form_data = $('.sale_form').serialize();
	
	 $.ajax({
		type: 'POST',
		url: ajax_url,
		data: 'type=sale_form&'+form_data+'',
		dataType: 'json',
		success: function(data)
		{
			if(data.status)
			{
					
				window.location.reload();
				
			}
			else
			{
					Swal.fire({
					  icon: 'error',
					  title: 'Hata',
					  text: data.msg,
					  confirmButtonText: 'Tamam'
					});
			}
		}
	});
   
    


	
});

function barcode_scanner(barcode)
{
	html5QrCode.stop();
	 $.ajax({
		type: 'POST',
		url: ajax_url,
		data: 'type=barcode_scan&barcode='+barcode+'',
		dataType: 'json',
		success: function(data)
		{
			
			if(data.status)
			{
				$('.product_name').val(data.name);
				$('.product_id').val(data.id);
				$('.product_image_url').attr('href',data.image);
				$('.product_image_src').attr('src',data.image);
			}
			else
			{
				if(data.login)
				{
					window.location.href = login_url;
				}
				else
				{
					Swal.fire({
					  icon: 'error',
					  title: 'Hata',
					  text: data.msg,
					  confirmButtonText: 'Tamam'
					});
				}
			}
			
		}
	});
}

function sale_barcode_scanner(barcode,stat=true)
{
	if(stat)
	{
		html5QrCode.stop();
	}
	
	$.ajax({
		type: 'POST',
		url: ajax_url,
		data: 'type=sale_barcode_scan&barcode='+barcode+'',
		dataType: 'json',
		success: function(data)
		{
			
			if(data.status)
			{
				$('.sale_products').prepend(data.html);
				
				sale_calculate();
			}
			else
			{
				if(data.login)
				{
					window.location.href = login_url;
				}
				else
				{
					Swal.fire({
					  icon: 'error',
					  title: 'Hata',
					  text: data.msg,
					  confirmButtonText: 'Tamam'
					});
				}
			}
			
		}
	});
}

function product_barcode_scanner(barcode)
{
	html5QrCode.stop();
	
	$('.pr_barcode').val(barcode);
}

const html5QrCode = new Html5Qrcode("reader");
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
	
	barcode_scanner(decodedText);
	
	html5QrCode.stop();
	
};
const config = { fps: 10, qrbox: { width: 250, height: 250 } };

$(document).on('click', '.barcode_scan', function (e) {
	
    
   
    html5QrCode.start({ facingMode: "environment" }, config, barcode_scan);


	
});

$(document).on('click', '.sale_barcode_scan', function (e) {
	
    
   
    html5QrCode.start({ facingMode: "environment" }, config, sale_barcode_scanner);


	
});

$(document).on('click', '.product_barcode_scan', function (e) {
	
    
   
    html5QrCode.start({ facingMode: "environment" }, config, product_barcode_scanner);


	
});


$(document).on('change', '.manuel_product', function (e) {
	
   	sale_barcode_scanner($(this).val(),false);  

	
});


$(document).on('click', '.print_btn', function (e) {
	
   e.preventDefault();
   
   
   var form_data = $('.sale_form').serialize();
	
	 $.ajax({
		type: 'POST',
		url: ajax_url,
		data: 'type=print_form&'+form_data+'',
		dataType: 'json',
		success: function(data)
		{
			if(data.status)
			{
					
				$('.print').print({
					globalStyles : true,
					mediaPrint : true,
					iframe : false
				});
				
			}
			else
			{
					Swal.fire({
					  icon: 'error',
					  title: 'Hata',
					  text: data.msg,
					  confirmButtonText: 'Tamam'
					});
			}
		}
	});
   
    


	
});