//Global variables of the system
var dn = "WVNRN2FCOW92cE9JdDZWTGpuZnpZMmlvMEJiU2g5SFdMcmw1QmF0ZTJFdz06OoLXGEhQbqjMc4lylnwwl9Q="

// Get Different Report Dates
var today_full_date = new Date()
var todays_date = today_full_date.getFullYear() + "-" + ("0" + (today_full_date.getMonth() + 1)).slice(-2) + "-" + ("0" + today_full_date.getDate()).slice(-2)

var yesterday_ = new Date(today_full_date); 
yesterday_.setDate(yesterday_.getDate() - 1); 
let yesterday_date = yesterday_.toISOString().split('T')[0];

var last3days_ = new Date(today_full_date); 
last3days_.setDate(last3days_.getDate() - 2); 
let last3days_date = last3days_.toISOString().split('T')[0];

let lastSaturday_ = new Date(today_full_date);
lastSaturday_.setDate(lastSaturday_.getDate() - (lastSaturday_.getDay() + 1) % 7);
let lastSaturday_date = lastSaturday_.toISOString().split('T')[0];

var last7days_ = new Date(today_full_date); 
last7days_.setDate(last7days_.getDate() - 6); 
let last7days_date = last7days_.toISOString().split('T')[0];

var last10days_ = new Date(today_full_date); 
last10days_.setDate(last10days_.getDate() - 9); 
let last10days_date = last10days_.toISOString().split('T')[0];

var thisMonth_start = today_full_date.getFullYear() + "-" + ("0" + (today_full_date.getMonth() + 1)).slice(-2) + "-01"

var lastMonth_start = today_full_date.getFullYear() + "-" + ("0" + (today_full_date.getMonth())).slice(-2) + "-01"
var lastMonth_ = new Date(today_full_date.getFullYear(), ("0" + (today_full_date.getMonth())).slice(-2), 0);
var lastMonth_end = lastMonth_.getFullYear() + "-" + ("0" + (lastMonth_.getMonth() + 1)).slice(-2) + "-" + ("0" + lastMonth_.getDate()).slice(-2)

var thisYear_start = today_full_date.getFullYear() + "-01-01"

var lastYear_start = today_full_date.getFullYear() - 1 + "-01-01"
var lastYear_end = today_full_date.getFullYear() - 1 + "-12-31"

let category_id_admin_pos = "All"
let category_id_edit_order = "All"
let category_id_waiter_pos = "All"
let category_id_edit_waiter_pos = "All"

$(document).ready(function () {

  // Call General Functions
  fillKitchens()
  fillWorkingSections()
  fillRestaurantCategories()
  fillActiveCustomers()
  fillActiveCustomersForWaiters()
  fillStockCategories()
  fillItemUnits()

  // ============================ START OF REGISTRATIONS MODULE SCRIPTS ========================================

  // ============================ Start of Kitchen Information Section =========================================

  // Register New Kitchen Page
  $("#registerNewKitchenForm").on("submit", function (e) {
    e.preventDefault()
    var vl = $("#txtKitchenNameNewKitchen").val() + "###" + $("#txtKitchenDescriptionNewKitchen").val() + "###" + $("#txtRegisteredByNewKitchen").val() + "###" + $("#txtRegisterDateNewKitchen").val() + "###" + "-" + "###" + "-"
    var hasFile = "No"
    var tn = "aGdPaytJRCtyaEhZVitMd1BsMWdyQT09OjqTDosdTtNQnAjgQNSWU40r"
    var commandType = "insert_command"
    var objName = "Kitchen"
    var objPre = "KTC"
    var post = {action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre}
    swal ({
      title: "Are you sure?", text: "You want to register this kitchen?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend:function(){
            $("#btnRegisterNewKitchen").prop('disabled', true)
            $("#btnRegisterNewKitchen").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnRegisterNewKitchen").prop('disabled', false)
            $("#btnRegisterNewKitchen").html("<i class='fa fa-lg fa-save'></i> Register Kitchen")
            var Message = data.Message
            var status = data.Status
            if (status == true) {		
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) location.reload()
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })

  })
  
  // Filling Data into Update Kitchen Modal
  $(document).on("click", ".btnUpdateKitchen", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    var tn = "aGdPaytJRCtyaEhZVitMd1BsMWdyQT09OjqTDosdTtNQnAjgQNSWU40r"
    var cm = "TVc1STZwclJ5ekNoR3NSYWhPNTY0QT09OjqCXMsshrnX7hqmkIiOabuH"
    var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
    $(".modal-body").load(objectID)
    $.ajax({
      method: "POST", url: "api/main.php", data: post, dataType: "JSON",
      success: function (data) {
        var Message = data.Message
        var status = data.Status
        if (status == true) {
          var returned_info = Message.split("###")
          $("#txtKitchenIddUpdateKitchen").val(returned_info[1])
          $("#txtKitchenNameUpdateKitchen").val(returned_info[2])
          $("#txtKitchenDescriptionUpdateKitchen").val(returned_info[3])
        }
      }, error: function (e) {
        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
      }
    })
  })

  // Update Kitchen Modal
  $("#updateKitchenForm").on("submit", function (e) {
    e.preventDefault()
    var vl = $("#txtKitchenIddUpdateKitchen").val() + "###" + $("#txtKitchenNameUpdateKitchen").val() + "###" + $("#txtKitchenDescriptionUpdateKitchen").val() + "###" + $("#txtUpdatedByUpdateKitchen").val() + "###" + $("#txtUpdateDateUpdateKitchen").val()
    var tn = "aGdPaytJRCtyaEhZVitMd1BsMWdyQT09OjqTDosdTtNQnAjgQNSWU40r"
    var cm = "d3FWMmNGNHBZNzhRM2dNZXZVU2VrYzJWaXJNaVdJOHA3L240eHlidDBYMkkzMnFEQ3FnaXVOQ0pKSjQ3S2lOeFdUdW5WaWZYZ0VUTnZxL1BZdHRRRk8rMVBlYmpXK3BUZ1g1aXBnaVgzaUE9Ojq5s0EJWTmxJODPST4dfJF1"
    var commandType = "update_command"
    var hasFile = "No"
    var objName = "Kitchen"
    var post = {
      action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
    }
    swal({
      title: "Are your sure?", text: "You want to update this kitchen?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend: function () {
              $("#btnUpdateKitchen").prop("disabled", true)
              $("#btnUpdateKitchen").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function (data) {
            $("#btnUpdateKitchen").prop("disabled", false)
            $("#btnUpdateKitchen").html("<i class='fa fa-pencil'></i> Update Kitchen")
            var Message = data.Message;
            var status = data.Status;
            if (status === true) {
              swal({
                  title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function (isConfirm) {
                  if (isConfirm) { location.reload() }
              })
            } else {
              Message.forEach(function (error) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
              })
            }
          }, error: function (e) {
              bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
          },
        })
      }
    })
  })

  // Delete Kitchen Data
  $(document).on('click', '.btnDeleteKitchen', function (e) {
    e.preventDefault()
    const deleteBtnID = $(this).attr("id")
    var vl = $(this).attr("data-id")
    var tn = "aGdPaytJRCtyaEhZVitMd1BsMWdyQT09OjqTDosdTtNQnAjgQNSWU40r"
    var cm = "TVc1STZwclJ5ekNoR3NSYWhPNTY0QT09OjqCXMsshrnX7hqmkIiOabuH"
    var commandType = "delete_command"
    var objName = "Kitchen"
    var post = {"action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName}
    swal({
      title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled")
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
        $.ajax({
          method: "POST", url: "api/main.php", data: post, dataType: "JSON",
          success: function (data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {
                swal("success", Message, "success")
                $("#" + deleteBtnID).parents("tr").remove()
            } else {
                swal("", Message, "error")
            }
          }, error: function (data) { }
        })
      }
    })
  })

  // ============================ End of Kitchen Information Section ===========================================

  // ============================ Start of Category Information Section ========================================

  // Register Restaurant Category Modal
	$("#registerNewRestaurantCategoryForm").on('submit', function (e) {
		e.preventDefault()
		var formData = new FormData(this)
		var vl = $("#txtCategoryNameNewRestaurantCategory").val() + "###" + $("#cmbCategorySectionNewRestaurantCategory").val() + "###" + $("#txtCategoryDescriptionNewRestaurantCategory").val() + "###" + $("#txtRegisteredByNewRestaurantCategory").val() + "###" + $("#txtRegisterDateNewRestaurantCategory").val() + "###" + "-" + "###" + "-"
		var hasFile = "Yes"
		var files = "photoNewRestaurantCategory1"
		var tn = "MHRGS0JIMWNGMCtvRCtqZ3cvTndnQkw2ejlLd2Z3b1hIM2EycUNvV2VHVT06OjgJcEBEbTIaLnRIrAQ2W8s="
		var commandType = "insert_command"
		var objName = "Category"
		var objPre = "RCT"
		formData.append("action", "ins_upd_del_everything")
		formData.append("vl", vl)
		formData.append("hasFile", hasFile)
		formData.append("files", files)
		formData.append("photoNewRestaurantCategory1", $("#restaurantCategoryPhoto")[0].files[0])
		formData.append("commandType", commandType)
		formData.append("tn", tn)
		formData.append("objName", objName)
		formData.append("objPre", objPre)
		swal ({
			title: "Are you sure?", text: "You want to register this category?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
                    url: "api/main.php", type: "POST", data:  formData, contentType: false, cache: false, processData:false,
					beforeSend:function(){
						$("#btnRegisterNewRestaurantCategory").prop('disabled', true)
						$("#btnRegisterNewRestaurantCategory").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnRegisterNewRestaurantCategory").prop('disabled', false)
						$("#btnRegisterNewRestaurantCategory").html("<i class='fa fa-lg fa-save'></i> Register Category")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					 }, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
			   })
			}
		})
	})

	// Filling Data into Update Restaurant Category Modal
	$(document).on("click", ".btnUpdateRestaurantCategory", function (e) {
		e.preventDefault()
		var objectID = $(this).attr("data-id")
		var tn = "MHRGS0JIMWNGMCtvRCtqZ3cvTndnQkw2ejlLd2Z3b1hIM2EycUNvV2VHVT06OjgJcEBEbTIaLnRIrAQ2W8s="
		var cm = "WnNDckJsQUFqbE81cUJ3Um5kdlpZZz09OjqqTmvut4bT2/6N7uYXJgL+"
		var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn" : tn, "cm" : cm, "objectID": objectID }
		$(".modal-body").load(objectID)
		$.ajax({
			method: "POST", url: "api/main.php", data:  post, dataType: "JSON",
			success: function(data) {
				var Message = data.Message
				var status = data.Status
				if (status == true) {
					var returned_info = Message.split("###")
					$("#txtCategoryIddUpdateRestaurantCategory").val(returned_info[1])
					$("#txtCategoryNameUpdateRestaurantCategory").val(returned_info[2])
          $("#cmbCategorySectionUpdateRestaurantCategory").select2().val(returned_info[3]).trigger('change')
					$("#txtCategoryDescriptionUpdateRestaurantCategory").val(returned_info[4])
					$("#restaurantCategoryPhotoTargetUpdate").attr("src", returned_info[9])
					$("#photoUpdateRestaurantCategory1").val(returned_info[9])
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
	   })
	})

  // Update Restaurant Category Modal
	$("#updateRestaurantCategoryForm").on('submit', function (e) {
		e.preventDefault()
		var formData = new FormData(this)
		var vl =  $("#txtCategoryIddUpdateRestaurantCategory").val() + "###" + $("#txtCategoryNameUpdateRestaurantCategory").val() + "###" + $("#cmbCategorySectionUpdateRestaurantCategory").val() + "###" + $("#txtCategoryDescriptionUpdateRestaurantCategory").val() + "###" + $("#txtUpdatedByNewRestaurantCategory").val() + "###" + $("#txtUpdateDateNewRestaurantCategory").val()
    var tn = "MHRGS0JIMWNGMCtvRCtqZ3cvTndnQkw2ejlLd2Z3b1hIM2EycUNvV2VHVT06OjgJcEBEbTIaLnRIrAQ2W8s="
    var cm = "SURXc2VObW5Db1RSY1FNNGJvUzR5MWw3YkJ3cFR2d2RUWmU3NEpuWW8vNFNnUXUxeHhzNTk2eEtVRG5XbmFvdUprajc0UzVQOWlFQ1JpRGNJVFdFUUNaL3VxeTMrb1BCQ21hWWxJaC9rNWNBQTA3ZmlFTE1neGRqckg2QVg1UjBlZDFYMFlNWVp2QjJGZ05FbUdzOHJnPT06OqUr4QJTH2uIWDVsrgtkXq8="
		var photoNames = $("#photoUpdateRestaurantCategory1").val()
		var docNames = ""				// Means no documents in this update
		var hasFile = "Yes"
		var files = "photoUpdateRestaurantCategory1"
		var commandType = "update_command"
		var objName = "Category"
		formData.append("action", "ins_upd_del_everything")
		formData.append("vl", vl)
		formData.append("cm", cm)
		formData.append("hasFile", hasFile)
		formData.append("files", files)
		formData.append("photoUpdateRestaurantCategory1", $("#restaurantCategoryPhotoUpdate")[0].files[0])
		formData.append("photoNames", photoNames)
		formData.append("docNames", docNames)
		formData.append("commandType", commandType)
		formData.append("tn", tn)
		formData.append("objName", objName)
		swal ({
			title: "Are you sure?", text: "You want to update this category?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
          url: "api/main.php", type: "POST", data:  formData, contentType: false, cache: false, processData:false,
					beforeSend:function(){
						$("#btnUpdateRestaurantCategory").prop('disabled', true)
						$("#btnUpdateRestaurantCategory").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnUpdateRestaurantCategory").prop('disabled', false)
						$("#btnUpdateRestaurantCategory").html("<i class='fa fa-lg fa-pencil'></i> Update Category")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					 }, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
			   })
			}
		})

	})

  // Delete Restaurant Category Data
  $(document).on('click', '.btnDeleteRestaurantCategory', function (e) {
    e.preventDefault();
    const deleteBtnID = $(this).attr("id")
    var vl = $(this).attr("data-id")
		var tn = "MHRGS0JIMWNGMCtvRCtqZ3cvTndnQkw2ejlLd2Z3b1hIM2EycUNvV2VHVT06OjgJcEBEbTIaLnRIrAQ2W8s="
		var cm = "WnNDckJsQUFqbE81cUJ3Um5kdlpZZz09OjqqTmvut4bT2/6N7uYXJgL+"
    var commandType = "delete_command"
    var objName = "Category"
    var post = {
      "action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName
    }
    swal({
      title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          method: "POST", url: "api/main.php", data: post, dataType: "JSON",
          success: function (data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {
              swal("success", Message, "success")
              location.reload()
            } else {
              swal("", Message, "error")
            }
          }, error: function (data) { }
        })
      }
    })
  })

  // ============================ End of Category Information Section ==========================================

  // ============================ Start of Product Information Section =========================================

  // Register Restaurant Product Modal
	$("#registerNewRestaurantProductForm").on('submit', function (e) {
		e.preventDefault()
		var formData = new FormData(this)
		var vl = $("#txtProductNameNewRestaurantProduct").val() + "###" + $("#cmbProductCategoryNewRestaurantProduct").val() + "###" + $("#txtProductPriceNewRestaurantProduct").val() + "###" + $("#cmbProductSectionNewRestaurantProduct").val() + "###" + $("#cmbProcessingKitchenNewRestaurantProduct").val() + "###" + $("#txtProductDescriptionNewRestaurantProduct").val() + "###" + 1 + "###" + $("#txtRegisteredByNewRestaurantProduct").val() + "###" + $("#txtRegisterDateNewRestaurantProduct").val() + "###" + "-" + "###" + "-"
		var hasFile = "Yes"
		var files = "photoNewRestaurantProduct1"
		var tn = "RU1wZWZjMTRFMG5zc242Wi9LallnNDZjL0l2b0EwMW9UQnh3a3czc2FHZz06Ot36HJIs2eBiijFIS8JR85I="
		var commandType = "insert_command"
		var objName = "Product"
		var objPre = "RPR"
		formData.append("action", "ins_upd_del_everything")
		formData.append("vl", vl)
		formData.append("hasFile", hasFile)
		formData.append("files", files)
		formData.append("photoNewRestaurantProduct1", $("#restaurantProductPhoto")[0].files[0])
		formData.append("commandType", commandType)
		formData.append("tn", tn)
		formData.append("objName", objName)
		formData.append("objPre", objPre)
		swal ({
			title: "Are you sure?", text: "You want to register this product?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
                    url: "api/main.php", type: "POST", data:  formData, contentType: false, cache: false, processData:false,
					beforeSend:function(){
						$("#btnRegisterNewRestaurantProduct").prop('disabled', true)
						$("#btnRegisterNewRestaurantProduct").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnRegisterNewRestaurantProduct").prop('disabled', false)
						$("#btnRegisterNewRestaurantProduct").html("<i class='fa fa-lg fa-save'></i> Register Product")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					 }, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
			   })
			}
		})
	})
	
    // Search Product - Products Page
    $(document).on("keyup", "#txtSearchRestaurantProductProductsPage", function () {
        var searched_product_name = $(this).val()
        var post = { "action": "search_restaurant_product_live_products_page", "searched_product_name": searched_product_name}
        $.ajax({
            type: "POST", url: "api/main.php", data: post, dataType: "text",
            success: function (response) {
                $("#restaurantProductsProductsPageArea").html(response)
            }
        })
  })

	// Filling Data into Update Restaurant Product Modal
	$(document).on("click", ".btnUpdateRestaurantProduct", function (e) {
		e.preventDefault()
		var objectID = $(this).attr("data-id")
		var tn = "bG83aWZGUDVienFsYmkzWW1oUUpVWVNOUGpyZFVFTjdoRFdyVzE0cWVlST06OrmUvTkAMOpxVlvdqaHNwUs="
		var cm = "L0IvN21hYkR5cFpPR3ByK2J2KzFRdz09Ojr88a/yzUUnYA/ZoFduVEGd"
		var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn" : tn, "cm" : cm, "objectID": objectID }
		$(".modal-body").load(objectID)
		$.ajax({
			method: "POST", url: "api/main.php", data:  post, dataType: "JSON",
			success: function(data) {
				var Message = data.Message
				var status = data.Status
				if (status == true) {
					var returned_info = Message.split("###")
					$("#txtProductIddUpdateRestaurantProduct").val(returned_info[1])
					$("#txtProductNameUpdateRestaurantProduct").val(returned_info[2])
          $("#cmbProductCategoryUpdateRestaurantProduct").select2().val(returned_info[3]).trigger('change')
					$("#txtProductPriceUpdateRestaurantProduct").val(returned_info[4])
          $("#cmbProductSectionUpdateRestaurantProduct").select2().val(returned_info[5]).trigger('change')
          $("#cmbProcessingKitchenUpdateRestaurantProduct").select2().val(returned_info[6]).trigger('change')
          $("#txtProductDescriptionUpdateRestaurantProduct").val(returned_info[7])
          $("#restaurantProductPhotoTargetUpdate").attr("src", returned_info[13])
					$("#photoUpdateRestaurantProduct1").val(returned_info[13])
          if (returned_info[8] == 1) {
            $("#cbxProductStatusUpdateRestaurantProduct").parent().addClass("btn-success")
            $("#cbxProductStatusUpdateRestaurantProduct").parent().removeClass("btn-danger off")
            $("#cbxProductStatusUpdateRestaurantProduct").attr("restaurant_product_status", "1")
          } else {
            $("#cbxProductStatusUpdateRestaurantProduct").parent().addClass("btn-danger off")
            $("#cbxProductStatusUpdateRestaurantProduct").parent().removeClass("btn-success")
            $("#cbxProductStatusUpdateRestaurantProduct").attr("restaurant_product_status", "0")
          }
				}	
		 	}, error: function(e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
			}          
	   })
	})

    $(document).on("change", "#cbxProductStatusUpdateRestaurantProduct", function () {
        this.checked ? $(this).attr("restaurant_product_status", "1") : $(this).attr("restaurant_product_status", "0")
    })

    // Update Restaurant Product Modal
	$("#updateRestaurantProductForm").on('submit', function (e) {
		e.preventDefault()
		var formData = new FormData(this)
		var vl =  $("#txtProductIddUpdateRestaurantProduct").val() + "###" + $("#txtProductNameUpdateRestaurantProduct").val() + "###" + $("#cmbProductCategoryUpdateRestaurantProduct").val() + "###" + $("#txtProductPriceUpdateRestaurantProduct").val() + "###" + $("#cmbProductSectionUpdateRestaurantProduct").val() + "###" + $("#cmbProcessingKitchenUpdateRestaurantProduct").val() + "###" + $("#txtProductDescriptionUpdateRestaurantProduct").val() + "###" + $("#cbxProductStatusUpdateRestaurantProduct").attr("restaurant_product_status") + "###" + $("#txtUpdatedByUpdateRestaurantProduct").val() + "###" + $("#txtUpdateDateUpdateRestaurantProduct").val()
		var tn = "bG83aWZGUDVienFsYmkzWW1oUUpVWVNOUGpyZFVFTjdoRFdyVzE0cWVlST06OrmUvTkAMOpxVlvdqaHNwUs="
    var cm = "QU1uK0l4MEM0MGJFTE4vVVh2cGJxNUsyUnQveW1VWDZvZDlvUHBmMzQ0WTZwWTAvWjNNWXFRNFFLNmlmaW9qY3U1UW1JTXl2aWFVSGppRVdaRE0yUFhnTllJelRNM2IrTEtkaUVKU2Z2Y2d0eE12UlBteEN6VzdXSi9rT2lDdmRYNStXWEd5VVpjdjZxNmdBc2IvS2tUZXZORm9hODN3V1F2QldRTHlFOTB4QW9uM2RSdDRXbHVrTjJmL1VPL1hHQkN6ZWM0MHpoU2sxYjBpck5GUDB3Zz09Ojp/KDhcl70a+UjkqLE3kI/v"
		var photoNames = $("#photoUpdateRestaurantProduct1").val()
		var docNames = ""				// Means no documents in this update
		var hasFile = "Yes"
		var files = "photoUpdateRestaurantProduct1"
		var commandType = "update_command"
		var objName = "Category"
		formData.append("action", "ins_upd_del_everything")
		formData.append("vl", vl)
		formData.append("cm", cm)
		formData.append("hasFile", hasFile)
		formData.append("files", files)
		formData.append("photoUpdateRestaurantProduct1", $("#restaurantProductPhotoUpdate")[0].files[0])
		formData.append("photoNames", photoNames)
		formData.append("docNames", docNames)
		formData.append("commandType", commandType)
		formData.append("tn", tn)
		formData.append("objName", objName)
		swal ({
			title: "Are you sure?", text: "You want to update this product?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
          url: "api/main.php", type: "POST", data:  formData, contentType: false, cache: false, processData:false,
					beforeSend:function(){
						$("#btnUpdateRestaurantProduct").prop('disabled', true)
						$("#btnUpdateRestaurantProduct").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnUpdateRestaurantProduct").prop('disabled', false)
						$("#btnUpdateRestaurantProduct").html("<i class='fa fa-lg fa-pencil'></i> Update Product")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					 }, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
			   })
			}
		})

	})

  // Delete Restaurant Product Data
  $(document).on('click', '.btnDeleteRestaurantProduct', function (e) {
    e.preventDefault();
    const deleteBtnID = $(this).attr("id")
    var vl = $(this).attr("data-id")
		var tn = "bG83aWZGUDVienFsYmkzWW1oUUpVWVNOUGpyZFVFTjdoRFdyVzE0cWVlST06OrmUvTkAMOpxVlvdqaHNwUs="
		var cm = "L0IvN21hYkR5cFpPR3ByK2J2KzFRdz09Ojr88a/yzUUnYA/ZoFduVEGd"
    var commandType = "delete_command"
    var objName = "Product"
    var post = {
      "action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName
    }
    swal({
      title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          method: "POST", url: "api/main.php", data: post, dataType: "JSON",
          success: function (data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {
              swal("success", Message, "success")
              location.reload()
            } else {
              swal("", Message, "error")
            }
          }, error: function (data) { }
        })
      }
    })
  })

  // ============================ End of Product Information Section ===========================================

  // ============================ Start of Table Information Section ===========================================

  // Register New Table Page
  $("#registerNewTableForm").on("submit", function (e) {
    e.preventDefault()
    var vl = $("#txtTableNameRegisterNewTable").val() + "###" + $("#cmbTableSectionRegisterNewTable").val() + "###" + $("#txtTableDescriptionRegisterNewTable").val() + "###" + $("#txtRegisteredByRegisterNewTable").val() + "###" + $("#txtRegisterDateRegisterNewTable").val() + "###" + "-" + "###" + "-"
    var hasFile = "No"
    var tn = "Q0d0QWxadHJQN3FWQVQ3V0xmMlZGdz09Ojo7eZRyY1q49AzPQFzP3XtK"
    var commandType = "insert_command"
    var objName = "Table"
    var objPre = "TBL"
    var post = {action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre}
    swal ({
      title: "Are you sure?", text: "You want to register this table?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend:function(){
            $("#btnRegisterNewTable").prop('disabled', true)
            $("#btnRegisterNewTable").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnRegisterNewTable").prop('disabled', false)
            $("#btnRegisterNewTable").html("<i class='fa fa-lg fa-save'></i> Register Table")
            var Message = data.Message
            var status = data.Status
            if (status == true) {		
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) location.reload()
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })

  })
  
  // Filling Data into Update Table Modal
  $(document).on("click", ".btnUpdateTable", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    var tn = "Q0d0QWxadHJQN3FWQVQ3V0xmMlZGdz09Ojo7eZRyY1q49AzPQFzP3XtK"
    var cm = "ZWN3bi85RUt3dFdOOU9BZnV1cGkxQT09OjqPu9BgdIYPZXApe+yI/NeB"
    var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
    $(".modal-body").load(objectID)
    $.ajax({
      method: "POST", url: "api/main.php", data: post, dataType: "JSON",
      success: function (data) {
        var Message = data.Message
        var status = data.Status
        if (status == true) {
          var returned_info = Message.split("###")
          $("#txtTableIddUpdateTable").val(returned_info[1])
          $("#txtTableNameUpdateTable").val(returned_info[2])
          $("#cmbTableSectionUpdateTable").select2().val(returned_info[3]).trigger('change')
          $("#txtTableDescriptionUpdateTable").val(returned_info[4])
        }
      }, error: function (e) {
        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
      }
    })
  })

  // Update Table Modal
  $("#updateTableForm").on("submit", function (e) {
    e.preventDefault()
    var vl = $("#txtTableIddUpdateTable").val() + "###" + $("#txtTableNameUpdateTable").val() + "###" + $("#cmbTableSectionUpdateTable").val() + "###" + $("#txtTableDescriptionUpdateTable").val() + "###" + $("#txtUpdatedByUpdateTable").val() + "###" + $("#txtUpdateDateUpdateTable").val()
    var tn = "Q0d0QWxadHJQN3FWQVQ3V0xmMlZGdz09Ojo7eZRyY1q49AzPQFzP3XtK"
    var cm = "LzhuWGlhdndIMmVBNitjc0lZcTdNUTJWOVZqU1E4WVpZdzJmV3BaU1UyZEsyaC9BdmtMSmU5WVJKdGtLOVY1Ym9PcXd2d2REc3hMSnEyMnJxZDJIcWN3VkVZR3BnMm8rZ0xCK3ZwTUpVQ1hLZDdWb05PcGdyZFk3dnpYU0JJRVk6OmA49BVbXkcrKGG8pF5tG8c="
    var commandType = "update_command"
    var hasFile = "No"
    var objName = "Table"
    var post = {
      action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
    }
    swal({
      title: "Are your sure?", text: "You want to update this table?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend: function () {
              $("#btnUpdateTable").prop("disabled", true)
              $("#btnUpdateTable").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function (data) {
            $("#btnUpdateTable").prop("disabled", false)
            $("#btnUpdateTable").html("<i class='fa fa-pencil'></i> Update Table")
            var Message = data.Message;
            var status = data.Status;
            if (status === true) {
              swal({
                  title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function (isConfirm) {
                  if (isConfirm) { location.reload() }
              })
            } else {
              Message.forEach(function (error) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
              })
            }
          }, error: function (e) {
              bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
          },
        })
      }
    })
  })

  // Delete Table Data
  $(document).on('click', '.btnDeleteTable', function (e) {
    e.preventDefault()
    const deleteBtnID = $(this).attr("id")
    var vl = $(this).attr("data-id")
    var tn = "Q0d0QWxadHJQN3FWQVQ3V0xmMlZGdz09Ojo7eZRyY1q49AzPQFzP3XtK"
    var cm = "ZWN3bi85RUt3dFdOOU9BZnV1cGkxQT09OjqPu9BgdIYPZXApe+yI/NeB"
    var commandType = "delete_command"
    var objName = "Table"
    var post = {"action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName}
    swal({
      title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled")
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
        $.ajax({
          method: "POST", url: "api/main.php", data: post, dataType: "JSON",
          success: function (data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {
                swal("success", Message, "success")
                $("#" + deleteBtnID).parents("tr").remove()
            } else {
                swal("", Message, "error")
            }
          }, error: function (data) { }
        })
      }
    })
  })

  // ============================ End of Table Information Section =============================================

  // ============================ Start of Customer Information Section ========================================

  // Register New Customer - Page
  $("#registerNewCustomerPageForm").on("submit", function (e) {
    e.preventDefault()
    var vl = $("#txtCustomerNameRegisterNewCustomerPage").val() + "###" + $("#txtCustomerMobileRegisterNewCustomerPage").val() + "###" + $("#txtCustomerAddressRegisterNewCustomerPage").val() + "###" + 1 + "###" + $("#txtRegisteredByRegisterNewCustomerPage").val() + "###" + $("#txtRegisterDateRegisterNewCustomerPage").val() + "###" + "-" + "###" + "-"
    var hasFile = "No"
    var tn = "N3RiQlE5aHpxYlhqcDZzY0htT1FHUT09OjrKESQBZhUcLtGXFR8YyNlc"
    var commandType = "insert_command"
    var objName = "Customer"
    var objPre = "CU"
    var post = {action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre}
    swal ({
      title: "Are you sure?", text: "You want to register this customer?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend:function(){
            $("#btnRegisterNewCustomerPage").prop('disabled', true)
            $("#btnRegisterNewCustomerPage").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnRegisterNewCustomerPage").prop('disabled', false)
            $("#btnRegisterNewCustomerPage").html("<i class='fa fa-lg fa-save'></i> Register Customer")
            var Message = data.Message
            var status = data.Status
            if (status == true) {		
              swal ({
                title: "", text: "Customer has been registered successfully", type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) location.reload()
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })
  })

  // Register New Customer - Modal
  $("#registerNewCustomerModalForm").on("submit", function (e) {
    e.preventDefault();
    var vl = $("#txtCustomerNameRegisterNewCustomerModal").val() + "###" + $("#txtCustomerMobileRegisterNewCustomerModal").val() + "###" + $("#txtCustomerAddressRegisterNewCustomerModal").val() + "###" + 1 + "###" + $("#txtRegisteredByRegisterNewCustomerModal").val() + "###" + $("#txtRegisterDateRegisterNewCustomerModal").val() + "###" + "-" + "###" + "-"
    var hasFile = "No"
    var tn = "N3RiQlE5aHpxYlhqcDZzY0htT1FHUT09OjrKESQBZhUcLtGXFR8YyNlc"
    var commandType = "insert_command"
    var objName = "Customer"
    var objPre = "CU"
    var post = {action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre}
    swal ({
      title: "Are you sure?", text: "You want to register this customer?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: true, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend:function(){
            $("#btnRegisterNewCustomerModal").prop('disabled', true)
            $("#btnRegisterNewCustomerModal").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnRegisterNewCustomerModal").prop('disabled', false)
            $("#btnRegisterNewCustomerModal").html("<i class='fa fa-lg fa-save'></i> Register Customer")
            var Message = data.Message
            var status = data.Status
            if (status == true) {
              fillActiveCustomers()
            //   alert(Message)
              $("#registerNewCustomerModal").modal("hide")
              var customer_post = {"action": "fill_customer_information", "selected_customer_id": Message}
              $.ajax({
                method: "POST", url: "api/main.php", data: customer_post, dataType: "JSON",
                success: function (response) {
                  var CustomerMessage = response.Message
                  var CustomerStatus = response.Status
                  if(CustomerStatus == true){
                    CustomerMessage.forEach(function(returned_data,i){
                      $("#cmbCustomerIddNewOrderAdminPOSPage").select2().val(returned_data['customerID']).trigger("change")                
                      $("#txtDeliveryAddressNewOrderAdminPOSPage").val(returned_data['customerAddress'])               
                    })
                  }
                }, error: function (e) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
                }
              })
            } else {
              Message.forEach(function (error) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })
  })
  
  // Filling Data into Update Customer Modal
  $(document).on("click", ".btnUpdateCustomer", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    var tn = "N3RiQlE5aHpxYlhqcDZzY0htT1FHUT09OjrKESQBZhUcLtGXFR8YyNlc"
    var cm = "dXNYS3JuVDF4Sk9hOXR6WTZtU2Radz09Ojr5ysjqpEPcYt9BvDkpe1cE"
    var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
    $(".modal-body").load(objectID)
    $.ajax({
      method: "POST", url: "api/main.php", data: post, dataType: "JSON",
      success: function (data) {
        var Message = data.Message
        var status = data.Status
        if (status == true) {
          var returned_info = Message.split("###")
          $("#txtCustomerIddUpdateCustomer").val(returned_info[1])
          $("#txtCustomerNameUpdateCustomer").val(returned_info[2])
          $("#txtCustomerMobileUpdateCustomer").val(returned_info[3])
          $("#txtCustomerAddressUpdateCustomer").val(returned_info[4])
        }
      }, error: function (e) {
        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
      }
    })
  })

  // Update Customer Modal
  $("#updateCustomerForm").on("submit", function (e) {
    e.preventDefault()
    var vl = $("#txtCustomerIddUpdateCustomer").val() + "###" + $("#txtCustomerNameUpdateCustomer").val() + "###" + $("#txtCustomerMobileUpdateCustomer").val() + "###" + $("#txtCustomerAddressUpdateCustomer").val() + "###" + $("#txtUpdatedByUpdateCustomer").val() + "###" + $("#txtUpdateDateUpdateCustomer").val()
    var tn = "N3RiQlE5aHpxYlhqcDZzY0htT1FHUT09OjrKESQBZhUcLtGXFR8YyNlc"
    var cm = "Y2ZtdkxyVXQvKzc0UHNPeDRmaDRldDlyRWRld2MzMjA2ZVk5UXNNVWpvOHRETXdiTUY3L2R5aGV6dDNCeFAzV0N1TkZoUmtDQTJhZzhmMVN2UWdqZTZLdzB0dW5waDdmVFB1dWJQY3d4WlFqTlJINk82eEJzSVluOHYvL2Y4OWQ6Ogi0CL3Z/pr7LRkmmVEyGng="
    var commandType = "update_command"
    var hasFile = "No"
    var objName = "Customer"
    var post = {
      action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
    }
    swal({
      title: "Are your sure?", text: "You want to update this customer?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend: function () {
              $("#btnUpdateCustomer").prop("disabled", true)
              $("#btnUpdateCustomer").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function (data) {
            $("#btnUpdateCustomer").prop("disabled", false)
            $("#btnUpdateCustomer").html("<i class='fa fa-pencil'></i> Update Customer")
            var Message = data.Message;
            var status = data.Status;
            if (status === true) {
              swal({
                  title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function (isConfirm) {
                  if (isConfirm) { location.reload() }
              })
            } else {
              Message.forEach(function (error) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
              })
            }
          }, error: function (e) {
              bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
          },
        })
      }
    })
  })

  // Delete Customer Data
  $(document).on('click', '.btnDeleteCustomer', function (e) {
    e.preventDefault()
    const deleteBtnID = $(this).attr("id")
    var vl = $(this).attr("data-id")
    var tn = "N3RiQlE5aHpxYlhqcDZzY0htT1FHUT09OjrKESQBZhUcLtGXFR8YyNlc"
    var cm = "dXNYS3JuVDF4Sk9hOXR6WTZtU2Radz09Ojr5ysjqpEPcYt9BvDkpe1cE"
    var commandType = "delete_command"
    var objName = "Customer"
    var post = {"action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName}
    swal({
      title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled")
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
        $.ajax({
          method: "POST", url: "api/main.php", data: post, dataType: "JSON",
          success: function (data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {
                swal("", Message, "success")
                $("#" + deleteBtnID).parents("tr").remove()
            } else {
                swal("", Message, "error")
            }
          }, error: function (data) { }
        })
      }
    })
  })

  // ============================ End of Customer Information Section ==========================================

  // ============================ END OF REGISTRATIONS MODULE SCRIPTS ==========================================

  // ============================ START OF POS ADMIN SECTION MODULE SCRIPTS ====================================

  $("#btnSeatInAdminPOSPage").removeClass("btn-outline-success")
  $("#btnSeatInAdminPOSPage").addClass("btn-success")
  let order_type_admin_pos = "OT0001"
  let serving_waiter_admin_pos = "-"
  $("#txtDeliveryAddressNewOrderAdminPOSPage").hide()

  // Fetch Restaurant Products By Category - Admin POS Page
  $(document).on('click', '.restaurant_categories_admin_pos', function () {
    $("#txtSearchRestaurantProductLiveAdminPOS").val("")
    category_id_admin_pos = $(this).attr("category-id")
    $(".restaurant_categories_admin_pos").removeClass("btn-primary")
    $(".restaurant_categories_admin_pos").addClass("btn-light")
    $(this).removeClass("btn-light")
    $(this).addClass("btn-primary")
    let post = { "action": "fetch_restaurant_products_by_category_admin_pos", "category_id_admin_pos": category_id_admin_pos}
    $.ajax({
      type: "POST", url: "api/main.php", data: post, dataType: "text",
      success: function (response) {
        $(".restaurantProductsAdminPOSPageArea").html(response)
      }
    })
  })

  // Search Product - Admin POS Page Live
  $(document).on("keyup", "#txtSearchRestaurantProductLiveAdminPOS", function () {
    var searched_product_name = $(this).val()
    var post = { "action": "search_restaurant_product_live_admin_pos", "searched_product_name": searched_product_name, "category_id_admin_pos": category_id_admin_pos}
    $.ajax({
      type: "POST", url: "api/main.php", data: post, dataType: "text",
      success: function (response) {
        $(".restaurantProductsAdminPOSPageArea").html(response)
      }
    })
  })

  // Selcet Product to Checkout - Admin POS Page
  $(document).on("click", ".singleProductAdminPOSPageArea", function () {
    var selected_product_id = $(this).attr("product-id")
    var selected_product_name = $(this).attr("product-name")
    var selected_product_price = parseFloat($(this).attr("product-price")) || 0
    var order_subtotal_admin_pos = ((parseFloat($("#orderedProductsSubtotalAdminPOS").text()) || 0) + selected_product_price).toFixed(2)
    var order_vat_admin_pos = ((order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)) * 0.05).toFixed(2)
    var order_true_vat_admin_pos = (((order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)) + (parseFloat(order_vat_admin_pos) || 0)) * 0.05).toFixed(2)
    var order_total_admin_pos = ((order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)) + (parseFloat(order_true_vat_admin_pos) || 0)).toFixed(2)
    
    // var order_vat_admin_pos = (order_total_admin_pos * 0.05).toFixed(2)
    // var order_true_vat_admin_pos = (((parseFloat(order_total_admin_pos) || 0) + (parseFloat(order_vat_admin_pos) || 0)) * 0.05).toFixed(2)
    if ($("#orderedProductId" + selected_product_id).length == 0) {
      $(".orderedProductsAdminPOSPageArea").closest('div').append(`<div class='row align-items-center font-weight-bold p-2 border-bottom border-light' style='margin: 0px;' id='orderedProductId${selected_product_id}' ordered-product-id='${selected_product_id}' ordered-product-price='${selected_product_price}'>\
          <div class='col-md-1 text-left'><i class='fa fa-trash fa-lg text-danger removeOrderedProductAdminPOS' style='cursor: pointer;'></i></div>\
          <div class='col-md-5'>${selected_product_name}</div>\
          <div class='col-md-4'>\
              <button class='btn btn-outline-success rounded-pill btnIncrementProductQuantityAdminPOS'><span class='font-weight-bold'>+</span></button><span class='pl-2 pr-2 orderedProductQuantityAdminPOS'>1</span><button class='btn btn-outline-success rounded-pill btnDecrementProductQuantityAdminPOS'><span class='font-weight-bold'>-</span></button>\
          </div>\
          <div class='col-md-2'>$<span class='orderedProductPriceAdminPOS' >${selected_product_price.toFixed(2)}</div></div>\
      </div>`)
      $("#orderedProductsSubtotalAdminPOS").text(order_subtotal_admin_pos)
      $("#txtOrderedProductsVATAdminPOS").val(order_true_vat_admin_pos)   
      $("#orderedProductsTotalAdminPOS").text(order_total_admin_pos)

    //   $("#orderedProductsTrueVATAdminPOS").text(order_true_vat_admin_pos)    
    } else {
      let selected_product_quantity = (parseInt($("#orderedProductId" + selected_product_id + " .orderedProductQuantityAdminPOS").text()) || 0) + 1
      let selected_product_total_price = parseFloat(selected_product_quantity * selected_product_price) || 0
      $("#orderedProductId" + selected_product_id + " .orderedProductQuantityAdminPOS").text(selected_product_quantity)
      $("#orderedProductId" + selected_product_id + " .orderedProductPriceAdminPOS").text(selected_product_total_price.toFixed(2))
      $("#orderedProductsSubtotalAdminPOS").text(order_subtotal_admin_pos)
      $("#txtOrderedProductsVATAdminPOS").val(order_true_vat_admin_pos)   
      $("#orderedProductsTotalAdminPOS").text(order_total_admin_pos)

    //   $("#orderedProductsTrueVATAdminPOS").text(order_true_vat_admin_pos)
    }
  })

  // Increment Ordered Product - Admin POS Page
  $(document).on("click", ".btnIncrementProductQuantityAdminPOS", function () {
    let selected_product_quantity = (parseInt($(this).parent().find(".orderedProductQuantityAdminPOS").text()) || 0) + 1
    let selected_product_price = parseFloat($(this).parent().parent().attr("ordered-product-price")) || 0
    var order_subtotal_admin_pos = ((parseFloat($("#orderedProductsSubtotalAdminPOS").text()) || 0) + selected_product_price).toFixed(2)
    var order_vat_admin_pos = ((order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)) * 0.05).toFixed(2)
    var order_true_vat_admin_pos = (((order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)) + (parseFloat(order_vat_admin_pos) || 0)) * 0.05).toFixed(2)
    var order_total_admin_pos = ((order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)) + (parseFloat(order_true_vat_admin_pos) || 0)).toFixed(2)

    // var order_total_admin_pos = (order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)).toFixed(2)
    $(this).parent().find(".orderedProductQuantityAdminPOS").text(selected_product_quantity)
    $(this).parent().next().find(".orderedProductPriceAdminPOS").text((parseFloat(selected_product_quantity * selected_product_price) || 0).toFixed(2))
    $("#orderedProductsSubtotalAdminPOS").text(order_subtotal_admin_pos)
    $("#txtOrderedProductsVATAdminPOS").val(order_true_vat_admin_pos)   
    $("#orderedProductsTotalAdminPOS").text(order_total_admin_pos)
    // $("#orderedProductsTotalAdminPOS").text(order_total_admin_pos)   
  })

  // Decrement Ordered Product - Admin POS Page
  $(document).on("click", ".btnDecrementProductQuantityAdminPOS", function () {
    let selected_product_quantity = parseInt($(this).parent().find(".orderedProductQuantityAdminPOS").text()) || 0
    let selected_product_price = parseFloat($(this).parent().parent().attr("ordered-product-price")) || 0
    var order_subtotal_admin_pos = ((parseFloat($("#orderedProductsSubtotalAdminPOS").text()) || 0) - selected_product_price).toFixed(2)
    var order_vat_admin_pos = ((order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)) * 0.05).toFixed(2)
    var order_true_vat_admin_pos = (((order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)) + (parseFloat(order_vat_admin_pos) || 0)) * 0.05).toFixed(2)
    var order_total_admin_pos = ((order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)) + (parseFloat(order_true_vat_admin_pos) || 0)).toFixed(2)
    
    // var order_total_admin_pos = (order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)).toFixed(2)
    if (selected_product_quantity > 1) {
      selected_product_quantity--
      $(this).parent().find(".orderedProductQuantityAdminPOS").text(selected_product_quantity)
      $(this).parent().next().find(".orderedProductPriceAdminPOS").text((parseFloat(selected_product_quantity * selected_product_price) || 0).toFixed(2))
      $("#orderedProductsSubtotalAdminPOS").text(order_subtotal_admin_pos)
      $("#txtOrderedProductsVATAdminPOS").val(order_true_vat_admin_pos)   
      $("#orderedProductsTotalAdminPOS").text(order_total_admin_pos)
    //   $("#orderedProductsTotalAdminPOS").text(order_total_admin_pos) 
    }
  })

  // Remove Ordered Product - Admin POS Page
  $(document).on("click", ".removeOrderedProductAdminPOS", function () {
    let selected_product_price = parseFloat($(this).parent().parent().find(".orderedProductPriceAdminPOS").text()) || 0
    var order_subtotal_admin_pos = ((parseFloat($("#orderedProductsSubtotalAdminPOS").text()) || 0) - selected_product_price).toFixed(2)
    var order_vat_admin_pos = ((order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)) * 0.05).toFixed(2)
    var order_true_vat_admin_pos = (((order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)) + (parseFloat(order_vat_admin_pos) || 0)) * 0.05).toFixed(2)
    var order_total_admin_pos = ((order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)) + (parseFloat(order_true_vat_admin_pos) || 0)).toFixed(2)
    
    // var order_total_admin_pos = (order_subtotal_admin_pos - (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0)).toFixed(2)
    $("#orderedProductsSubtotalAdminPOS").text(order_subtotal_admin_pos)
    $("#txtOrderedProductsVATAdminPOS").val(order_true_vat_admin_pos)   
    $("#orderedProductsTotalAdminPOS").text(order_total_admin_pos)
    // $("#orderedProductsTotalAdminPOS").text(order_total_admin_pos)
    $(this).parent().parent().remove()
  })

  // Discount Entry - Admin POS Page
  $(document).on("keyup keypress blur change focusout", "#txtOrderedProductsDiscountAdminPOS", function(e){
      let checkout_subtotal_admin_pos = parseFloat($("#orderedProductsSubtotalAdminPOS").text()) || 0
      let checkout_discount_admin_pos = parseFloat($(this).val()) || 0
      
      var checkout_vat_admin_pos = ((checkout_subtotal_admin_pos - checkout_discount_admin_pos) * 0.05).toFixed(2)
      var checkout_true_vat_admin_pos = (((checkout_subtotal_admin_pos - checkout_discount_admin_pos) + (parseFloat(checkout_vat_admin_pos) || 0)) * 0.05).toFixed(2)
      var checkout_total_admin_pos = ((checkout_subtotal_admin_pos - checkout_discount_admin_pos) + (parseFloat(checkout_true_vat_admin_pos) || 0)).toFixed(2)
    
      if (checkout_discount_admin_pos >= checkout_subtotal_admin_pos) {
        bs4pop.notice("<h5 class='pt-2'><i class='fa fa-exclamation-circle fa-lg pr-2'></i>" + " Check Discount Amount</h5>", { type: "warning", position: "topright", appendType: "append"})
      } else {
        $("#txtOrderedProductsVATAdminPOS").val(checkout_true_vat_admin_pos)       
        $("#orderedProductsTotalAdminPOS").text(checkout_total_admin_pos)       
      }
  })
  
  // VAT Tax Entry - Admin POS Page
  $(document).on("keyup keypress blur change focusout", "#txtOrderedProductsVATAdminPOS", function(e){
      let checkout_subtotal_admin_pos = parseFloat($("#orderedProductsSubtotalAdminPOS").text()) || 0
      let checkout_discount_admin_pos = parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0
      let checkout_true_vat_admin_pos = parseFloat($(this).val()) || 0
      let checkout_total_admin_pos = ((checkout_subtotal_admin_pos - checkout_discount_admin_pos) + checkout_true_vat_admin_pos)
      if (checkout_discount_admin_pos >= checkout_subtotal_admin_pos) {
        bs4pop.notice("<h5 class='pt-2'><i class='fa fa-exclamation-circle fa-lg pr-2'></i>" + " Check VAT Amount</h5>", { type: "warning", position: "topright", appendType: "append"})
      } else {
        $("#orderedProductsTotalAdminPOS").text((checkout_total_admin_pos).toFixed(2) || 0)       
      }
  })

  // Select Seat In - Admin POS
  $(document).on("click", "#btnSeatInAdminPOSPage", function () {
    $(this).removeClass("btn-outline-success")
    $(this).addClass("btn-success")
    $("#btnTakeAwayAdminPOSPage").removeClass("btn-primary")
    $("#btnTakeAwayAdminPOSPage").addClass("btn-outline-primary")
    $("#btnDeliveryAdminPOSPage").removeClass("btn-dark")
    $("#btnDeliveryAdminPOSPage").addClass("btn-outline-dark")
    order_type_admin_pos = "OT0001"
    $("#txtDeliveryAddressNewOrderAdminPOSPage").hide()
  })

  // Select TakeAway - Admin POS
  $(document).on("click", "#btnTakeAwayAdminPOSPage", function () {
    $("#btnSeatInAdminPOSPage").removeClass("btn-success")
    $("#btnSeatInAdminPOSPage").addClass("btn-outline-success")
    $(this).removeClass("btn-outline-primary")
    $(this).addClass("btn-primary")
    $("#btnDeliveryAdminPOSPage").removeClass("btn-dark")
    $("#btnDeliveryAdminPOSPage").addClass("btn-outline-dark")
    order_type_admin_pos = "OT0002"
    $("#txtDeliveryAddressNewOrderAdminPOSPage").hide()
  })

  // Select Delivery - Admin POS
  $(document).on("click", "#btnDeliveryAdminPOSPage", function () {
    $("#btnSeatInAdminPOSPage").removeClass("btn-success")
    $("#btnSeatInAdminPOSPage").addClass("btn-outline-success")
    $("#btnTakeAwayAdminPOSPage").removeClass("btn-primary")
    $("#btnTakeAwayAdminPOSPage").addClass("btn-outline-primary")
    $(this).removeClass("btn-outline-dark")
    $(this).addClass("btn-dark")
    order_type_admin_pos = "OT0003"
    $("#txtDeliveryAddressNewOrderAdminPOSPage").show()
  })

  // Select Customer - Admin POS
  $("#cmbCustomerIddNewOrderAdminPOSPage").on("change", function (e) {
    e.preventDefault()
    var selected_customer_id = $(this).val()
    if (selected_customer_id == "RegisterNewCustomer") {
    //   $("#txtDeliveryAddressNewOrderAdminPOSPage").val("")
        $("#registerNewCustomerModalForm")[0].reset();
        $("#registerNewCustomerModal").modal("show")
    } else {
      var post = {"action": "fill_customer_information", "selected_customer_id": selected_customer_id }
      $.ajax({
        method: "POST", url: "api/main.php", data:  post, dataType: "JSON",
        success: function(data) {
          var Message = data.Message
          var status = data.Status
          if (status == true){
            Message.forEach(function(returned_data,i){
              $("#txtDeliveryAddressNewOrderAdminPOSPage").val(returned_data['customerAddress'])               
            })
          }
        }, error: function(e) {
          bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
        }          
      })
    }
  })

  // Select Serving Waiter - Admin POS
  $(document).on("click", ".cbxServingWaiterAdminPOSPageArea", function() {
    if (this.checked) {
      serving_waiter_admin_pos = $(this).attr("serving-waiter-id")
      $(".cbxServingWaiterAdminPOSPageArea").not(this).prop("checked", false)
    } else {
      serving_waiter_admin_pos = "-"
    }
   
  })

  // Register Order and  Pay - Admin POS
  $(document).on("click", "#btnRegisterAndPayAdminPOSPage", function (e) {
    e.preventDefault()

    let ordered_products_list_admin_pos = []
    let selected_order_type = order_type_admin_pos
    let selected_customer_id = $("#cmbCustomerIddNewOrderAdminPOSPage").val()
    let selected_deliveryman_id = "-"
    let selected_delivery_address = $("#txtDeliveryAddressNewOrderAdminPOSPage").val() == "" ? "-" : $("#txtDeliveryAddressNewOrderAdminPOSPage").val()
    let selected_table_id = "-"
    let selected_waiter_id = serving_waiter_admin_pos
    $('[id^="orderedProductId"]').each(function() {
      ordered_products_list_admin_pos.push([$(this).attr("ordered-product-id"), $(this).find(".orderedProductQuantityAdminPOS").text(), $(this).attr("ordered-product-price"), $(this).find(".orderedProductPriceAdminPOS").text()])
    })
    let kitchen_note_descript = $("#txtKitchenNoteNewOrderAdminPOSPage").val()
    let order_subtotal_amount = (parseFloat($("#orderedProductsSubtotalAdminPOS").text()) || 0).toFixed(2)
    let order_discount_amount = $("#txtOrderedProductsDiscountAdminPOS").val() === "" ? 0.00 : (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0).toFixed(2)
    let order_true_vat_amount = $("#txtOrderedProductsVATAdminPOS").val() === "" ? 0.00 : (parseFloat($("#txtOrderedProductsVATAdminPOS").val()) || 0).toFixed(2)
    let order_total_amount = (parseFloat($("#orderedProductsTotalAdminPOS").text()) || 0).toFixed(2)

    let checked_order_products_list = ordered_products_list_admin_pos.length === 0 ? {"productsStatus": "false", "productsMessage": "Select Product to Save Order"} : {"productsStatus": "true", "productsMessage": ordered_products_list_admin_pos}

    const order_post_parameters = {
      "action": "register_restaurant_order_admin_pos_page",
      "selected_order_type": selected_order_type,
      "selected_customer_id": selected_customer_id,
      "selected_deliveryman_id": selected_deliveryman_id,
      "selected_delivery_address":  selected_delivery_address,
      "selected_table_id":  selected_table_id,
      "checked_order_products_list": checked_order_products_list,
      "selected_waiter_id":  selected_waiter_id,
      "kitchen_note_descript": kitchen_note_descript,
      "order_subtotal_amount": order_subtotal_amount,
      "order_discount_amount": order_discount_amount,
      "order_true_vat_amount": order_true_vat_amount,
      "order_total_amount": order_total_amount
    }
    swal ({
      title: "Are you sure?", text: "You want to register this order?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: true, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: order_post_parameters, dataType: "JSON",
          beforeSend:function(){
            $("#btnRegisterAndPayAdminPOSPage").prop('disabled', true)
            $("#btnRegisterAndPayAdminPOSPage").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnRegisterAndPayAdminPOSPage").prop('disabled', false)
            $("#btnRegisterAndPayAdminPOSPage").html("<i class='fa fa-lg fa-save'></i> Register & Pay")
            var Message = data.Message
            var status = data.Status
            if (status == true) {
              $("#registerCustomerPaymentModal").modal("show")
              $("#cmbDepositAccountRegisterCustomerPayment0").select2({ tags: false, dropdownParent: $("#registerCustomerPaymentModal") })
              let order_post = {"action": "fetch_order_information", "selected_order_id": Message}
              $(".modal-body").load(Message)
              $.ajax({
                "async": false, method: "POST", url: "api/main.php", data: order_post, dataType: "text",
                success: function(response) {
                  $(".orderInformationCustomerPaymentModal").html(response)      
                }, error: function(e) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
                }          
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })

  })

  // Hold Order - Admin POS
  $(document).on("click", "#btnHoldOrderAdminPOSPage", function (e) {
    e.preventDefault()

    let ordered_products_list_admin_pos = []
    let selected_order_type = order_type_admin_pos
    let selected_customer_id = $("#cmbCustomerIddNewOrderAdminPOSPage").val()
    let selected_deliveryman_id = "-"
    let selected_delivery_address = $("#txtDeliveryAddressNewOrderAdminPOSPage").val() == "" ? "-" : $("#txtDeliveryAddressNewOrderAdminPOSPage").val()
    let selected_table_id = "-"
    let selected_waiter_id = serving_waiter_admin_pos
    $('[id^="orderedProductId"]').each(function() {
      ordered_products_list_admin_pos.push([$(this).attr("ordered-product-id"), $(this).find(".orderedProductQuantityAdminPOS").text(), $(this).attr("ordered-product-price"), $(this).find(".orderedProductPriceAdminPOS").text()])
    })
    let kitchen_note_descript = $("#txtKitchenNoteNewOrderAdminPOSPage").val()
    let order_subtotal_amount = (parseFloat($("#orderedProductsSubtotalAdminPOS").text()) || 0).toFixed(2)
    let order_discount_amount = $("#txtOrderedProductsDiscountAdminPOS").val() === "" ? 0.00 : (parseFloat($("#txtOrderedProductsDiscountAdminPOS").val()) || 0).toFixed(2)
    let order_true_vat_amount = $("#txtOrderedProductsVATAdminPOS").val() === "" ? 0.00 : (parseFloat($("#txtOrderedProductsVATAdminPOS").val()) || 0).toFixed(2)
    let order_total_amount = (parseFloat($("#orderedProductsTotalAdminPOS").text()) || 0).toFixed(2)

    let checked_order_products_list = ordered_products_list_admin_pos.length === 0 ? {"productsStatus": "false", "productsMessage": "Select Product to Save Order"} : {"productsStatus": "true", "productsMessage": ordered_products_list_admin_pos}

    const order_post_parameters = {
      "action": "register_restaurant_order_admin_pos_page",
      "selected_order_type": selected_order_type,
      "selected_customer_id": selected_customer_id,
      "selected_deliveryman_id": selected_deliveryman_id,
      "selected_delivery_address":  selected_delivery_address,
      "selected_table_id":  selected_table_id,
      "checked_order_products_list": checked_order_products_list,
      "selected_waiter_id":  selected_waiter_id,
      "kitchen_note_descript": kitchen_note_descript,
      "order_subtotal_amount": order_subtotal_amount,
      "order_discount_amount": order_discount_amount,
      "order_true_vat_amount": order_true_vat_amount,
      "order_total_amount": order_total_amount
    }
    swal ({
      title: "Are you sure?", text: "You want to hold this order?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: true, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: order_post_parameters, dataType: "JSON",
          beforeSend:function(){
            $("#btnHoldOrderAdminPOSPage").prop('disabled', true)
            $("#btnHoldOrderAdminPOSPage").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnHoldOrderAdminPOSPage").prop('disabled', false)
            $("#btnHoldOrderAdminPOSPage").html("<i class='fa fa-lg fa-pause'></i> Hold Order")
            var Message = data.Message
            var status = data.Status
            if (status == true) {
              var returned_data = Message.split("####")
              $("#viewAndPrintOrderReceiptModal").modal("show")
              var receipt_post = { "action": "view_and_print_order_receipt", "selected_order_id": returned_data[0], "btn_type": "Print"}
              $(".modal-body").load(returned_data[0])
              $.ajax({
                "async":false, method: "POST", url: "api/main.php", data:  receipt_post, dataType: "text",
                success: function(response) {
                  $("#viewOrderFullInformationDivisionArea").html(response)
                }, error: function(e) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
                }          
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })

  })
  
  // Delete Order Data Permenantly
  $(document).on('click', '.btnDeleteCancelledOrder', function (e) {
    e.preventDefault()
    const deleteBtnID = $(this).attr("id")
    var selected_order_id = $(this).attr("data-id")
    var delete_post = {"action": "delete_cancelled_order_permenantly", "selected_order_id": selected_order_id}
    swal({
        title: "Are you sure?", text: "You want to delete this order permenantly?", type: "", animation: "slide-from-top", showCancelButton: true, cancelButtonText: "No", confirmButtonText: "Yes", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled")
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
        $.ajax({
          method: "POST", url: "api/main.php", data: delete_post, dataType: "JSON",
          success: function (data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {
                swal("success", Message, "success")
                $("#" + deleteBtnID).parents("tr").remove()
            } else {
                swal("", Message, "error")
            }
          }, error: function (data) { }
        })
      }
    })
  })

  // ============================ End of Kitchen Information Section ===========================================

  // ============================ END OF POS ADMIN SECTION MODULE SCRIPTS ======================================
  
  // ============================ START OF EDIT ORDER SECTION MODULE SCRIPTS ===================================

  let order_type_edit_order = ""
  let serving_waiter_edit_order = "-"
  let order_id_edit_order_information
  
  // Fetch Order Full Informational into Edit Order Modal
  $(document).on("click", ".btnEditOrderInformation", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    var post = { "action": "fetch_order_full_information_to_edit", "selected_order_id": objectID }
    $(".modal-body").load(objectID)
    $.ajax({
      method: "POST", url: "api/main.php", data:  post, dataType: "text",
      success: function(response) {
        $("#orderFullInformationDivisionArea").html(response)
        order_id_edit_order_information = $(".txtOrderIddEditOrderInformation").attr("order-id-to-edit")
        order_type_edit_order = $(".btnOrderTypeEditOrderInformation").attr("order-type-edit-order")
        if (order_type_edit_order == "OT0001" || order_type_edit_order == "OT0002" ) {
          $("#txtDeliveryAddressEditOrderInformation").hide()
        } else if (order_type_edit_order == "OT0003" ) {
          $("#txtDeliveryAddressEditOrderInformation").show()
        }
        $(".cbxSelectedWaiter").attr("current-selected-waiter-id") == undefined ? "-" : serving_waiter_edit_order = $(".cbxSelectedWaiter").attr("current-selected-waiter-id")
      }, error: function(e) {
        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
      }          
    })
  })

  // Fetch Restaurant Products By Category - Edit Order Information
  $(document).on('click', '.restaurant_categories_edit_order', function () {
    $("#txtSearchRestaurantProductLiveEditOrderInformation").val("")
    category_id_edit_order = $(this).attr("category-id")
    $(".restaurant_categories_edit_order").removeClass("btn-primary")
    $(".restaurant_categories_edit_order").addClass("btn-light")
    $(this).removeClass("btn-light")
    $(this).addClass("btn-primary")
    let post = { "action": "fetch_restaurant_products_by_category_edit_order", "category_id_edit_order": category_id_edit_order}
    $.ajax({
      type: "POST", url: "api/main.php", data: post, dataType: "text",
      success: function (response) {
        $(".restaurantProductsEditOrderInformation").html(response)
      }
    })
  })

  // Search Product Live - Edit Order Information
  $(document).on("keyup", "#txtSearchRestaurantProductLiveEditOrderInformation", function () {
    var searched_product_name = $(this).val()
    var post = { "action": "search_restaurant_product_live_edit_order", "searched_product_name": searched_product_name, "category_id_edit_order": category_id_edit_order}
    $.ajax({
      type: "POST", url: "api/main.php", data: post, dataType: "text",
      success: function (response) {
        $(".restaurantProductsEditOrderInformation").html(response)
      }
    })
  })

  // Selcet Product to Checkout - Edit Order Information
  $(document).on("click", ".singleProductEditOrderInformation", function () {
    var selected_product_id = $(this).attr("product-id")
    var selected_product_name = $(this).attr("product-name")
    var selected_product_price = parseFloat($(this).attr("product-price")) || 0
    var order_subtotal_edit_order = ((parseFloat($("#orderedProductsSubtotalEditOrderInformation").text()) || 0) + selected_product_price).toFixed(2)
    var order_vat_edit_order = ((order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)) * 0.05).toFixed(2)
    var order_true_vat_edit_order = (((order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)) + (parseFloat(order_vat_edit_order) || 0)) * 0.05).toFixed(2)
    var order_total_edit_order = ((order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)) + (parseFloat(order_true_vat_edit_order) || 0)).toFixed(2)
    
    // var order_total_edit_order = (order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val() || 0)) || 0).toFixed(2)
    if ($("#editOrderedProductId" + selected_product_id).length == 0) {
      $(".orderedProductsEditOrderInformation").closest('div').append(`<div class='row align-items-center font-weight-bold pt-2 pb-2 border-bottom border-light' style='margin: 0px;' id='editOrderedProductId${selected_product_id}' ordered-product-id='${selected_product_id}' ordered-product-price='${selected_product_price}'>\
          <div class='col-md-1 text-left'><i class='fa fa-trash fa-lg text-danger removeOrderedProductEditOrderInformation' style='cursor: pointer;'></i></div>\
          <div class='col-md-5'>${selected_product_name}</div>\
          <div class='col-md-4'>\
              <button class='btn btn-outline-success rounded-pill btnIncrementProductQuantityEditOrderInformation'><span class='font-weight-bold'>+</span></button><span class='pl-2 pr-2 orderedProductQuantityEditOrderInformation'>1</span><button class='btn btn-outline-success rounded-pill btnDecrementProductQuantityEditOrderInformation'><span class='font-weight-bold'>-</span></button>\
          </div>\
          <div class='col-md-2'>$<span class='orderedProductPriceEditOrderInformation' >${selected_product_price.toFixed(2)}</div></div>\
      </div>`)
      $("#orderedProductsSubtotalEditOrderInformation").text(order_subtotal_edit_order)
      $("#txtOrderedProductsVATEditOrderInformation").val(order_true_vat_edit_order)   
      $("#orderedProductsTotalEditOrderInformation").text(order_total_edit_order)
      
    //   $("#orderedProductsTotalEditOrderInformation").text(order_total_edit_order)
    } else {
      let selected_product_quantity = (parseInt($("#editOrderedProductId" + selected_product_id + " .orderedProductQuantityEditOrderInformation").text()) || 0) + 1
      let selected_product_total_price = parseFloat(selected_product_quantity * selected_product_price) || 0
      $("#editOrderedProductId" + selected_product_id + " .orderedProductQuantityEditOrderInformation").text(selected_product_quantity)
      $("#editOrderedProductId" + selected_product_id + " .orderedProductPriceEditOrderInformation").text(selected_product_total_price.toFixed(2))
      $("#orderedProductsSubtotalEditOrderInformation").text(order_subtotal_edit_order)
      $("#txtOrderedProductsVATEditOrderInformation").val(order_true_vat_edit_order)   
      $("#orderedProductsTotalEditOrderInformation").text(order_total_edit_order)
      
    //   $("#orderedProductsTotalEditOrderInformation").text(order_total_edit_order)    
    }
  })

  // Increment Ordered Product - Edit Order Information
  $(document).on("click", ".btnIncrementProductQuantityEditOrderInformation", function () {
    let selected_product_quantity = (parseInt($(this).parent().find(".orderedProductQuantityEditOrderInformation").text()) || 0) + 1
    let selected_product_price = parseFloat($(this).parent().parent().attr("ordered-product-price")) || 0
    var order_subtotal_edit_order = ((parseFloat($("#orderedProductsSubtotalEditOrderInformation").text()) || 0) + selected_product_price).toFixed(2)
    
    var order_vat_edit_order = ((order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)) * 0.05).toFixed(2)
    var order_true_vat_edit_order = (((order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)) + (parseFloat(order_vat_edit_order) || 0)) * 0.05).toFixed(2)
    var order_total_edit_order = ((order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)) + (parseFloat(order_true_vat_edit_order) || 0)).toFixed(2)
    
    
    // var order_total_edit_order = (order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)).toFixed(2)
    $(this).parent().find(".orderedProductQuantityEditOrderInformation").text(selected_product_quantity)
    $(this).parent().next().find(".orderedProductPriceEditOrderInformation").text((parseFloat(selected_product_quantity * selected_product_price) || 0).toFixed(2))
    $("#orderedProductsSubtotalEditOrderInformation").text(order_subtotal_edit_order)
    
    $("#txtOrderedProductsVATEditOrderInformation").val(order_true_vat_edit_order)   
    $("#orderedProductsTotalEditOrderInformation").text(order_total_edit_order)
    
    // $("#orderedProductsTotalEditOrderInformation").text(order_total_edit_order)   
  })

  // Decrement Ordered Product - Edit Order Information
  $(document).on("click", ".btnDecrementProductQuantityEditOrderInformation", function () {
    let selected_product_quantity = parseInt($(this).parent().find(".orderedProductQuantityEditOrderInformation").text()) || 0
    let selected_product_price = parseFloat($(this).parent().parent().attr("ordered-product-price")) || 0
    var order_subtotal_edit_order = ((parseFloat($("#orderedProductsSubtotalEditOrderInformation").text()) || 0) - selected_product_price).toFixed(2)
    
    var order_vat_edit_order = ((order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)) * 0.05).toFixed(2)
    var order_true_vat_edit_order = (((order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)) + (parseFloat(order_vat_edit_order) || 0)) * 0.05).toFixed(2)
    var order_total_edit_order = ((order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)) + (parseFloat(order_true_vat_edit_order) || 0)).toFixed(2)
    
    
    // var order_total_edit_order = (order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)).toFixed(2)
    if (selected_product_quantity > 1) {
      selected_product_quantity--
      $(this).parent().find(".orderedProductQuantityEditOrderInformation").text(selected_product_quantity)
      $(this).parent().next().find(".orderedProductPriceEditOrderInformation").text((parseFloat(selected_product_quantity * selected_product_price) || 0).toFixed(2))
      $("#orderedProductsSubtotalEditOrderInformation").text(order_subtotal_edit_order)
      
      $("#txtOrderedProductsVATEditOrderInformation").val(order_true_vat_edit_order)   
      $("#orderedProductsTotalEditOrderInformation").text(order_total_edit_order)
      
    //   $("#orderedProductsTotalEditOrderInformation").text(order_total_edit_order) 
    }
  })

  // Remove Ordered Product - Edit Order Information
  $(document).on("click", ".removeOrderedProductEditOrderInformation", function () {
    let order_id_edit_order = order_id_edit_order_information
    let selected_product_id = $(this).parent().parent().attr("ordered-product-id")
    let selected_product_price = parseFloat($(this).parent().parent().find(".orderedProductPriceEditOrderInformation").text()) || 0
    var order_subtotal_edit_order = ((parseFloat($("#orderedProductsSubtotalEditOrderInformation").text()) || 0) - selected_product_price).toFixed(2)
    
    var order_vat_edit_order = ((order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)) * 0.05).toFixed(2)
    var order_true_vat_edit_order = (((order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)) + (parseFloat(order_vat_edit_order) || 0)) * 0.05).toFixed(2)
    var order_total_edit_order = ((order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)) + (parseFloat(order_true_vat_edit_order) || 0)).toFixed(2)
    
    
    // var order_total_edit_order = (order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0)).toFixed(2)
    var post_data = {
      "action": "remove_order_list_item", "selected_product_id": selected_product_id, "selected_order_id": order_id_edit_order, "order_subtotal_edit_order": order_subtotal_edit_order, "order_total_edit_order": order_total_edit_order
    }
    swal ({
      title: "", text: "Are you sure?", type: "", customClass: "sweetAlertSmall", animation: "slide-from-bottom", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: true, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post_data, dataType: "JSON",
          success: function(data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {
              bs4pop.notice("<i class='fa fa-check-circle'></i> &nbsp;" + Message, {type: "success", position: "topright", appendType: "append"})
              $("#orderedProductsSubtotalEditOrderInformation").text(order_subtotal_edit_order)
              
              $("#txtOrderedProductsVATEditOrderInformation").val(order_true_vat_edit_order)   
              $("#orderedProductsTotalEditOrderInformation").text(order_total_edit_order)
              
            //   $("#orderedProductsTotalEditOrderInformation").text(order_total_edit_order)
              $("#editOrderedProductId" + selected_product_id).remove()
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	

          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })
  })

  // Discount Entry - Edit Order Information
  $(document).on("keyup keypress blur change focusout", "#txtOrderedProductsDiscountEditOrderInformation", function(e){
      let checkout_subtotal_edit_order = parseFloat($("#orderedProductsSubtotalEditOrderInformation").text()) || 0
      let checkout_discount_edit_order = parseFloat($(this).val()) || 0
      
      var checkout_vat_edit_order = ((checkout_subtotal_edit_order - checkout_discount_edit_order) * 0.05).toFixed(2)
      var checkout_true_vat_edit_order = (((checkout_subtotal_edit_order - checkout_discount_edit_order) + (parseFloat(checkout_vat_edit_order) || 0)) * 0.05).toFixed(2)
      var checkout_total_edit_order = ((checkout_subtotal_edit_order - checkout_discount_edit_order) + (parseFloat(checkout_true_vat_edit_order) || 0)).toFixed(2)
    
      
    //   let checkout_true_vat_edit_order = parseFloat($("#txtOrderedProductsVATEditOrderInformation").text()) || 0
    //   let checkout_total_edit_order = ((checkout_subtotal_edit_order - checkout_discount_edit_order) + checkout_true_vat_edit_order)
      if (checkout_discount_edit_order >= checkout_subtotal_edit_order) {
        bs4pop.notice("<h5 class='pt-2'><i class='fa fa-exclamation-circle fa-lg pr-2'></i>" + " Check Discount Amount</h5>", { type: "warning", position: "topright", appendType: "append"})
      } else {
        $("#txtOrderedProductsVATEditOrderInformation").val(checkout_true_vat_edit_order)       
        $("#orderedProductsTotalEditOrderInformation").text(checkout_total_edit_order)       
      }
  })
  
  // VAT Tax Entry - Edit Order Information
  $(document).on("keyup keypress blur change focusout", "#txtOrderedProductsVATEditOrderInformation", function(e){
      let checkout_subtotal_edit_order = parseFloat($("#orderedProductsSubtotalEditOrderInformation").text()) || 0
      let checkout_discount_edit_order = parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0
      let checkout_true_vat_edit_order = parseFloat($(this).val()) || 0
      let checkout_total_edit_order = ((checkout_subtotal_edit_order - checkout_discount_edit_order) + checkout_true_vat_edit_order)
      if (checkout_discount_edit_order >= checkout_subtotal_edit_order) {
        bs4pop.notice("<h5 class='pt-2'><i class='fa fa-exclamation-circle fa-lg pr-2'></i>" + " Check VAT Amount</h5>", { type: "warning", position: "topright", appendType: "append"})
      } else {
        $("#orderedProductsTotalEditOrderInformation").text((checkout_total_edit_order).toFixed(2) || 0)       
      }
  })

  // Select Seat In - Edit Order Information
  $(document).on("click", "#btnSeatInEditOrderInformation", function () {
    $(this).removeClass("btn-outline-success")
    $(this).addClass("btn-success")
    $("#btnTakeAwayEditOrderInformation").removeClass("btn-primary")
    $("#btnTakeAwayEditOrderInformation").addClass("btn-outline-primary")
    $("#btnDeliveryEditOrderInformation").removeClass("btn-dark")
    $("#btnDeliveryEditOrderInformation").addClass("btn-outline-dark")
    order_type_edit_order = "OT0001"
    $("#txtDeliveryAddressEditOrderInformation").hide()
  })

  // Select TakeAway - Edit Order Information
  $(document).on("click", "#btnTakeAwayEditOrderInformation", function () {
    $("#btnSeatInEditOrderInformation").removeClass("btn-success")
    $("#btnSeatInEditOrderInformation").addClass("btn-outline-success")
    $(this).removeClass("btn-outline-primary")
    $(this).addClass("btn-primary")
    $("#btnDeliveryEditOrderInformation").removeClass("btn-dark")
    $("#btnDeliveryEditOrderInformation").addClass("btn-outline-dark")
    order_type_edit_order = "OT0002"
    $("#txtDeliveryAddressEditOrderInformation").hide()
  })

  // Select Delivery - Edit Order Information
  $(document).on("click", "#btnDeliveryEditOrderInformation", function () {
    $("#btnSeatInEditOrderInformation").removeClass("btn-success")
    $("#btnSeatInEditOrderInformation").addClass("btn-outline-success")
    $("#btnTakeAwayEditOrderInformation").removeClass("btn-primary")
    $("#btnTakeAwayEditOrderInformation").addClass("btn-outline-primary")
    $(this).removeClass("btn-outline-dark")
    $(this).addClass("btn-dark")
    order_type_edit_order = "OT0003"
    $("#txtDeliveryAddressEditOrderInformation").show()
  })
  
  // Select Serving Waiter - Edit Order Information
  $(document).on("click", ".cbxServingWaiterEditOrderInformation", function() {
    if (this.checked) {
      serving_waiter_edit_order = $(this).attr("serving-waiter-id")
      $(".cbxServingWaiterEditOrderInformation").not(this).prop("checked", false)
    } else {
      serving_waiter_edit_order = "-"
    }
   
  })

  // Edit Order and Print - Edit Order Information
  $(document).on("click", "#btnEditAndPrintEditOrderInformation", function (e) {
    e.preventDefault()

    let ordered_products_list_edit_order = []
    let selected_order_id = order_id_edit_order_information
    let selected_order_type = order_type_edit_order
    let selected_customer_id = $("#cmbCustomerIddEditOrderInformation").val()
    let selected_delivery_address = $("#txtDeliveryAddressEditOrderInformation").val() == "" ? "-" : $("#txtDeliveryAddressEditOrderInformation").val()
    let selected_waiter_id = serving_waiter_edit_order
    $('[id^="editOrderedProductId"]').each(function() {
      ordered_products_list_edit_order.push([$(this).attr("ordered-product-id"), $(this).find(".orderedProductQuantityEditOrderInformation").text(), $(this).attr("ordered-product-price"), $(this).find(".orderedProductPriceEditOrderInformation").text()])
    })
    let kitchen_note_descript = $("#txtKitchenNoteEditOrderInformation").val()
    let order_subtotal_amount = (parseFloat($("#orderedProductsSubtotalEditOrderInformation").text()) || 0).toFixed(2)
    let order_discount_amount = $("#txtOrderedProductsDiscountEditOrderInformation").val() === "" ? 0.00 : (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val()) || 0).toFixed(2)
    let order_true_vat_amount = $("#txtOrderedProductsVATEditOrderInformation").val() === "" ? 0.00 : (parseFloat($("#txtOrderedProductsVATEditOrderInformation").val()) || 0).toFixed(2)
    let order_total_amount = (parseFloat($("#orderedProductsTotalEditOrderInformation").text()) || 0).toFixed(2)

    let checked_order_products_list = ordered_products_list_edit_order.length === 0 ? {"productsStatus": "false", "productsMessage": "Select Product to Save Order"} : {"productsStatus": "true", "productsMessage": ordered_products_list_edit_order}

    const order_post_parameters = {
      "action": "edit_restaurant_order_information",
      "selected_order_id": selected_order_id,
      "selected_order_type": selected_order_type,
      "selected_customer_id": selected_customer_id,
      "selected_delivery_address":  selected_delivery_address,
      "selected_waiter_id": selected_waiter_id,
      "checked_order_products_list": checked_order_products_list,
      "kitchen_note_descript": kitchen_note_descript,
      "order_subtotal_amount": order_subtotal_amount,
      "order_discount_amount": order_discount_amount,
      "order_true_vat_amount": order_true_vat_amount,
      "order_total_amount": order_total_amount
    }
    swal ({
      title: "Are you sure?", text: "You want to edit this order?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: true, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: order_post_parameters, dataType: "JSON",
          beforeSend:function(){
            $("#btnEditAndPrintEditOrderInformation").prop('disabled', true)
            $("#btnEditAndPrintEditOrderInformation").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnEditAndPrintEditOrderInformation").prop('disabled', false)
            $("#btnEditAndPrintEditOrderInformation").html("<i class='fa fa-lg fa-print'></i> Edit & Print")
            var Message = data.Message
            var status = data.Status
            if (status == true) {
              var returned_data = Message.split("####")
              $("#editRestaurantOrderModal").modal("hide")
              $("#viewAndPrintOrderReceiptModal").modal("show")
              var receipt_post = { "action": "view_and_print_order_receipt", "selected_order_id": returned_data[0], "btn_type": "Print"}
              $(".modal-body").load(returned_data[0])
              $.ajax({
                "async":false, method: "POST", url: "api/main.php", data:  receipt_post, dataType: "text",
                success: function(response) {
                  $("#viewOrderFullInformationDivisionArea").html(response)
                }, error: function(e) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
                }          
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	

          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })

  })

  // ============================ END OF EDIT ORDER SECTION MODULE SCRIPTS =====================================

    // ============================ START OF PRINT ORDER RECEIPT SECTION MODULE SCRIPTS ==========================
        
    // View Only Order Full Informational
    $(document).on("click", ".btnViewOrderInformation", function (e) {
        e.preventDefault()
        var objectID = $(this).attr("data-id")
        var btn_type = $(this).attr("btn-type")
        var post = { "action": "view_and_print_order_receipt", "selected_order_id": objectID, "btn_type": btn_type }
        $(".modal-body").load(objectID)
        $.ajax({
            method: "POST", url: "api/main.php", data:  post, dataType: "text",
            success: function(response) {
                $("#viewOrderFullInformationDivisionArea").html(response)
            }, error: function(e) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
            }          
        })
    })

    // View and Print Order Full Informational
    $(document).on("click", ".btnPrintOrderInformation", function (e) {
        e.preventDefault()
        var objectID = $(this).attr("data-id")
        var btn_type = $(this).attr("btn-type")
        var post = { "action": "view_and_print_order_receipt", "selected_order_id": objectID, "btn_type": btn_type }
        $(".modal-body").load(objectID)
        $.ajax({
            method: "POST", url: "api/main.php", data:  post, dataType: "text",
            success: function(response) {
                $("#viewOrderFullInformationDivisionArea").html(response)
            }, error: function(e) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
            }          
        })
    })

    $(document).on("click", "#printCurrentOrderReceipts", function () {
        //Display and open the print dialog box to print the report
        $(".printOrderForKitchens").each(function () {
            var report_restore_page = $("body").html()
            var report_print_area = $("#" + $(this).attr("div-to-print")).html()
            $("body").html(report_print_area)
            window.print()
            $("body").html(report_restore_page)
        })
    })
 
    // Cancel Order - Orders of Today
    $(document).on("click", ".btnCancelOrderInformation", function (e) {
        e.preventDefault()
        var objectID = $(this).attr("data-id")
        var cancel_purpose = ""
        swal ({
            title: "Are you sure?", text: "You want to cancel this order?", type: "input", animation: "slide-from-top", inputPlaceholder: "Write cancel reason...", showCancelButton: true, cancelButtonText: "Back", confirmButtonText: "Cancel", closeOnConfirm: false, closeOnCancel: true
        }, function(isConfirm) {
            if (isConfirm) {
                $(".confirm").attr("disabled", "disabled") 
                $(".confirm").attr("style", "color: #FFF") 
                $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
                var cancel_post = { "action": "cancel_restaurant_order_now", "selected_order_id": objectID, "cancel_purpose": isConfirm}
                $.ajax({
                    url: "api/main.php", type: "POST", data: cancel_post, dataType: "JSON",
                    beforeSend:function(){
                        $(".btnCancelOrderInformation").prop('disabled', true)
                        $(".btnCancelOrderInformation").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
                    }, success: function(data) {
                        $(".btnCancelOrderInformation").prop('disabled', false)
                        $(".btnCancelOrderInformation").html("<i class='fa fa-times fa-md'></i> Cancel")
                        var Message = data.Message
                        var status = data.Status
                        if (status == true) {		
                            swal ({
                                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
                            }, function(isConfirm) {
                                if (isConfirm) location.reload()
                            })
                        } else {
                            Message.forEach(function (error) {
                                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
                            })
                        }	
                    }, error: function(e) {
                        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
                    }          
                })
            }
        })
    })

  // ============================ END OF PRINT ORDER RECEIPT SECTION MODULE SCRIPTS ============================
  
    // ============================ Start of Search Date Based Orders Section ==================================

    $("#txtFromDateSearchDateBasedOrders, #txtToDateSearchDateBasedOrders").val(todays_date)
    $("#txtFromDateSearchDateBasedOrders, #txtToDateSearchDateBasedOrders").prop("max", todays_date)

    $("#searchDateBasedOrderForm").on('submit', function (e) {
        e.preventDefault()
        var selected_order_status = $("#cmbOrderStatusSearchDateBasedOrders").val()
        var selected_start_date = $("#txtFromDateSearchDateBasedOrders").val() + " 06:00"
        var selected_end_date = $("#txtToDateSearchDateBasedOrders").val() + " 06:00"
        var post = {
            "action": "search_date_based_orders", 
            "selected_order_status" : selected_order_status, 
            "selected_start_date" : selected_start_date, 
            "selected_end_date" : selected_end_date
        }
    
        $.ajax({
            type: "POST", url: "api/main.php", data: post, dataType: "text",
            beforeSend:function(){
                $("#btnSearchDateBasedOrder").prop('disabled', true)
                $("#btnSearchDateBasedOrder").html("<i class='fa fa-spinner fa-pulse' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i> Please wait")
            },
            success: function (response) {
                $("#btnSearchDateBasedOrder").prop('disabled', false)
                $("#btnSearchDateBasedOrder").html("<i class='fa fa-search' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i> Search")
                $(".dateBasedOrdersSectionArea").html(response)
            }
        })
    })
    
    // ============================ End of Search Date Based Orders Section ====================================
    
    // ============================ Start of Search Date Based Delivery Orders Section =========================

    $("#txtFromDateSearchDateBasedDeliveryOrders, #txtToDateSearchDateBasedDeliveryOrders").val(todays_date)
    $("#txtFromDateSearchDateBasedDeliveryOrders, #txtToDateSearchDateBasedDeliveryOrders").prop("max", todays_date)

    $("#searchDateBasedDeliveryOrderForm").on('submit', function (e) {
        e.preventDefault()
        var selected_order_status = $("#cmbOrderStatusSearchDateBasedDeliveryOrders").val()
        var selected_start_date = $("#txtFromDateSearchDateBasedDeliveryOrders").val() + " 06:00"
        var selected_end_date = $("#txtToDateSearchDateBasedDeliveryOrders").val() + " 06:00"
        var post = {
            "action": "search_date_based_delivery_orders", 
            "selected_order_status" : selected_order_status, 
            "selected_start_date" : selected_start_date, 
            "selected_end_date" : selected_end_date
        }
    
        $.ajax({
            type: "POST", url: "api/main.php", data: post, dataType: "text",
            beforeSend:function(){
                $("#btnSearchDateBasedDeliveryOrder").prop('disabled', true)
                $("#btnSearchDateBasedDeliveryOrder").html("<i class='fa fa-spinner fa-pulse' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i> Please wait")
            },
            success: function (response) {
                $("#btnSearchDateBasedDeliveryOrder").prop('disabled', false)
                $("#btnSearchDateBasedDeliveryOrder").html("<i class='fa fa-search' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i> Search")
                $(".dateBasedDeliveryOrdersSectionArea").html(response)
            }
        })
    })
    
    // ============================ End of Search Date Based Delivery Orders Section ===========================



  // ============================ START OF CUSTOMER PAYMENT SECTION MODULE SCRIPTS =============================

  // Filling Order Informational into Customer Payment Modal
  $(document).on("click", ".btnPuyNowCustomerPayment", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    var post = { "action": "fetch_order_information", "selected_order_id": objectID }
    $(".modal-body").load(objectID)
    $.ajax({
      method: "POST", url: "api/main.php", data:  post, dataType: "text",
      success: function(response) {
        $(".orderInformationCustomerPaymentModal").html(response)      
      }, error: function(e) {
        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
      }          
    })
  })

  let count_deposit_account_unpaid_orders = 0
  // Add Deposit Account - Unpaid Orders Page
  $(document).on("click", ".btnAddDepositAccountRegisterCustomerPayment", function () {
      if (count_deposit_account_unpaid_orders < 2) {
        count_deposit_account_unpaid_orders++
        $(".depositAccountsCustomerPaymentModal").append(`<div class='row pb-2' id='depositAccountCustomerPayment${count_deposit_account_unpaid_orders}'>
          <div class='col-md-1'>
            <i class='fa fa-trash fa-2x text-danger pull-right removeDepositAccountCustomerPaymentModal' style='cursor: pointer;'></i>
          </div>
          <div class='col-md-5'>
            <select class='form-control cmbDepositAccountRegisterCustomerPayment' style='width: 100%;' name='cmbDepositAccountRegisterCustomerPayment${count_deposit_account_unpaid_orders}' id='cmbDepositAccountRegisterCustomerPayment${count_deposit_account_unpaid_orders}' required>
              
            </select>
          </div>
          <div class='col-md-3'>
            <input class='form-control text-center txtPaidAmountRegisterCustomerPayment' type='number' name='txtPaidAmountRegisterCustomerPayment${count_deposit_account_unpaid_orders}' id='txtPaidAmountRegisterCustomerPayment${count_deposit_account_unpaid_orders}' step='0.01' min='0.01' required>
          </div>
          <div class='col-md-3'>
            <textarea class='form-control txtPaymentDescriptionRegisterCustomerPayment' style='resize:none' rows='1' name='txtPaymentDescriptionRegisterCustomerPayment${count_deposit_account_unpaid_orders}' id='txtPaymentDescriptionRegisterCustomerPayment${count_deposit_account_unpaid_orders}' placeholder='Desciption' required></textarea>
          </div>	
        </div>`)

        $.ajax({    
          method: "POST", url : "api/main.php", data: {"action" : "fill_deposit_accounts"}, dataType: "JSON",
          success: function(data) {
            var Message = data.Message, status = data.Status, html = ''
            if (status == true) {
              html += `<option value="">Select Account</option>`
              Message.forEach(function(accounts_data, i) {
                  if (accounts_data['gatewayType'] === "1") html += `<option value="${accounts_data['accountNoID']}">${accounts_data['gatewayName']} (${accounts_data['accountNumber']})</option>`
                  else if (accounts_data['gatewayType'] === "2") html += `<option value="${accounts_data['accountNoID']}">${accounts_data['gatewayName']} ${accounts_data['accountNoName']} (${accounts_data['accountNumber']})</option>`
                  else if (accounts_data['gatewayType'] === "3") html += `<option value="${accounts_data['accountNoID']}">${accounts_data['accountNoName']} (${accounts_data['accountNumber']})</option>`
              })
              $("#cmbDepositAccountRegisterCustomerPayment" + count_deposit_account_unpaid_orders).html(html)
              $("#cmbDepositAccountRegisterCustomerPayment" + count_deposit_account_unpaid_orders).select2({ tags: false, dropdownParent: $("#registerCustomerPaymentModal") })
            }
          },error : function(data){ }
        })
        $("#txtPaidAmountRegisterCustomerPayment" + count_deposit_account_unpaid_orders).focus()
      } else {
        $("#txtPaidAmountRegisterCustomerPayment" + count_deposit_account_unpaid_orders).focus()
      }

  })

  // Remove Deposit Account - Customer Payment Modal
  $(document).on("click", ".removeDepositAccountCustomerPaymentModal", function () {
    let selected_account_paid_amount = parseFloat($(this).parent().parent().find(".txtPaidAmountRegisterCustomerPayment").val()) || 0
    $("#totalPaidAmountCustomerPayments").text(((parseFloat($("#totalPaidAmountCustomerPayments").text()) || 0) - selected_account_paid_amount).toFixed(2))
    $(this).parent().parent().remove()
    count_deposit_account_unpaid_orders--
  })

  // Paid Amount Entry - Customer Payment Modal
  $(document).on("keyup focusout", ".txtPaidAmountRegisterCustomerPayment", function(e){
    let total_paid_amount = 0
    $('[id^="depositAccountCustomerPayment"]').each(function() {
      total_paid_amount += (parseFloat($(this).find(".txtPaidAmountRegisterCustomerPayment").val()) || 0)
    })
    $("#totalPaidAmountCustomerPayments").text((total_paid_amount).toFixed(2) || 0)       
})

  // Register Customer Payment - Customer Payment Modal
  $(document).on("click", "#btnRegisterCustomerPayment", function (e) {
    e.preventDefault()
    let deposit_accounts_list_customer_payment = []
    let selected_order_id = $("#txtOrderIddRegisterCustomerPayment").text()
    let selected_customer_id = $("#txtCustomerIddRegisterCustomerPayment").attr("customer-id")
    let total_customer_paid_amount = parseFloat($("#totalPaidAmountCustomerPayments").text()) || 0
    $('[id^="depositAccountCustomerPayment"]').each(function() {
      deposit_accounts_list_customer_payment.push([$(this).find(".cmbDepositAccountRegisterCustomerPayment").val(), $(this).find(".txtPaidAmountRegisterCustomerPayment").val(), $(this).find(".txtPaymentDescriptionRegisterCustomerPayment").val()])
    })

    const payment_post_parameters = {
      "action": "register_customer_payment",
      "selected_order_id": selected_order_id,
      "selected_customer_id": selected_customer_id,
      "deposit_accounts_list_customer_payment": deposit_accounts_list_customer_payment,
      "total_customer_paid_amount": total_customer_paid_amount
    }
    swal ({
      title: "Are you sure?", text: "You want to register this payment?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: payment_post_parameters, dataType: "JSON",
          beforeSend:function(){
            $("#btnRegisterCustomerPayment").prop('disabled', true)
            $("#btnRegisterCustomerPayment").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnRegisterCustomerPayment").prop('disabled', false)
            $("#btnRegisterCustomerPayment").html("<i class='fa fa-lg fa-save'></i> Register Payment")
            var Message = data.Message
            var status = data.Status
            if (status == true) {
              
              var returned_data = Message.split("####")
              
              swal ({
                title: "Print Receipt?", text: returned_data[1], type: "success", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: true, closeOnCancel: true
              }, function(isConfirm) {
                if (isConfirm) {
                  $(".confirm").attr("disabled", "disabled") 
                  $(".confirm").attr("style", "color: #FFF") 
                  $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
                  $("#registerCustomerPaymentModal").modal("hide")
                  $("#viewAndPrintOrderReceiptModal").modal("show")
                  $(".modal").attr("style", "overflow: auto !important;")
                  $("body").attr("style", "overflow: hidden !important;")
                  var receipt_post = { "action": "view_and_print_order_receipt", "selected_order_id": returned_data[0], "btn_type": "Print"}
                  $(".modal-body").load(returned_data[0])
                  $.ajax({
                    "async":false, method: "POST", url: "api/main.php", data:  receipt_post, dataType: "text",
                    success: function(response) {
                      $("#viewOrderFullInformationDivisionArea").html(response)
                    }, error: function(e) {
                      bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
                    }          
                  })
                }
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })

  })

  // ============================ END OF CUSTOMER PAYMENT SECTION MODULE SCRIPTS ===============================

  // ============================ START OF DELIVER ORDER SECTION MODULE SCRIPTS ================================

  let serving_deliverymen_id_waiting_deliveries = "-"

  // Filling Delivery Order Information - Waiting Deliveries
  $(document).on("click", ".btnDeliverNowWaitingDeliveries", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    var post = { "action": "fetch_delivery_order_information", "selected_order_id": objectID }
    $(".modal-body").load(objectID)
    $.ajax({
      method: "POST", url: "api/main.php", data:  post, dataType: "text",
      success: function(response) {
        $(".orderInformationCustomerPaymentModal").html(response)      
      }, error: function(e) { bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"}) }          
    })
  })

  // Pick Deliveryman - Waiting Deliveries
  $(document).on("click", ".cbxDeliveryManWaitingDeliveries", function() {
    if (this.checked) {
      serving_deliverymen_id_waiting_deliveries = $(this).attr("serving-deliverymen-id")
      $(".cbxDeliveryManWaitingDeliveries").not(this).prop("checked", false)
    } else {
      serving_deliverymen_id_waiting_deliveries = "-"
    }

  })

  // Register Deliver Order - Waiting Deliveries
  $(document).on("click", "#btnRegisterDeliveryWaitingDeliveries", function (e) {
    e.preventDefault()
    let selected_order_id = $("#txtOrderIddDeliverOrderNow").text()
    let selected_delivery_address = $("#txtDeliveryAddressDeliverOrderNow").text()
    let selected_deliveryman_id = serving_deliverymen_id_waiting_deliveries
    const delivery_post_parameters = {
      "action": "register_deliver_waiting_order",
      "selected_order_id": selected_order_id,
      "selected_delivery_address": selected_delivery_address,
      "selected_deliveryman_id": selected_deliveryman_id

    }
    swal ({
      title: "Are you sure?", text: "You want to register this delivery order?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: delivery_post_parameters, dataType: "JSON",
          beforeSend:function(){
            $("#btnRegisterAndPayAdminPOSPage").prop('disabled', true)
            $("#btnRegisterAndPayAdminPOSPage").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnRegisterAndPayAdminPOSPage").prop('disabled', false)
            $("#btnRegisterAndPayAdminPOSPage").html("<i class='fa fa-lg fa-save'></i> Register & Pay")
            var Message = data.Message
            var status = data.Status
            if (status == true) {		
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) location.reload()
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })

  })
  
  // Complete Now - Delivery Order Information
  $(document).on("click", ".btnCompleteNowWaitingDeliveries", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    var post = { "action": "complete_delivery_order_now", "selected_order_id": objectID }
    swal ({
      title: "Are you sure?", text: "You want to complete this delivery order?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend:function(){
            $(".btnCompleteNowWaitingDeliveries").prop('disabled', true)
            $(".btnCompleteNowWaitingDeliveries").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $(".btnCompleteNowWaitingDeliveries").prop('disabled', false)
            $(".btnCompleteNowWaitingDeliveries").html("<i class='fa fa-hourglass-1'></i>Complete Now")
            var Message = data.Message
            var status = data.Status
            if (status == true) {		
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) location.reload()
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })
  })
  
  
  let serving_deliverymen_id_change_deliveryman = "-"

  // Filling Delivery Order Information - Change Deliveryman
  $(document).on("click", ".btnChangeDeliverymanModal", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    var post = { "action": "fetch_delivery_and_deliveryman_information", "selected_order_id": objectID }
    $(".modal-body").load(objectID)
    $.ajax({
      method: "POST", url: "api/main.php", data:  post, dataType: "text",
      success: function(response) {
        $(".deliveryOrderChangeDeliverymanAreaSection").html(response)      
      }, error: function(e) { bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"}) }          
    })
  })

  // Pick Deliveryman - Change Deliveryman
  $(document).on("click", ".cbxDeliveryManChangeDeliveryman", function() {
    if (this.checked) {
      serving_deliverymen_id_change_deliveryman = $(this).attr("current-selected-deliverymen-id")
      $(".cbxDeliveryManChangeDeliveryman").not(this).prop("checked", false)
    } else {
      serving_deliverymen_id_change_deliveryman = "-"
    }

  })
  
  // Change Deliverman Order
  $(document).on("click", "#btnChangeDeliverymanDeliveryOrder", function (e) {
    e.preventDefault()
    let selected_order_id = $("#txtOrderIddChangeDeliveryman").text()
    let selected_deliveryman_id = serving_deliverymen_id_change_deliveryman
    const delivery_post_parameters = {
      "action": "change_deliveryman_delivery_order",
      "selected_order_id": selected_order_id,
      "selected_deliveryman_id": selected_deliveryman_id
    }
    swal ({
      title: "Are you sure?", text: "You want to change this deliveryman?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: delivery_post_parameters, dataType: "JSON",
          beforeSend:function(){
            $("#btnChangeDeliverymanDeliveryOrder").prop('disabled', true)
            $("#btnChangeDeliverymanDeliveryOrder").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnChangeDeliverymanDeliveryOrder").prop('disabled', false)
            $("#btnChangeDeliverymanDeliveryOrder").html("<i class='fa fa-lg fa-refresh'></i> Change Deliveryman")
            var Message = data.Message
            var status = data.Status
            if (status == true) {		
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: true, closeOnCancel: false
              }, function(isConfirm) {
                // $("#changeDeliverymanModal").modal("hide")
                if (isConfirm) location.reload()
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })

  })
  
  // ============================ END OF DELIVER ORDER SECTION MODULE SCRIPTS ==================================

  // ============================ START OF WAITER LOGIN SECTION MODULE SCRIPTS =================================

  $("#txtWaiterPasswordWaitersLoginPage").focus()

  // When a key in the keyboard is clicked
  $(document).on("click", ".btnWaiterKeyboardNumbersWaitersLoginPage", function() {
    $("#txtWaiterPasswordWaitersLoginPage").val($("#txtWaiterPasswordWaitersLoginPage").val() + $(this).text())
  })

  // Clear button is clickes
  $(document).on("click", ".btnClearNumbersWaitersLoginPage", function() {
    $("#txtWaiterPasswordWaitersLoginPage").val("")
    $("#txtWaiterPasswordWaitersLoginPage").focus()
  })

  // Login Button is Clicked - Waiter Login Page
  $("#waiterLoginPageForm").on('submit', function (e) {
    e.preventDefault()
    let entered_waiter_passcode = $("#txtWaiterPasswordWaitersLoginPage").val()
    const waiter_login_post_parameters = { "action": "waiter_login_process", "entered_waiter_passcode": entered_waiter_passcode}

    $.ajax({
      url: "api/main.php", type: "POST", data: waiter_login_post_parameters, dataType: "JSON",
      beforeSend:function(){
        $("#btnLoginWaitersLoginPage").prop('disabled', true)
        $("#btnLoginWaitersLoginPage").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
      }, success: function(data) {
        $("#btnLoginWaitersLoginPage").prop('disabled', false)
        $("#btnLoginWaitersLoginPage").html("<i class='fa fa-lg fa-sign-in'></i> Login")
        var Message = data.Message
        var status = data.Status
        if (status == true) {		
          location = Message
        } else {
          Message.forEach(function (error) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
          })
        }	
      }, error: function(e) {bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})}          
    })
 
  })

  // ============================ END OF WAITER LOGIN SECTION MODULE SCRIPTS ===================================

  // ============================ START OF WAITER DASHBOARD SECTION MODULE SCRIPTS =============================

  // ============================ END OF WAITER DASHBOARD SECTION MODULE SCRIPTS ===============================

  // ============================ START OF WAITER POS SECTION MODULE SCRIPTS ===================================

  $("#btnSeatInWaiterPOSPage").removeClass("btn-outline-success")
  $("#btnSeatInWaiterPOSPage").addClass("btn-success")
  let order_type_waiter_pos = "OT0001"

  // Fetch Restaurant Products By Category - Waiter POS Page
  $(document).on('click', '.restaurant_categories_waiter_pos', function () {
    $("#txtSearchRestaurantProductLiveWaiterPOS").val("")
    category_id_waiter_pos = $(this).attr("category-id")
    $(".restaurant_categories_waiter_pos").removeClass("btn-primary")
    $(".restaurant_categories_waiter_pos").addClass("btn-light")
    $(this).removeClass("btn-light")
    $(this).addClass("btn-primary")
    let post = { "action": "fetch_restaurant_products_by_category_waiter_pos", "category_id_waiter_pos": category_id_waiter_pos}
    $.ajax({
      type: "POST", url: "api/main.php", data: post, dataType: "text",
      success: function (response) {
        $(".restaurantProductsWaiterPOSPageArea").html(response)
      }
    })
  })

  // Search Product - Waiter POS Page Live
  $(document).on("keyup", "#txtSearchRestaurantProductLiveWaiterPOS", function () {
    var searched_product_name = $(this).val()
    var post = { "action": "search_restaurant_product_live_waiter_pos", "searched_product_name": searched_product_name, "category_id_waiter_pos": category_id_waiter_pos}
    $.ajax({
      type: "POST", url: "api/main.php", data: post, dataType: "text",
      success: function (response) {
        $(".restaurantProductsWaiterPOSPageArea").html(response)
      }
    })
  })

  // Selcet Product to Checkout - Waiter POS Page
  $(document).on("click", ".singleProductWaiterPOSPageArea", function () {
    var selected_product_id = $(this).attr("product-id")
    var selected_product_name = $(this).attr("product-name")
    var selected_product_price = parseFloat($(this).attr("product-price")) || 0
    var order_subtotal_admin_pos = ((parseFloat($("#orderedProductsSubtotalWaiterPOS").text()) || 0) + selected_product_price).toFixed(2)
    
    var order_vat_admin_pos = ((parseFloat(order_subtotal_admin_pos) || 0) * 0.05).toFixed(2)
    var order_true_vat_admin_pos = (((parseFloat(order_subtotal_admin_pos) || 0) + (parseFloat(order_vat_admin_pos) || 0)) * 0.05).toFixed(2)
    var order_total_admin_pos = ((parseFloat(order_subtotal_admin_pos) || 0) + (parseFloat(order_true_vat_admin_pos) || 0)).toFixed(2)
    
    
    // var order_total_admin_pos = (parseFloat(order_subtotal_admin_pos) || 0).toFixed(2)
    if ($("#waiterOrderedProductId" + selected_product_id).length == 0) {
      $(".orderedProductsWaiterPOSPageArea").closest('div').append(`<div class='row align-items-center font-weight-bold p-2 border-bottom border-light' style='margin: 0px;' id='waiterOrderedProductId${selected_product_id}' ordered-product-id='${selected_product_id}' ordered-product-price='${selected_product_price}'>\
          <div class='col-md-1 text-left'><i class='fa fa-trash fa-lg text-danger removeOrderedProductWaiterPOS' style='cursor: pointer;'></i></div>\
          <div class='col-md-5'>${selected_product_name}</div>\
          <div class='col-md-4'>\
              <button class='btn btn-outline-success rounded-pill btnIncrementProductQuantityWaiterPOS'><span class='font-weight-bold'>+</span></button><span class='pl-2 pr-2 orderedProductQuantityWaiterPOS'>1</span><button class='btn btn-outline-danger rounded-pill btnDecrementProductQuantityWaiterPOS'><span class='font-weight-bold'>-</span></button>\
          </div>\
          <div class='col-md-2'>$<span class='orderedProductPriceWaiterPOS' >${selected_product_price.toFixed(2)}</div></div>\
      </div>`)
      $("#orderedProductsSubtotalWaiterPOS").text(order_subtotal_admin_pos)
      
      $("#txtOrderedProductsVATWaiterPOS").text(order_true_vat_admin_pos)   
      $("#orderedProductsTotalWaiterPOS").text(order_total_admin_pos)

      
    //   $("#orderedProductsTotalWaiterPOS").text(order_total_admin_pos)
    } else {
      let selected_product_quantity = (parseInt($("#waiterOrderedProductId" + selected_product_id + " .orderedProductQuantityWaiterPOS").text()) || 0) + 1
      let selected_product_total_price = parseFloat(selected_product_quantity * selected_product_price) || 0
      $("#waiterOrderedProductId" + selected_product_id + " .orderedProductQuantityWaiterPOS").text(selected_product_quantity)
      $("#waiterOrderedProductId" + selected_product_id + " .orderedProductPriceWaiterPOS").text(selected_product_total_price.toFixed(2))
      $("#orderedProductsSubtotalWaiterPOS").text(order_subtotal_admin_pos)
      
      $("#txtOrderedProductsVATWaiterPOS").text(order_true_vat_admin_pos)   
      $("#orderedProductsTotalWaiterPOS").text(order_total_admin_pos)
      
      $("#orderedProductsTotalWaiterPOS").text(order_total_admin_pos)    
    }
  })

  // Increment Ordered Product - Waiter POS Page
  $(document).on("click", ".btnIncrementProductQuantityWaiterPOS", function () {
    let selected_product_quantity = (parseInt($(this).parent().find(".orderedProductQuantityWaiterPOS").text()) || 0) + 1
    let selected_product_price = parseFloat($(this).parent().parent().attr("ordered-product-price")) || 0
    var order_subtotal_admin_pos = ((parseFloat($("#orderedProductsSubtotalWaiterPOS").text()) || 0) + selected_product_price).toFixed(2)
    
    var order_vat_admin_pos = ((parseFloat(order_subtotal_admin_pos) || 0) * 0.05).toFixed(2)
    var order_true_vat_admin_pos = (((parseFloat(order_subtotal_admin_pos) || 0) + (parseFloat(order_vat_admin_pos) || 0)) * 0.05).toFixed(2)
    var order_total_admin_pos = ((parseFloat(order_subtotal_admin_pos) || 0) + (parseFloat(order_true_vat_admin_pos) || 0)).toFixed(2)
    
    
    // var order_total_admin_pos = (parseFloat(order_subtotal_admin_pos) || 0).toFixed(2)
    $(this).parent().find(".orderedProductQuantityWaiterPOS").text(selected_product_quantity)
    $(this).parent().next().find(".orderedProductPriceWaiterPOS").text((parseFloat(selected_product_quantity * selected_product_price) || 0).toFixed(2))
    $("#orderedProductsSubtotalWaiterPOS").text(order_subtotal_admin_pos)
    
    $("#txtOrderedProductsVATWaiterPOS").text(order_true_vat_admin_pos)   
    $("#orderedProductsTotalWaiterPOS").text(order_total_admin_pos)
    
    // $("#orderedProductsTotalWaiterPOS").text(order_total_admin_pos)   

  })

  // Decrement Ordered Product - Waiter POS Page
  $(document).on("click", ".btnDecrementProductQuantityWaiterPOS", function () {
    let selected_product_quantity = parseInt($(this).parent().find(".orderedProductQuantityWaiterPOS").text()) || 0
    let selected_product_price = parseFloat($(this).parent().parent().attr("ordered-product-price")) || 0
    var order_subtotal_admin_pos = ((parseFloat($("#orderedProductsSubtotalWaiterPOS").text()) || 0) - selected_product_price).toFixed(2)
    
    var order_vat_admin_pos = ((parseFloat(order_subtotal_admin_pos) || 0) * 0.05).toFixed(2)
    var order_true_vat_admin_pos = (((parseFloat(order_subtotal_admin_pos) || 0) + (parseFloat(order_vat_admin_pos) || 0)) * 0.05).toFixed(2)
    var order_total_admin_pos = ((parseFloat(order_subtotal_admin_pos) || 0) + (parseFloat(order_true_vat_admin_pos) || 0)).toFixed(2)
    
    
    // var order_total_admin_pos = (parseFloat(order_subtotal_admin_pos) || 0).toFixed(2)
    if (selected_product_quantity > 1) {
      selected_product_quantity--
      $(this).parent().find(".orderedProductQuantityWaiterPOS").text(selected_product_quantity)
      $(this).parent().next().find(".orderedProductPriceWaiterPOS").text((parseFloat(selected_product_quantity * selected_product_price) || 0).toFixed(2))
      $("#orderedProductsSubtotalWaiterPOS").text(order_subtotal_admin_pos)
      
      $("#txtOrderedProductsVATWaiterPOS").text(order_true_vat_admin_pos)   
      $("#orderedProductsTotalWaiterPOS").text(order_total_admin_pos)
      
    //   $("#orderedProductsTotalWaiterPOS").text(order_total_admin_pos) 
    }

  })

  // Remove Ordered Product - Waiter POS Page
  $(document).on("click", ".removeOrderedProductWaiterPOS", function () {
    let selected_product_price = parseFloat($(this).parent().parent().find(".orderedProductPriceWaiterPOS").text()) || 0
    var order_subtotal_admin_pos = ((parseFloat($("#orderedProductsSubtotalWaiterPOS").text()) || 0) - selected_product_price).toFixed(2)
    
    var order_vat_admin_pos = ((parseFloat(order_subtotal_admin_pos) || 0) * 0.05).toFixed(2)
    var order_true_vat_admin_pos = (((parseFloat(order_subtotal_admin_pos) || 0) + (parseFloat(order_vat_admin_pos) || 0)) * 0.05).toFixed(2)
    var order_total_admin_pos = ((parseFloat(order_subtotal_admin_pos) || 0) + (parseFloat(order_true_vat_admin_pos) || 0)).toFixed(2)
    
    
    // var order_total_admin_pos = (parseFloat(order_subtotal_admin_pos) || 0).toFixed(2)
    $("#orderedProductsSubtotalWaiterPOS").text(order_subtotal_admin_pos)
    $("#txtOrderedProductsVATWaiterPOS").text(order_true_vat_admin_pos)   
    $("#orderedProductsTotalWaiterPOS").text(order_total_admin_pos)
    
    // $("#orderedProductsTotalWaiterPOS").text(order_total_admin_pos)
    $(this).parent().parent().remove()
  })

  // Select Seat In - Waiter POS
  $(document).on("click", "#btnSeatInWaiterPOSPage", function () {
    $(this).removeClass("btn-outline-success")
    $(this).addClass("btn-success")
    $("#btnTakeAwayWaiterPOSPage").removeClass("btn-primary")
    $("#btnTakeAwayWaiterPOSPage").addClass("btn-outline-primary")
    order_type_waiter_pos = "OT0001"
  })

  // Select TakeAway - Waiter POS
  $(document).on("click", "#btnTakeAwayWaiterPOSPage", function () {
    $("#btnSeatInWaiterPOSPage").removeClass("btn-success")
    $("#btnSeatInWaiterPOSPage").addClass("btn-outline-success")
    $(this).removeClass("btn-outline-primary")
    $(this).addClass("btn-primary")
    order_type_waiter_pos = "OT0002"
  })

  // Hold Order - Waiter POS
  $(document).on("click", "#btnHoldOrderWaiterPOSPage", function (e) {
    e.preventDefault()

    let ordered_products_list_admin_pos = []
    let selected_order_type = order_type_waiter_pos
    let selected_customer_id = $("#cmbCustomerIddNewOrderWaiterPOSPage").val()
    $('[id^="waiterOrderedProductId"]').each(function() {
      ordered_products_list_admin_pos.push([$(this).attr("ordered-product-id"), $(this).find(".orderedProductQuantityWaiterPOS").text(), $(this).attr("ordered-product-price"), $(this).find(".orderedProductPriceWaiterPOS").text()])
    })
    let kitchen_note_descript = $("#txtKitchenNoteNewOrderWaiterPOSPage").val()
    let order_subtotal_amount = (parseFloat($("#orderedProductsSubtotalWaiterPOS").text()) || 0).toFixed(2)
    let order_true_vat_amount = (parseFloat($("#txtOrderedProductsVATWaiterPOS").text()) || 0).toFixed(2)
    let order_total_amount = (parseFloat($("#orderedProductsTotalWaiterPOS").text()) || 0).toFixed(2)
    let checked_order_products_list = ordered_products_list_admin_pos.length === 0 ? {"productsStatus": "false", "productsMessage": "Select Product to Save Order"} : {"productsStatus": "true", "productsMessage": ordered_products_list_admin_pos}

    const order_post_parameters = {
      "action": "register_restaurant_order_waiter_pos_page",
      "selected_order_type": selected_order_type,
      "selected_customer_id": selected_customer_id,
      "checked_order_products_list": checked_order_products_list,
      "kitchen_note_descript": kitchen_note_descript,
      "order_subtotal_amount": order_subtotal_amount,
      "order_true_vat_amount": order_true_vat_amount,
      "order_total_amount": order_total_amount
    }
    swal ({
      title: "Are you sure?", text: "You want to hold this order?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: true, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: order_post_parameters, dataType: "JSON",
          beforeSend:function(){
            $("#btnHoldOrderWaiterPOSPage").prop('disabled', true)
            $("#btnHoldOrderWaiterPOSPage").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnHoldOrderWaiterPOSPage").prop('disabled', false)
            $("#btnHoldOrderWaiterPOSPage").html("<i class='fa fa-lg fa-pause'></i> Hold Order")
            var Message = data.Message
            var status = data.Status
            if (status == true) {
              var returned_data = Message.split("####")
              $("#viewAndPrintOrderReceiptModal").modal("show")
              var receipt_post = { "action": "view_and_print_order_receipt", "selected_order_id": returned_data[0], "btn_type": "Print"}
              $(".modal-body").load(returned_data[0])
              $.ajax({
                "async":false, method: "POST", url: "api/main.php", data:  receipt_post, dataType: "text",
                success: function(response) {
                  $("#viewOrderFullInformationDivisionArea").html(response)
                }, error: function(e) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
                }          
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })

  })

  // ============================ END OF WAITER POS SECTION MODULE SCRIPTS =====================================

  // ============================ START OF EDIT WAITER ORDER SECTION MODULE SCRIPTS ============================

    let order_type_edit_waiter_order = ""
    let order_id_edit_waiter_order_information
    
    // Fetch Order Full Informational - Edit Waiter Order Modal
    $(document).on("click", ".btnEditOrderInformationWaiterPOS", function (e) {
      e.preventDefault()
      var objectID = $(this).attr("data-id")
      var post = { "action": "fetch_waiter_order_full_information_to_edit", "selected_order_id": objectID }
      $(".modal-body").load(objectID)
      $.ajax({
        method: "POST", url: "api/main.php", data:  post, dataType: "text",
        success: function(response) {
          $("#orderFullInformationWaiterPOSDivisionArea").html(response)
          order_id_edit_waiter_order_information = $(".txtOrderIddWaiterPOSEditOrderInformation").attr("order-id-to-edit")
          order_type_edit_waiter_order = $(".btnOrderTypeWaiterPOSEditOrderInformation").attr("order-type-edit-order")
        }, error: function(e) {
          bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
        }          
      })
    })
  
    // Fetch Restaurant Products By Category - Edit Waiter Order Information
    $(document).on('click', '.restaurant_categories_edit_waiter_order', function () {
      $("#txtSearchRestaurantProductLiveWaiterPOSEditOrderInformation").val("")
      category_id_edit_waiter_pos = $(this).attr("category-id")
      $(".restaurant_categories_edit_waiter_order").removeClass("btn-primary")
      $(".restaurant_categories_edit_waiter_order").addClass("btn-light")
      $(this).removeClass("btn-light")
      $(this).addClass("btn-primary")
      let post = {"action": "fetch_restaurant_products_by_category_edit_waiter_order", "category_id_edit_waiter_pos": category_id_edit_waiter_pos}
      $.ajax({
        type: "POST", url: "api/main.php", data: post, dataType: "text",
        success: function (response) {
          $(".restaurantProductsWaiterPOSEditOrderInformation").html(response)
        }
      })
    })
  
    // Search Product Live - Edit Waiter Order Information
    $(document).on("keyup", "#txtSearchRestaurantProductLiveWaiterPOSEditOrderInformation", function () {
      var searched_product_name = $(this).val()
      var post = { "action": "search_restaurant_product_live_edit_waiter_order", "searched_product_name": searched_product_name, "category_id_edit_waiter_pos": category_id_edit_waiter_pos}
      $.ajax({
        type: "POST", url: "api/main.php", data: post, dataType: "text",
        success: function (response) {
          $(".restaurantProductsWaiterPOSEditOrderInformation").html(response)
        }
      })
    })
  
    // Selcet Product to Checkout - Edit Waiter Order Information
    $(document).on("click", ".singleProductWaiterPOSEditOrderInformation", function () {
      var selected_product_id = $(this).attr("product-id")
      var selected_product_name = $(this).attr("product-name")
      var selected_product_price = parseFloat($(this).attr("product-price")) || 0
      var order_subtotal_edit_order = ((parseFloat($("#waiterOrderedProductsSubtotalEditOrderInformation").text()) || 0) + selected_product_price).toFixed(2)
      
      var order_vat_edit_order = ((parseFloat(order_subtotal_edit_order) || 0) * 0.05).toFixed(2)
      var order_true_vat_edit_order = (((parseFloat(order_subtotal_edit_order) || 0) + (parseFloat(order_vat_edit_order) || 0)) * 0.05).toFixed(2)
      var order_total_edit_order = ((parseFloat(order_subtotal_edit_order) || 0) + (parseFloat(order_true_vat_edit_order) || 0)).toFixed(2)
    
      
    //   var order_total_edit_order = (order_subtotal_edit_order - (parseFloat($("#txtOrderedProductsDiscountEditOrderInformation").val() || 0)) || 0).toFixed(2)
      if ($("#editWaiterOrderedProductId" + selected_product_id).length == 0) {
        $(".orderedProductsWaiterPOSEditOrderInformation").closest('div').append(`<div class='row align-items-center font-weight-bold pt-2 pb-2 border-bottom border-light' style='margin: 0px;' id='editWaiterOrderedProductId${selected_product_id}' ordered-product-id='${selected_product_id}' ordered-product-price='${selected_product_price}'>\
            <div class='col-md-1 text-left'><i class='fa fa-trash fa-lg text-danger removeWaiterOrderedProductEditOrderInformation' style='cursor: pointer;'></i></div>\
            <div class='col-md-5'>${selected_product_name}</div>\
            <div class='col-md-4'>\
                <button class='btn btn-outline-success rounded-pill btnIncrementProductQuantityWaiterPOSEditOrderInformation'><span class='font-weight-bold'>+</span></button><span class='pl-2 pr-2 waiterOrderedProductQuantityEditOrderInformation'>1</span><button class='btn btn-outline-danger rounded-pill btnDecrementProductQuantityWaiterPOSEditOrderInformation' original-product-quantity="1"><span class='font-weight-bold'>-</span></button>\
            </div>\
            <div class='col-md-2'>$<span class='waiterOrderedProductPriceEditOrderInformation' >${selected_product_price.toFixed(2)}</div></div>\
        </div>`)
        $("#waiterOrderedProductsSubtotalEditOrderInformation").text(order_subtotal_edit_order)
        $("#txtOrderedProductsVATWaiterPOSEditOrderInformation").text(order_true_vat_edit_order)
        $("#waiterOrderedProductsTotalEditOrderInformation").text(order_total_edit_order)
      } else {
        let selected_product_quantity = (parseInt($("#editWaiterOrderedProductId" + selected_product_id + " .waiterOrderedProductQuantityEditOrderInformation").text()) || 0) + 1
        let selected_product_total_price = parseFloat(selected_product_quantity * selected_product_price) || 0
        $("#editWaiterOrderedProductId" + selected_product_id + " .waiterOrderedProductQuantityEditOrderInformation").text(selected_product_quantity)
        $("#editWaiterOrderedProductId" + selected_product_id + " .waiterOrderedProductPriceEditOrderInformation").text(selected_product_total_price.toFixed(2))
        $("#waiterOrderedProductsSubtotalEditOrderInformation").text(order_subtotal_edit_order)
        $("#txtOrderedProductsVATWaiterPOSEditOrderInformation").text(order_true_vat_edit_order)
        $("#waiterOrderedProductsTotalEditOrderInformation").text(order_total_edit_order)    
      }
    })
  
    // Increment Ordered Product - Edit Waiter Order Information
    $(document).on("click", ".btnIncrementProductQuantityWaiterPOSEditOrderInformation", function () {
      let selected_product_quantity = (parseInt($(this).parent().find(".waiterOrderedProductQuantityEditOrderInformation").text()) || 0) + 1
      let selected_product_price = parseFloat($(this).parent().parent().attr("ordered-product-price")) || 0
      var order_subtotal_edit_order = ((parseFloat($("#waiterOrderedProductsSubtotalEditOrderInformation").text()) || 0) + selected_product_price).toFixed(2)
      
       var order_vat_edit_order = ((parseFloat(order_subtotal_edit_order) || 0) * 0.05).toFixed(2)
      var order_true_vat_edit_order = (((parseFloat(order_subtotal_edit_order) || 0) + (parseFloat(order_vat_edit_order) || 0)) * 0.05).toFixed(2)
      var order_total_edit_order = ((parseFloat(order_subtotal_edit_order) || 0) + (parseFloat(order_true_vat_edit_order) || 0)).toFixed(2)
    
      
    //   var order_total_edit_order = order_subtotal_edit_order
      $(this).parent().find(".waiterOrderedProductQuantityEditOrderInformation").text(selected_product_quantity)
      $(this).parent().next().find(".waiterOrderedProductPriceEditOrderInformation").text((parseFloat(selected_product_quantity * selected_product_price) || 0).toFixed(2))
      $("#waiterOrderedProductsSubtotalEditOrderInformation").text(order_subtotal_edit_order)
      $("#txtOrderedProductsVATWaiterPOSEditOrderInformation").text(order_true_vat_edit_order)
      $("#waiterOrderedProductsTotalEditOrderInformation").text(order_total_edit_order)   
    })
  
    // Decrement Ordered Product - Edit Waiter Order Information
    $(document).on("click", ".btnDecrementProductQuantityWaiterPOSEditOrderInformation", function () {
      let original_quantity = parseInt($(this).attr("original-product-quantity"))
      let selected_product_quantity = parseInt($(this).parent().find(".waiterOrderedProductQuantityEditOrderInformation").text()) || 0
      let selected_product_price = parseFloat($(this).parent().parent().attr("ordered-product-price")) || 0
      var order_subtotal_edit_order = ((parseFloat($("#waiterOrderedProductsSubtotalEditOrderInformation").text()) || 0) - selected_product_price).toFixed(2)
      
      var order_vat_edit_order = ((parseFloat(order_subtotal_edit_order) || 0) * 0.05).toFixed(2)
      var order_true_vat_edit_order = (((parseFloat(order_subtotal_edit_order) || 0) + (parseFloat(order_vat_edit_order) || 0)) * 0.05).toFixed(2)
      var order_total_edit_order = ((parseFloat(order_subtotal_edit_order) || 0) + (parseFloat(order_true_vat_edit_order) || 0)).toFixed(2)
    
      
    //   var order_total_edit_order = order_subtotal_edit_order
      if (selected_product_quantity > original_quantity) {
        selected_product_quantity--
        $(this).parent().find(".waiterOrderedProductQuantityEditOrderInformation").text(selected_product_quantity)
        $(this).parent().next().find(".waiterOrderedProductPriceEditOrderInformation").text((parseFloat(selected_product_quantity * selected_product_price) || 0).toFixed(2))
        $("#waiterOrderedProductsSubtotalEditOrderInformation").text(order_subtotal_edit_order)
        $("#txtOrderedProductsVATWaiterPOSEditOrderInformation").text(order_true_vat_edit_order)
        $("#waiterOrderedProductsTotalEditOrderInformation").text(order_total_edit_order) 
      }
    })

    // Remove Ordered Product - Edit Waiter Order Information
    $(document).on("click", ".removeWaiterOrderedProductEditOrderInformation", function () {
    let selected_product_price = parseFloat($(this).parent().parent().find(".waiterOrderedProductPriceEditOrderInformation").text()) || 0
    var order_subtotal_edit_order = ((parseFloat($("#waiterOrderedProductsSubtotalEditOrderInformation").text()) || 0) - selected_product_price).toFixed(2)
    
    var order_vat_edit_order = ((parseFloat(order_subtotal_edit_order) || 0) * 0.05).toFixed(2)
    var order_true_vat_edit_order = (((parseFloat(order_subtotal_edit_order) || 0) + (parseFloat(order_vat_edit_order) || 0)) * 0.05).toFixed(2)
    var order_total_edit_order = ((parseFloat(order_subtotal_edit_order) || 0) + (parseFloat(order_true_vat_edit_order) || 0)).toFixed(2)
    
    
    // var order_total_edit_order = (parseFloat(order_subtotal_edit_order) || 0).toFixed(2)
    $("#waiterOrderedProductsSubtotalEditOrderInformation").text(order_subtotal_edit_order)
    $("#txtOrderedProductsVATWaiterPOSEditOrderInformation").text(order_true_vat_edit_order)
    $("#waiterOrderedProductsTotalEditOrderInformation").text(order_total_edit_order)
    $(this).parent().parent().remove()
  })
  
    // Select Seat In - Edit Waiter Order Information
    $(document).on("click", "#btnSeatInWaiterPOSEditOrderInformation", function () {
      $(this).removeClass("btn-outline-success")
      $(this).addClass("btn-success")
      $("#btnTakeAwayWaiterPOSEditOrderInformation").removeClass("btn-primary")
      $("#btnTakeAwayWaiterPOSEditOrderInformation").addClass("btn-outline-primary")
      order_type_edit_waiter_order = "OT0001"
    })
  
    // Select TakeAway - Edit Waiter Order Information
    $(document).on("click", "#btnTakeAwayWaiterPOSEditOrderInformation", function () {
      $("#btnSeatInWaiterPOSEditOrderInformation").removeClass("btn-success")
      $("#btnSeatInWaiterPOSEditOrderInformation").addClass("btn-outline-success")
      $(this).removeClass("btn-outline-primary")
      $(this).addClass("btn-primary")
      order_type_edit_waiter_order = "OT0002"
    })

    // Edit Order and Print - Edit Waiter Order Information
    $(document).on("click", "#btnEditAndPrintWaiterOrderEditOrderInformation", function (e) {
      e.preventDefault()
  
      let waiter_ordered_products_list_edit_order = []
      let selected_order_id = order_id_edit_waiter_order_information
      let selected_order_type = order_type_edit_waiter_order
      let selected_customer_id = $("#cmbCustomerIddWaiterPOSEditOrderInformation").val()
      $('[id^="editWaiterOrderedProductId"]').each(function() {
        waiter_ordered_products_list_edit_order.push([$(this).attr("ordered-product-id"), $(this).find(".waiterOrderedProductQuantityEditOrderInformation").text(), $(this).attr("ordered-product-price"), $(this).find(".waiterOrderedProductPriceEditOrderInformation").text()])
      })
      let order_subtotal_amount = (parseFloat($("#waiterOrderedProductsSubtotalEditOrderInformation").text()) || 0).toFixed(2)
      let order_true_vat_amount = (parseFloat($("#txtOrderedProductsVATWaiterPOSEditOrderInformation").text()) || 0).toFixed(2)
      let order_total_amount = (parseFloat($("#waiterOrderedProductsTotalEditOrderInformation").text()) || 0).toFixed(2)
  
      let checked_order_products_list = waiter_ordered_products_list_edit_order.length === 0 ? {"productsStatus": "false", "productsMessage": "Select Product to Save Order"} : {"productsStatus": "true", "productsMessage": waiter_ordered_products_list_edit_order}
  
      const order_post_parameters = {
        "action": "edit_restaurant_waiter_order_information",
        "selected_order_id": selected_order_id,
        "selected_order_type": selected_order_type,
        "selected_customer_id": selected_customer_id,
        "checked_order_products_list": checked_order_products_list,
        "order_subtotal_amount": order_subtotal_amount,
        "order_true_vat_amount": order_true_vat_amount,
        "order_total_amount": order_total_amount
      }
      swal ({
        title: "Are you sure?", text: "You want to edit this order?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: true, closeOnCancel: true
      }, function(isConfirm) {
        if (isConfirm) {
          $(".confirm").attr("disabled", "disabled") 
          $(".confirm").attr("style", "color: #FFF") 
          $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
          $.ajax({
            url: "api/main.php", type: "POST", data: order_post_parameters, dataType: "JSON",
            beforeSend:function(){
              $("#btnEditAndPrintEditOrderInformation").prop('disabled', true)
              $("#btnEditAndPrintEditOrderInformation").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
            }, success: function(data) {
              $("#btnEditAndPrintEditOrderInformation").prop('disabled', false)
              $("#btnEditAndPrintEditOrderInformation").html("<i class='fa fa-lg fa-print'></i> Edit & Print")
              var Message = data.Message
              var status = data.Status
              if (status == true) {
                var returned_data = Message.split("####")
                $("#editRestaurantOrderWaiterPOSModal").modal("hide")
                $("#viewAndPrintOrderReceiptModal").modal("show")
                var receipt_post = { "action": "view_and_print_order_receipt", "selected_order_id": returned_data[0], "btn_type": "Print"}
                $(".modal-body").load(returned_data[0])
                $.ajax({
                  "async":false, method: "POST", url: "api/main.php", data:  receipt_post, dataType: "text",
                  success: function(response) {
                    $("#viewOrderFullInformationDivisionArea").html(response)
                  }, error: function(e) {
                    bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
                  }          
                })
              } else {
                Message.forEach(function (error) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
                })
              }	
  
            }, error: function(e) {
              bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
            }          
          })
        }
      })
  
    })
  
    // ============================ END OF EDIT ORDER SECTION MODULE SCRIPTS =====================================
    
  // ============================ START OF STOCK MANAGEMENT MODULE SCRIPTS =====================================
  
  // ============================ Start of Supplier Information Section ========================================

  // Register New Supplier
  $("#registerNewSupplierForm").on("submit", function (e) {
    e.preventDefault()
    var vl = $("#txtSupplierNameRegisterNewSupplier").val() + "###" + $("#txtSupplierAddressRegisterNewSupplier").val() + "###" + $("#txtContactPersonRegisterNewSupplier").val() + "###" + $("#txtSupplierMobileRegisterNewSupplier").val() + "###" + $("#txtSupplierEmailRegisterNewSupplier").val() + "###" + 1 + "###currentUserIdd###currentDateTime###-###-"
    var hasFile = "No"
    var tn = "R0QraDduWTRyVFp5NlNwbUxUeTFHQT09OjprE8gn+VafIdXVgnfZ1wc1"
    var commandType = "insert_command"
    var objName = "Supplier"
    var objPre = "SP"
    var post = {action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre}
    swal ({
      title: "Are you sure?", text: "You want to register this supplier?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend:function(){
            $("#btnRegisterNewSupplier").prop('disabled', true)
            $("#btnRegisterNewSupplier").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnRegisterNewSupplier").prop('disabled', false)
            $("#btnRegisterNewSupplier").html("<i class='fa fa-lg fa-save'></i> Register Supplier")
            var Message = data.Message
            var status = data.Status
            if (status == true) {		
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) location.reload()
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })
  })

  // Filling Data into Update Supplier Modal
  $(document).on("click", ".btnUpdateSupplier", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    var tn = "R0QraDduWTRyVFp5NlNwbUxUeTFHQT09OjprE8gn+VafIdXVgnfZ1wc1"
    var cm = "TU9yelhudWZFbW12K1RZTEh5bW81dz09Ojr6lGV65L/bnddVd7xwTVbq"
    var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
    $(".modal-body").load(objectID)
    $.ajax({
      method: "POST", url: "api/main.php", data: post, dataType: "JSON",
      success: function (data) {
        var Message = data.Message
        var status = data.Status
        if (status == true) {
          var returned_info = Message.split("###")
          $("#txtSupplierIdUpdateSupplier").val(returned_info[1])
          $("#txtSupplierNameUpdateSupplier").val(returned_info[2])
          $("#txtSupplierAddressUpdateSupplier").val(returned_info[3])
          $("#txtContactPersonUpdateSupplier").val(returned_info[4])
          $("#txtSupplierMobileUpdateSupplier").val(returned_info[5])
          $("#txtSupplierEmailUpdateSupplier").val(returned_info[6])
          $("#cmbSupplierStatusUpdateSupplier").select2().val(returned_info[7]).trigger('change')
        }
      }, error: function (e) {
        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
      }
    })
  })

  // Update Supplier Modal
  $("#updateSupplierForm").on("submit", function (e) {
    e.preventDefault()
    var vl = $("#txtSupplierIdUpdateSupplier").val() + "###" + $("#txtSupplierNameUpdateSupplier").val() + "###" + $("#txtSupplierAddressUpdateSupplier").val() + "###" + $("#txtContactPersonUpdateSupplier").val() + "###" + $("#txtSupplierMobileUpdateSupplier").val() + "###" + $("#txtSupplierEmailUpdateSupplier").val() + "###" + $("#cmbSupplierStatusUpdateSupplier").val() + "###currentUserIdd###currentDateTime"
    var tn = "R0QraDduWTRyVFp5NlNwbUxUeTFHQT09OjprE8gn+VafIdXVgnfZ1wc1"
    var cm = "QWRGUmhJUkVudEZlYmVOT05mZzVQZkJSMjZiU3VLekFkeUNYQlh6ajNXdTIvY0VJVTBrTFZKdDNZcjRoNi9DWlVvUUtDczdDc3F4Ulp6bEpDZ2tYam1MVitTWEVVMmNvbHJuWkJINkJpd1B2NXVCODB5S1JPSVpmMjdnVS9rWEVTZnpBc3lpdWk4TFVkWEovOWlCTk1CL042cVZZL0x5cHBVbmJBN2cvZEFla1pkb0p1K0x1ZTN3am9Ed2dOTDJDOjoKnBxyep+KsZHOfIsDIzYT"
    var commandType = "update_command"
    var hasFile = "No"
    var objName = "Supplier"
    var post = {
      action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
    }
    swal({
      title: "Are your sure?", text: "You want to update this supplier?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend: function () {
              $("#btnUpdateSupplier").prop("disabled", true)
              $("#btnUpdateSupplier").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function (data) {
            $("#btnUpdateSupplier").prop("disabled", false)
            $("#btnUpdateSupplier").html("<i class='fa fa-pencil'></i> Update Supplier")
            var Message = data.Message;
            var status = data.Status;
            if (status === true) {
              swal({
                  title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function (isConfirm) {
                  if (isConfirm) { location.reload() }
              })
            } else {
              Message.forEach(function (error) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
              })
            }
          }, error: function (e) {
              bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
          },
        })
      }
    })
  })

  // Delete Suspplier Data
  $(document).on('click', '.btnDeleteSupplier', function (e) {
    e.preventDefault()
    const deleteBtnID = $(this).attr("id")
    var vl = $(this).attr("data-id")
    var tn = "R0QraDduWTRyVFp5NlNwbUxUeTFHQT09OjprE8gn+VafIdXVgnfZ1wc1"
    var cm = "TU9yelhudWZFbW12K1RZTEh5bW81dz09Ojr6lGV65L/bnddVd7xwTVbq"
    var commandType = "delete_command"
    var objName = "Supplier"
    var post = {"action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName}
    swal({
      title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled")
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
        $.ajax({
          method: "POST", url: "api/main.php", data: post, dataType: "JSON",
          success: function (data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {
                swal("", Message, "success")
                $("#" + deleteBtnID).parents("tr").remove()
            } else {
                swal("", Message, "error")
            }
          }, error: function (data) { }
        })
      }
    })
  })

  // ============================ End of Supplier Information Section ==========================================
  
  	// ============================ Start of Item Units Information Section ======================================

  	// Register New Unit
	$("#registerNewUnitForm").on("submit", function (e) {
		e.preventDefault()
		var vl = $("#txtUnitNameRegisterNewUnit").val() + "###" + $("#txtUnitRemarksRegisterNewUnit").val() + "###currentUserIdd###currentDateTime###-###-"
		var hasFile = "No"
		var tn = "Q3BNUzVtNkRCUWEybjR2aUN3MnRDdz09OjodnJxAyBtCHkBuAPVdb9N9"
		var commandType = "insert_command"
		var objName = "Unit"
		var objPre = "UT"
		var post = {action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre}
		swal ({
			title: "Are you sure?", text: "You want to register this unit?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
				$(".confirm").attr("disabled", "disabled") 
				$(".confirm").attr("style", "color: #FFF") 
				$(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
					url: "api/main.php", type: "POST", data: post, dataType: "JSON",
					beforeSend:function(){
						$("#btnRegisterNewUnit").prop('disabled', true)
						$("#btnRegisterNewUnit").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function(data) {
						$("#btnRegisterNewUnit").prop('disabled', false)
						$("#btnRegisterNewUnit").html("<i class='fa fa-lg fa-save'></i> Register Unit")
						var Message = data.Message
						var status = data.Status
						if (status == true) {		
							swal ({
								title: "", text: "Unit has been registered successfully", type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) location.reload()
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
							})
						}	
					}, error: function(e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
					}          
				})
			}
    	})
  	})

	// Filling Data into Update Unit Modal
	$(document).on("click", ".btnUpdateUnit", function (e) {
		e.preventDefault()
		var objectID = $(this).attr("data-id")
		var tn = "Q3BNUzVtNkRCUWEybjR2aUN3MnRDdz09OjodnJxAyBtCHkBuAPVdb9N9"
		var cm = "MG04Mk82WjlXYjIrUTJzQk1rL0xzQT09Ojrx9hAMce3YT7Rt9504CMMz"
		var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
		$(".modal-body").load(objectID)
		$.ajax({
			method: "POST", url: "api/main.php", data: post, dataType: "JSON",
			success: function (data) {
				var Message = data.Message
				var status = data.Status
				if (status == true) {
					var returned_info = Message.split("###")
					$("#txtUnitIdUpdateUnit").val(returned_info[1])
					$("#txtUnitNameUpdateUnit").val(returned_info[2])
					$("#txtUnitRemarksUpdateUnit").val(returned_info[3])
				}
			}, error: function (e) {
				bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
			}
		})
	})

	// Update Unit Modal
	$("#updateUnitForm").on("submit", function (e) {
		e.preventDefault()
		var vl = $("#txtUnitIdUpdateUnit").val() + "###" + $("#txtUnitNameUpdateUnit").val() + "###" + $("#txtUnitRemarksUpdateUnit").val() + "###currentUserIdd###currentDateTime"
		var tn = "Q3BNUzVtNkRCUWEybjR2aUN3MnRDdz09OjodnJxAyBtCHkBuAPVdb9N9"
		var cm = "RXdEcUdaNjZORXJRL1BxdEgxL0lGWjhneHN5ZGdGckJzWUU3RG0yRFBKOWZ6Rzh4YnExdlhSSW9aMGg1NndBUW1MdWRuVFN0SGxXY0NWUkdabHRabUE9PTo6RESUPsY/IHNzjTkjMWax0A=="
		var commandType = "update_command"
		var hasFile = "No"
		var objName = "Unit"
		var post = {
			action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
		}
		swal({
			title: "Are your sure?", text: "You want to update this unit?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function (isConfirm) {
			if (isConfirm) {
				$(".confirm").attr("disabled", "disabled") 
				$(".confirm").attr("style", "color: #FFF") 
				$(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
				$.ajax({
					url: "api/main.php", type: "POST", data: post, dataType: "JSON",
					beforeSend: function () {
						$("#btnUpdateUnit").prop("disabled", true)
						$("#btnUpdateUnit").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
					}, success: function (data) {
						$("#btnUpdateUnit").prop("disabled", false)
						$("#btnUpdateUnit").html("<i class='fa fa-pencil'></i> Update Unit")
						var Message = data.Message;
						var status = data.Status;
						if (status === true) {
							swal({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function (isConfirm) {
								if (isConfirm) { location.reload() }
							})
						} else {
							Message.forEach(function (error) {
								bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
							})
						}
					}, error: function (e) {
						bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
					}
				})
			}
		})
	})

	// Delete Unit Data
	$(document).on('click', '.btnDeleteUnit', function (e) {
		e.preventDefault()
		const deleteBtnID = $(this).attr("id")
		var vl = $(this).attr("data-id")
		var tn = "Q3BNUzVtNkRCUWEybjR2aUN3MnRDdz09OjodnJxAyBtCHkBuAPVdb9N9"
		var cm = "MG04Mk82WjlXYjIrUTJzQk1rL0xzQT09Ojrx9hAMce3YT7Rt9504CMMz"
		var commandType = "delete_command"
		var objName = "Unit"
		var post = {"action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName}
		swal({
			title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function (isConfirm) {
			if (isConfirm) {
				$(".confirm").attr("disabled", "disabled")
				$(".confirm").attr("style", "color: #FFF") 
				$(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
				$.ajax({
					method: "POST", url: "api/main.php", data: post, dataType: "JSON",
					success: function (data) {
						var Message = data.Message
						var status = data.Status
						if (status == true) {
							swal("", Message, "success")
							$("#" + deleteBtnID).parents("tr").remove()
						} else {
							swal("", Message, "error")
						}
					}, error: function (data) { }
				})
			}
		})
	})

  	// ============================ End of Unit Information Section ==========================================

  // ============================ Start of Stock Category Information Section ================================

  // Register New Stock Category
  $("#registerNewStockCategoryForm").on("submit", function (e) {
    e.preventDefault()
    var vl = $("#txtCategoryNameRegisterNewStockCategory").val() + "###" + $("#txtCategoryRemarksRegisterNewStockCategory").val() + "###currentUserIdd###currentDateTime###-###-"
    var hasFile = "No"
    var tn = "cjFQR0dwOWd1UzVjT3pLdlFlZ0diRG1TbG1JZndnc1FjUTYweDR3QmJkRT06Ojno4nogGLEYqbKZ237Ag4M="
    var commandType = "insert_command"
    var objName = "Category"
    var objPre = "CT"
    var post = {action: "ins_upd_del_everything", vl: vl, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName, objPre: objPre}
    swal ({
      title: "Are you sure?", text: "You want to register this category?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend:function(){
            $("#btnRegisterNewStockCategory").prop('disabled', true)
            $("#btnRegisterNewStockCategory").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnRegisterNewStockCategory").prop('disabled', false)
            $("#btnRegisterNewStockCategory").html("<i class='fa fa-lg fa-save'></i> Register Category")
            var Message = data.Message
            var status = data.Status
            if (status == true) {		
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) location.reload()
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })
  })

  // Filling Data into Update Stock Category Modal
  $(document).on("click", ".btnUpdateStockCategory", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    var tn = "cjFQR0dwOWd1UzVjT3pLdlFlZ0diRG1TbG1JZndnc1FjUTYweDR3QmJkRT06Ojno4nogGLEYqbKZ237Ag4M="
    var cm = "WnpvdG0rV0NnUjRPWXJrbWFzMkQ1UT09OjpEddc9dMZxEA+ZJFmAruHp"
    var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
    $(".modal-body").load(objectID)
    $.ajax({
      method: "POST", url: "api/main.php", data: post, dataType: "JSON",
      success: function (data) {
        var Message = data.Message
        var status = data.Status
        if (status == true) {
          var returned_info = Message.split("###")
          $("#txtCategoryIdUpdateStockCategory").val(returned_info[1])
          $("#txtCategoryNameUpdateStockCategory").val(returned_info[2])
          $("#txtCategoryRemarksUpdateStockCategory").val(returned_info[3])
        }
      }, error: function (e) {
        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
      }
    })
  })

  // Update Stock Category Modal
  $("#updateStockCategoryForm").on("submit", function (e) {
    e.preventDefault()
    var vl = $("#txtCategoryIdUpdateStockCategory").val() + "###" + $("#txtCategoryNameUpdateStockCategory").val() + "###" + $("#txtCategoryRemarksUpdateStockCategory").val() + "###currentUserIdd###currentDateTime"
    var tn = "cjFQR0dwOWd1UzVjT3pLdlFlZ0diRG1TbG1JZndnc1FjUTYweDR3QmJkRT06Ojno4nogGLEYqbKZ237Ag4M="
    var cm = "a3pBUnpxSWJEWTkvWk44bnlXK1duVFBTM1l6eEF0S2phbDRQNEEyMUJZVDgxcGo5eGp1RW1CbEtGZEZGYXprVlYySk05QU9hMEZ0YUJ1UktFdSt6SkR6TTBRdWdUTVFRQ1hMSnpxUldHTXc9OjqitpNPCLQW7B9dc33u0UVY"
    var commandType = "update_command"
    var hasFile = "No"
    var objName = "Category"
    var post = {
      action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
    }
    swal({
      title: "Are your sure?", text: "You want to update this category?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend: function () {
              $("#btnUpdateStockCategory").prop("disabled", true)
              $("#btnUpdateStockCategory").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function (data) {
            $("#btnUpdateStockCategory").prop("disabled", false)
            $("#btnUpdateStockCategory").html("<i class='fa fa-pencil'></i> Update Category")
            var Message = data.Message;
            var status = data.Status;
            if (status === true) {
              swal({
                  title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function (isConfirm) {
                  if (isConfirm) { location.reload() }
              })
            } else {
              Message.forEach(function (error) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
              })
            }
          }, error: function (e) {
              bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
          },
        })
      }
    })
  })

  // Delete Category Data
  $(document).on('click', '.btnDeleteStockCategory', function (e) {
    e.preventDefault()
    const deleteBtnID = $(this).attr("id")
    var vl = $(this).attr("data-id")
    var tn = "cjFQR0dwOWd1UzVjT3pLdlFlZ0diRG1TbG1JZndnc1FjUTYweDR3QmJkRT06Ojno4nogGLEYqbKZ237Ag4M="
    var cm = "WnpvdG0rV0NnUjRPWXJrbWFzMkQ1UT09OjpEddc9dMZxEA+ZJFmAruHp"
    var commandType = "delete_command"
    var objName = "Category"
    var post = {"action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName}
    swal({
      title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled")
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
        $.ajax({
          method: "POST", url: "api/main.php", data: post, dataType: "JSON",
          success: function (data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {
                swal("", Message, "success")
                $("#" + deleteBtnID).parents("tr").remove()
            } else {
                swal("", Message, "error")
            }
          }, error: function (data) { }
        })
      }
    })
  })

  // ============================ End of Stock Category Information Section ====================================

  // ============================ Start of Items Information Section ===========================================

  let count_items = 0
  // Add New Project Particle
  $(document).on("click", ".btnAddNewStockItem", function () {
      count_items++
      $(".itemsNewItemsModal").append(`<div class='row m-0 pt-2 pb-2 align-items-top' id='itemInformation${count_items}'>
        <div class='col-md-3'>
          <input class='form-control form-control-sm txtItemNameRegisterNewStockItem' type='text' name='txtItemNameRegisterNewStockItem${count_items}' id='txtItemNameRegisterNewStockItem${count_items}' placeholder='Item Name' required>
        </div>
        <div class='col-md-2'>
          <select class='form-control cmbCategoryNameRegisterNewStockItem' style='width: 100%;' name='cmbCategoryNameRegisterNewStockItem${count_items}' id='cmbCategoryNameRegisterNewStockItem${count_items}' required>

          </select>
        </div>
        <div class='col-md-2'>
          <select class='form-control cmbUnitNameRegisterNewStockItem' style='width: 100%;' name='cmbUnitNameRegisterNewStockItem${count_items}' id='cmbUnitNameRegisterNewStockItem${count_items}' required>

          </select>
        </div>
        <div class='col-md-4'>
          <textarea class='form-control form-control-sm txtItemRemarksRegisterNewStockItem' style='resize:none' rows='2' name='txtItemRemarksRegisterNewStockItem${count_items}' id='txtItemRemarksRegisterNewStockItem${count_items}' placeholder='Remarks' required></textarea>
        </div>
        <div class='col-md-1 text-center'>
          <i class='fa fa-trash fa-2x text-danger btnRemoveStockItem' style='cursor: pointer;'></i>
        </div>	  
      </div>`)

      $.ajax({    
        method: "POST", url : "api/main.php", data: {"action" : "fill_stock_categories"}, dataType: "JSON",
        success: function(data) {
          var Message = data.Message, status = data.Status, html = ''
          if (status == true) {
            html += `<option value="">Select Category</option>`
            Message.forEach(function(returned_data, i) {
              html += `<option value="${returned_data['categoryID']}">${returned_data['categoryName']}</option>`
              })
            $("#cmbCategoryNameRegisterNewStockItem" + count_items).html(html)
            $("#cmbCategoryNameRegisterNewStockItem" + count_items).select2({ tags: false, dropdownParent: $("#registerStockItemsModal") })
          }
        },error : function(data){ }
      })

      // Fill units of items
      $.ajax({    
        method: "POST", url : "api/main.php", data: {"action" : "fill_item_units"}, dataType: "JSON",
        success: function(data) {
          var Message = data.Message, status = data.Status, html = ''
          if (status == true) {
            html += `<option value="">Select Unit</option>`
            Message.forEach(function(returned_data, i) {
              html += `<option value="${returned_data['unitID']}">${returned_data['unitName']}</option>`
              })
            $("#cmbUnitNameRegisterNewStockItem" + count_items).html(html)
            $("#cmbUnitNameRegisterNewStockItem" + count_items).select2({ tags: false, dropdownParent: $("#registerStockItemsModal") })
          }
        },error : function(data){ }
      })

      $("#txtItemNameRegisterNewStockItem" + count_items).focus()
  })
  
  // Remove Item
  $(document).on("click", ".btnRemoveStockItem", function () {
    $(this).parent().parent().remove()
    count_items--
  })
  
  // Register Items
  $(document).on("submit", "#registerNewStockItemsForm", function (e) {
    e.preventDefault()
    let stock_items_list = []
    $('[id^="itemInformation"]').each(function() {
      stock_items_list.push([$(this).find(".txtItemNameRegisterNewStockItem").val(), $(this).find(".cmbCategoryNameRegisterNewStockItem").val(), $(this).find(".cmbUnitNameRegisterNewStockItem").val(), $(this).find(".txtItemRemarksRegisterNewStockItem").val()])
    })
    // console.log(stock_items_list)

    const post_data = {
      "action": "register_stock_items",
      "stock_items_list": stock_items_list,
    }
    swal ({
      title: "Are you sure?", text: "You want to register these items?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post_data, dataType: "JSON",
          beforeSend:function(){
            $("#btnRegisterNewStockItems").prop('disabled', true)
            $("#btnRegisterNewStockItems").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnRegisterNewStockItems").prop('disabled', false)
            $("#btnRegisterNewStockItems").html("<i class='fa fa-lg fa-save'></i> Register Particle")
            var Message = data.Message
            var status = data.Status
            if (status == true) {	
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) { location.reload() }
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })

  })

  // Filling Data into Update Stock Item Modal
  $(document).on("click", ".btnUpdateStockItem", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    var tn = "K0NQcnpGdTlaT3lzUGJwZ0IzNEV2UT09OjrZl/fzZqm0d5nwg790ma5R"
    var cm = "VHZXbmFWamFOcm9jRzJjUTdUU0hhQT09Ojq5Id8l3Vl9HLn5VEcVbZkZ"
    var post = { "action": "fetch_parameterized_everything", "dn": dn, "tn": tn, "cm": cm, "objectID": objectID }
    $(".modal-body").load(objectID)
    $.ajax({
      method: "POST", url: "api/main.php", data: post, dataType: "JSON",
      success: function (data) {
        var Message = data.Message
        var status = data.Status
        if (status == true) {
          var returned_info = Message.split("###")
          $("#txtItemIdUpdateStockItem").val(returned_info[1])
          $("#txtItemNameUpdateStockItem").val(returned_info[2])
          $("#cmbCategoryNameUpdateStockItem").select2().val(returned_info[3]).trigger('change')
          $("#cmbUnitNameUpdateStockItem").select2().val(returned_info[4]).trigger('change')
          $("#txtItemRemarksUpdateStockItem").val(returned_info[5])
        }
      }, error: function (e) {
        bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
      }
    })
  })
  
  // Update Stock Item Modal
  $("#updateStockItemForm").on("submit", function (e) {
    e.preventDefault()
    var vl = $("#txtItemIdUpdateStockItem").val() + "###" + $("#txtItemNameUpdateStockItem").val() + "###" + $("#cmbCategoryNameUpdateStockItem").val() + "###" + $("#cmbUnitNameUpdateStockItem").val() + "###" + $("#txtItemRemarksUpdateStockItem").val() + "###currentUserIdd###currentDateTime"
    var tn = "K0NQcnpGdTlaT3lzUGJwZ0IzNEV2UT09OjrZl/fzZqm0d5nwg790ma5R"
    var cm = "VUc4dFR4Z3N2UFM1cVhWdzFoblFiYjVLZ2RSVW9ad3VZVVdCYU5DMm9zUXNXMThZWC9aK29oVkZkR3gwaEd5ZUF5ZURDQTVEOVRJRjJXTHdHYjJubml1aG9xZ0ZwQTdhQ25jaERuMU9NT0U9OjrCfTFznLD5zgxBubVdQYJY"
    var commandType = "update_command"
    var hasFile = "No"
    var objName = "Item"
    var post = {
      action: "ins_upd_del_everything", vl: vl, cm: cm, hasFile: hasFile, commandType: commandType, tn: tn, objName: objName
    }
    swal({
      title: "Are your sure?", text: "You want to update this item?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post, dataType: "JSON",
          beforeSend: function () {
              $("#btnUpdateStockItem").prop("disabled", true)
              $("#btnUpdateStockItem").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function (data) {
            $("#btnUpdateStockItem").prop("disabled", false)
            $("#btnUpdateStockItem").html("<i class='fa fa-pencil'></i> Update Item")
            var Message = data.Message;
            var status = data.Status;
            if (status === true) {
              swal({
                  title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function (isConfirm) {
                  if (isConfirm) { location.reload() }
              })
            } else {
              Message.forEach(function (error) {
                  bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, { type: "danger", position: "topright", appendType: "append"})
              })
            }
          }, error: function (e) {
              bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, { type: "danger", position: "topright", appendType: "append"})
          },
        })
      }
    })
  })

  // Delete Stock Item Data
  $(document).on('click', '.btnDeleteStockItem', function (e) {
    e.preventDefault()
    const deleteBtnID = $(this).attr("id")
    var vl = $(this).attr("data-id")
    var tn = "K0NQcnpGdTlaT3lzUGJwZ0IzNEV2UT09OjrZl/fzZqm0d5nwg790ma5R"
    var cm = "VHZXbmFWamFOcm9jRzJjUTdUU0hhQT09Ojq5Id8l3Vl9HLn5VEcVbZkZ"
    var commandType = "delete_command"
    var objName = "Item"
    var post = {"action": "ins_upd_del_everything", "vl": vl, "tn": tn, "cm": cm, "commandType": commandType, "objName": objName}
    swal({
      title: "Are your sure?", text: "You want to delete this permenantly?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function (isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled")
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
        $.ajax({
          method: "POST", url: "api/main.php", data: post, dataType: "JSON",
          success: function (data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {
                swal("", Message, "success")
                $("#" + deleteBtnID).parents("tr").remove()
            } else {
                swal("", Message, "error")
            }
          }, error: function (data) { }
        })
      }
    })
  })

  // ============================ End of Items Information Section =============================================

  // ============================ Start of Create New Request For Quotation Section ============================

  // Add Item to Request For Quotation
  $(document).on("change", "#cmbAddItemIdNewRequestForQuotation", function () {
    // var selected_item_id = $(this).find('option:selected');
    var selected_item_id = $(this).val()
    if (selected_item_id === "") {
      // Do nothing
    } else {
      // $("#registerProjectitemsModal").prop("style", "overflow-y: auto")
      var selected_item_name = $(this).select2().find(":selected").data("name")
      var selected_item_category = $(this).select2().find(":selected").data("category")
      var selected_item_unit = $(this).select2().find(":selected").data("unit")

     if ($("#requesteditemId" + selected_item_id).length == 0) {
        $(".newRequestForQuotationItemsList").closest('div').append(`<div class='row no-gutters align-items-center font-weight-normal p-1 border-bottom border-light' style='margin: 0px;' id='requesteditemId${selected_item_id}' requested-item-id='${selected_item_id}'>\
            <div class='col-md-1 text-center'><i class='fa fa-trash fa-lg text-danger removeRequestedItem' style='cursor: pointer;'></i></div>\
            <div class='col-md-5 p1-1 pr-1'><input type='text' class='form-control form-control-sm' value='${selected_item_name}' readonly /></div>\
            <div class='col-md-3 pl-1 pr-1'><input type='text' class='form-control form-control-sm' value='${selected_item_category}' readonly /></div>\
            <div class='col-md-2 pl-1 pr-1'><input type='text' class='form-control form-control-sm text-center' value='${selected_item_unit}' readonly /></div>\
            <div class='col-md-1 pl-2 pr-1'><input type='number' class='form-control form-control-sm text-center requesteditemQuantity' name='requesteditemQuantity${selected_item_id}' id='requesteditemQuantity${selected_item_id}'/></div>\
        </div>`)
        $("#requesteditemQuantity" + selected_item_id).focus()
      } else {
        $("#requesteditemQuantity" + selected_item_id).focus()  
      }
    }
    
  })

  // Remove Requested Items
  $(document).on("click", ".removeRequestedItem", function () {
    $(this).parent().parent().remove()
  })

  // Register New Request For Quotation
  $("#registerNewRFQForm").on("submit", function (e) {
    e.preventDefault()
    let requested_items_list = []
    let rfq_description = $("#txtRFQDescriptionNewRFQ").val()
    let rfq_condition = $("#txtRFQConditionNewRFQ").val()
    let rfq_created_date = $("#txtRFQCreatedDateNewRFQ").val()
    let rfq_closing_date = $("#txtRFQClosingDateNewRFQ").val()
    $('[id^="requesteditemId"]').each(function() {
      requested_items_list.push([$(this).attr("requested-item-id"), $(this).find(".requesteditemQuantity").val()])
    })
    let checked_requested_items_list = requested_items_list.length === 0 ? {"itemStatus": "false", "itemMessage": "Please Select Item"} : {"itemStatus": "true", "itemMessage": requested_items_list}

    const post_data = {
      "action": "register_new_request_for_quotation",
      "rfq_description": rfq_description,
      "rfq_condition": rfq_condition,
      "rfq_created_date": rfq_created_date,
      "rfq_closing_date": rfq_closing_date,
      "checked_requested_items_list": checked_requested_items_list,
    }
    swal ({
      title: "Are you sure?", text: "You want to register this request for quotation?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data: post_data, dataType: "JSON",
          beforeSend:function(){
            $("#btnRegisterNewRFQ").prop('disabled', true)
            $("#btnRegisterNewRFQ").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnRegisterNewRFQ").prop('disabled', false)
            $("#btnRegisterNewRFQ").html("<i class='fa fa-lg fa-send'></i> Send Request")
            var Message = data.Message
            var status = data.Status
            if (status == true) {
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) { location.reload() }
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })

  })

  
  // Accept RFQ
  $(document).on("click", ".btnAcceptRFQ", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    // var rfq_quotation_accept_purpose = ""
    swal ({
      title: "Are you sure?", text: "You want to accept this RFQ?", type: "input", animation: "slide-from-top", inputPlaceholder: "Write accept reason...", showCancelButton: true, cancelButtonText: "Cancel", confirmButtonText: "Accept", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
        var approve_post = { "action": "accept_request_for_quotation", "selected_rfq_id": objectID, "rfq_accept_purpose": isConfirm}
        $.ajax({
          url: "api/main.php", type: "POST", data: approve_post, dataType: "JSON",
          beforeSend:function(){
          }, success: function(data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {		
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) location.reload()
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })
  })

  // Reject RFQ
  $(document).on("click", ".btnRejectRFQ", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    // var rfq_quotation_accept_purpose = ""
    swal ({
      title: "Are you sure?", text: "You want to reject this RFQ?", type: "input", animation: "slide-from-top", inputPlaceholder: "Write rejection reason...", showCancelButton: true, cancelButtonText: "Cancel", confirmButtonText: "Reject", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
        var approve_post = { "action": "reject_request_for_quotation", "selected_rfq_id": objectID, "rfq_reject_purpose": isConfirm}
        $.ajax({
          url: "api/main.php", type: "POST", data: approve_post, dataType: "JSON",
          beforeSend:function(){
          }, success: function(data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {		
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) location.reload()
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })
  })

  // ============================ End of Create New Request For Quotation Section ==============================
  
  // ============================ Start of View and Print Individual RFQ Section =============================
  
  // View and Print Individual RFQ
	$(document).on("click", ".btnViewIndividualRFQ", function (e) {
		e.preventDefault()
		var selected_rfq_id = $(this).attr("data-id")
	    $(".modal-body").load(selected_rfq_id)
		var post = {"action": "view_and_print_individual_rfq",	"selected_rfq_id" : selected_rfq_id}
		$.ajax({
			type: "POST", url: "api/main.php", data: post, dataType: "text",
			success: function (response) {
				$("#printIndividualRFQArea").html(response)
			}
		})
	})

  $(document).on('click', '#printIndividualRFQ', function () {
    //Display and open the print dialog box to print the report
    var report_restore_page = document.body.innerHTML
    var report_print_area = document.getElementById("individualRFQPrintArea").innerHTML
    document.body.innerHTML = report_print_area
    window.print()
    document.body.innerHTML = report_restore_page
  })

  // ============================ End of View and Print Individual RFQ Section =================================

  // ============================ Start of Add New Quotation For RFQ Information Section =======================

  // Fetch RFQ Items when an RFQ is selected
  $(document).on('click', '.btnAddNewRFQQuotation', function (e) {
	  e.preventDefault()
		var selected_rfq_id = $(this).attr("data-id")
    $(".modal-body").load(selected_rfq_id)
    var post_data = {"action": "fetch_rfq_items_list", "selected_rfq_id" : selected_rfq_id}
		$.ajax({
			type: "POST", url: "api/main.php", data: post_data, dataType: "text",
			success: function (response) {
				$("#fetchRequestForQuotationItemsSection").html(response)
			}
		})
	})

  // Enter Item Price then Calculate
  $(document).on("keyup keypress blur change focusout", ".rfqQuotationItemUnitPrice", function () {
    let selected_item_quantity = (parseInt($(this).parent().parent().find(".rfqQuotationItemQuantity").val()) || 0)
    let selected_item_price = parseFloat($(this).val()) || 0
    $(this).parent().parent().find(".rfqQuotationItemTotalPrice").val((parseFloat(selected_item_quantity * selected_item_price) || 0).toFixed(2))

    // Update the quotation sub total label
    var getAllQuotationTotalPriceElements = document.getElementsByClassName("rfqQuotationItemTotalPrice")
    var quotation_subtotal_new_quotation = 0.00;
    for(var i = 0; i < getAllQuotationTotalPriceElements.length; i++) {
      quotation_subtotal_new_quotation += parseFloat(getAllQuotationTotalPriceElements[i].value) || 0
    }
		$("#quotationSubtotalNewRFQQuotation").text(parseFloat(quotation_subtotal_new_quotation).toFixed(2))
    let quotation_total_new_quotation = (quotation_subtotal_new_quotation - (parseFloat($("#txtQoatationDiscountNewRFQQuotation").val()) || 0)).toFixed(2)
    $("#quotationTotalNewRFQQuotation").text(quotation_total_new_quotation)   

  })

  // Discount Entry New Quotation
  $(document).on("keyup keypress blur change focusout", "#txtQoatationDiscountNewRFQQuotation", function(e){
    let quotation_subtotal_new_quotation = parseFloat($("#quotationSubtotalNewRFQQuotation").text()) || 0
    let quotation_discount_new_quotation = parseFloat($(this).val()) || 0
    let quotation_total_new_quotation = quotation_subtotal_new_quotation - quotation_discount_new_quotation
    if (quotation_discount_new_quotation >= quotation_subtotal_new_quotation) {
      bs4pop.notice("<h6 class='pt-2'><i class='fa fa-exclamation-circle fa-lg pr-2'></i>" + " Check Discount Amount</h6>", { type: "warning", position: "topright", appendType: "append"})
    } else {
      $("#quotationTotalNewRFQQuotation").text((quotation_total_new_quotation).toFixed(2) || 0)       
    }
  })

  // Register New RFQ Quotation
  $(document).on("submit", "#addNewRFQQuotationForm", function (e) {
    e.preventDefault()

    var formData = new FormData(this);

    let rfq_quotation_items_list = []
    let selected_supplier_id = $("#cmbSupplierIdNewRFQQuotation").val()
    let quotation_date = $("#txtQuotationDateNewRFQQuotation").val()
    let selected_rfq_id = $("#txtRFQIDNewRFQQuotation").val()
    $('[id^="rfqQuotationItemId"]').each(function() {
      rfq_quotation_items_list.push([$(this).attr("rfq-quotation-item-id"), $(this).find(".rfqQuotationItemQuantity").val(), $(this).find(".rfqQuotationItemUnitPrice").val(), $(this).find(".rfqQuotationItemTotalPrice").val()])
    })
    let quotation_remarks = $("#txtQuotationRemarksNewRFQQuotation").val() == "" ? "-" : $("#txtQuotationRemarksNewRFQQuotation").val()
    console.log(rfq_quotation_items_list)
    let quotation_subtotal_amount = (parseFloat($("#quotationSubtotalNewRFQQuotation").text()) || 0).toFixed(2)
    let quotation_discount_amount = $("#txtQoatationDiscountNewRFQQuotation").val() === "" ? 0.00 : (parseFloat($("#txtQoatationDiscountNewRFQQuotation").val()) || 0).toFixed(2)
    let quotation_total_amount = (parseFloat($("#quotationTotalNewRFQQuotation").text()) || 0).toFixed(2)

    let checked_rfq_quotation_items_list = rfq_quotation_items_list.length === 0 ? {"itemStatus": "false", "itemMessage": "Please Select Item"} : {"itemStatus": "true", "itemMessage": rfq_quotation_items_list}

    formData.append("action", "register_new_rfq_quotation")
    formData.append("selected_supplier_id", selected_supplier_id)
    formData.append("quotation_date", quotation_date)
    formData.append("selected_rfq_id", selected_rfq_id)
    formData.append("checked_rfq_quotation_items_list", JSON.stringify(checked_rfq_quotation_items_list))
    formData.append("quotation_subtotal_amount", quotation_subtotal_amount)
    formData.append("quotation_discount_amount", quotation_discount_amount)
    formData.append("quotation_total_amount", quotation_total_amount)
    formData.append("quotation_remarks", quotation_remarks)
    formData.append("quotation_document", $("#txtQuotationDocumentNewRFQQuotation")[0].files[0])

    swal ({
      title: "Are you sure?", text: "You want to register this quotation?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({
          url: "api/main.php", type: "POST", data:  formData, contentType: false, cache: false, processData:false,
          beforeSend:function(){
            $("#btnRegisterNewRFQQuotation").prop('disabled', true)
            $("#btnRegisterNewRFQQuotation").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          }, success: function(data) {
            $("#btnRegisterNewRFQQuotation").prop('disabled', false)
            $("#btnRegisterNewRFQQuotation").html("<i class='fa fa-lg fa-save'></i> Register Quotation")
            var Message = data.Message
            var status = data.Status
            if (status == true) {
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) { location.reload() }
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })

  })

  // Approve RFQ Quotation
  $(document).on("click", ".btnApproveRFQQuotation", function (e) {
    e.preventDefault()
    var objectID = $(this).attr("data-id")
    var selected_rfq_id = $(this).attr("rfq-id")
    // var rfq_quotation_accept_purpose = ""
    swal ({
      title: "Are you sure?", text: "You want to approve this quotation?", type: "input", animation: "slide-from-top", inputPlaceholder: "Write approve reason...", showCancelButton: true, cancelButtonText: "Cancel", confirmButtonText: "Approve", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
        var approve_post = { "action": "approve_rfq_quotation", "selected_rfq_quotation_id": objectID, "selected_rfq_id": selected_rfq_id, "rfq_quotation_approve_purpose": isConfirm}
        $.ajax({
          url: "api/main.php", type: "POST", data: approve_post, dataType: "JSON",
          beforeSend:function(){
          }, success: function(data) {
            var Message = data.Message
            var status = data.Status
            if (status == true) {		
              swal ({
                title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) location.reload()
              })
            } else {
              Message.forEach(function (error) {
                bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + error, {type: "danger", position: "topright", appendType: "append"})
              })
            }	
          }, error: function(e) {
            bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
          }          
        })
      }
    })
  })

  // ============================ End of Add New Quotation For RFQ Information Section =========================

  // ============================ Start of Purchase order Information Section ==================================

  // Get the invoices associated with the selected supplier
	$("#cmbSupplierIdNewPurchaseOrder").on("change", function () {
		var selected_supplier_id = $(this).val()
		if (selected_supplier_id == "") {
			$("#cmbChooseInvoiceNewPurchaseOrder").empty().append("<option value=''>Choose Invoice</option>")
			$("#txtDeptAmountNewPurchaseOrder").val("")
			$("#txtPaidAmountNewPurchaseOrder").val("")
			$("#txtRemainingBalanceNewPurchaseOrder").val("")
		} else {
			var post = { "action": "fetch_supplier_invoices", "selected_supplier_id": selected_supplier_id }
			$.ajax({
				method: "POST", url: "api/main.php", data:  post, dataType: "JSON",
				success: function(data) {
					var Message = data.Message
					var status = data.Status
					var chargeStatus
					var html = ''
					if(status == true){
						html += `<option value="">Choose Invoice</option>`

						Message.forEach(function(returned_data, i){
							if (parseFloat(returned_data['Remaining']) == parseFloat(returned_data['TotalDept'])) {
								chargeStatus = "Not Paid"
							} else if (parseFloat(returned_data['Remaining']) < parseFloat(returned_data['TotalDept'])) {
								chargeStatus = "Partial Paid"
							}
							html += `<option value="${returned_data['invoiceID']}">${returned_data['invoiceID']} ${returned_data['invoiceMonth']} - $${returned_data['Remaining']} - ${chargeStatus}</option>`
						})
						$("#cmbChooseInvoiceNewPurchaseOrder").html(html);
					} else {
						$("#cmbChooseInvoiceNewPurchaseOrder").empty().append("<option value=''>Choose Invoice</option>")
					}
					$("#txtDeptAmountNewPurchaseOrder").val("")
          $("#txtPaidAmountNewPurchaseOrder").val("")
          $("#txtRemainingBalanceNewPurchaseOrder").val("")
					$("#txtInvoiceStatusNewPurchaseOrder").val("")

				}, error: function(e) {
					bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
				}          
			})
		}
	})

  // Calculate invoice balance when invoice is selected in purchase order
	$("#cmbChooseInvoiceNewPurchaseOrder").on("change", function (e) {
		e.preventDefault()
		var selected_invoice_id = $(this).val()
		if (selected_invoice_id == "") {
			$("#txtDeptAmountNewPurchaseOrder").val("")
		} else {
			var post = {"action": "calculate_supplier_invoices_balance", "selected_invoice_id": selected_invoice_id }

			$.ajax({
				method: "POST", url: "api/main.php", data:  post, dataType: "JSON",
				success: function(data) {
					var Message = data.Message
					var status = data.Status
					if (status == true){
            var returned_data = Message.split("###")
						$("#txtDeptAmountNewPurchaseOrder").val(parseFloat(returned_data[1]))
						$("#txtPaidAmountNewPurchaseOrder").prop("max", parseFloat(returned_data[1]))
					}
					$("#txtPaidAmountNewPurchaseOrder").val("")
					$("#txtRemainingBalanceNewPurchaseOrder").val("")
					$("#txtInvoiceStatusNewPurchaseOrder").val("")

				}, error: function(e) {
					bs4pop.notice("<i class='fa fa-times-circle'></i> &nbsp;" + e, {type: "danger", position: "topright", appendType: "append"})
				}          
			});
			
		}
	});

  $(document).on("keyup keypress blur change focusout", "#txtPaidAmountNewPurchaseOrder", function () {
		var totalDeptAmount = parseFloat($("#txtDeptAmountNewPurchaseOrder").val())
		var paidAmount = parseFloat($(this).val()) || 0
		var totalRemaining = Math.round((totalDeptAmount - paidAmount) * 100) / 100
		
		if (totalDeptAmount === "" || paidAmount === "") {
			$("#txtRemainingBalanceNewPurchaseOrder").val("")
		} else if (totalRemaining == totalDeptAmount){
			$("#txtRemainingBalanceNewPurchaseOrder").val(totalRemaining)
			$("#txtInvoiceStatusNewPurchaseOrder").val("Not Paid")
		} else if (totalRemaining > 0){
			$("#txtRemainingBalanceNewPurchaseOrder").val(totalRemaining)
			$("#txtInvoiceStatusNewPurchaseOrder").val("Partial Paid")
		} else if (totalRemaining <= 0){
			$("#txtRemainingBalanceNewPurchaseOrder").val(totalRemaining)
			$("#txtInvoiceStatusNewPurchaseOrder").val("Full Paid")
		}
	})

    // Register New Purchase Order
	$("#registerPurchaseOrderForm").submit(function (e) {
		e.preventDefault();
		var selected_supplier_id = $("#cmbSupplierIdNewPurchaseOrder").val()
		var selected_invoice_id = $("#cmbChooseInvoiceNewPurchaseOrder").val()
		var total_paid_amount = $("#txtPaidAmountNewPurchaseOrder").val()
		var deposit_account = $("#cmbDepositAccountNewPurchaseOrder").val()
		var payment_remarks = $("#txtPaymentDescriptionNewPurchaseOrder").val()
		var post = {
			"action": "register_new_purchase_order", "selected_supplier_id": selected_supplier_id, "selected_invoice_id": selected_invoice_id,
			"total_paid_amount": total_paid_amount, "deposit_account": deposit_account, "payment_remarks": payment_remarks
		}
		swal ({
			title: "Are you sure?", text: "You want to register this order?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
		}, function(isConfirm) {
			if (isConfirm) {
			    $(".confirm").attr("disabled", "disabled") 
			    $(".confirm").attr("style", "color: #FFF") 
			    $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
			    $.ajax({
					url : "api/main.php", method: "POST", data:  post, dataType: "JSON",
					beforeSend:function(){
						$("#btnRegisterPurchaseOrder").prop('disabled', true)
						$("#btnRegisterPurchaseOrder").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait")
					},
					success : function(data) {
						var Message = data.Message
						var status = data.Status
						if (status == true) {
							swal ({
								title: "", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
							}, function(isConfirm) {
								if (isConfirm) { location.reload() }
							});
						} else {
							swal("", Message, "error")
						}				
					},
					error : function(data){ }
				})
			}
		})

	})

  // ============================ End of Purchase order Information Section ====================================

  // ============================ END OF STOCK MANEGEMENT MODULE SCRIPTS =======================================

  // ============================ START OF WAITER CHANGE PASSWORD SECTION MODULE SCRIPTS =======================
	
  $(document).on("focusout", "#txtConfirmPasswordWaiterChangePassword", function () {
    var waiter_new_password = $("#txtNewPasswordWaiterChangePassword").val()
    if ($(this).val() != waiter_new_password) {
      bs4pop.notice("<i class='fa fa-exclamation-triangle text-danger'></i> &nbsp; Password and confirm password must match each other, please check!", {type: "warning", position: "topright", appendType: "append"})
      $("#btnChangeWaiterPassword").prop("disabled", true)
    } else {
      $("#btnChangeWaiterPassword").prop("disabled", false)
    }
  })

	$(document).on("keyup", "#txtConfirmPasswordWaiterChangePassword", function () {
		var waiter_new_password = $("#txtNewPasswordWaiterChangePassword").val()
		if ($(this).val() == waiter_new_password) { $("#btnChangeWaiterPassword").prop("disabled", false) } else { $("#btnChangeWaiterPassword").prop("disabled", true) }
	})
	
	$("#waiterChangePasswordForm").submit(function (e) {
		e.preventDefault()
		var waiter_old_password = $("#txtCurrentPasswordWaiterChangePassword").val()
		var waiter_new_password = $("#txtNewPasswordWaiterChangePassword").val()
		var waiter_confirm_password = $("#txtConfirmPasswordWaiterChangePassword").val()
    var post = {"action" : "change_waiter_password", "waiter_old_password" : waiter_old_password, "waiter_new_password" : waiter_new_password, "waiter_confirm_password" : waiter_confirm_password}
    swal ({
      title: "Are you sure?", text: "You want to change your password?", type: "", showCancelButton: true, confirmButtonText: "Yes", cancelButtonText: "No", closeOnConfirm: false, closeOnCancel: true
    }, function(isConfirm) {
      if (isConfirm) {
        $(".confirm").attr("disabled", "disabled") 
        $(".confirm").attr("style", "color: #FFF") 
        $(".confirm").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please wait") 
        $.ajax({    
          method: "POST", url : "api/main.php", data: post, dataType: "JSON",
          beforeSend:function(){
            $("#btnChangeWaiterPassword").prop('disabled', true)
            $("#btnChangeWaiterPassword").html("<i class='fa fa-lg fa-spinner fa-pulse'></i> Please Wait")
          },
          success : function(data){
            $("#btnChangeWaiterPassword").prop('disabled', false)
            $("#btnChangeWaiterPassword").html("<i class='fa fa-fw fa-lg fa-refresh'></i>Change Password")
            var Message = data.Message;
            var status = data.Status;
            if (status == true) {
              swal ({
                title: "Success", text: Message, type: "success", showCancelButton: false, closeOnConfirm: false, closeOnCancel: false
              }, function(isConfirm) {
                if (isConfirm) { location.reload() }
              })
            } else {swal("", Message, "error")}
          },
          error: function(data){ }
        })
      }
    })
	})
	
  // ============================ END OF WAITER CHANGE PASSWORD SECTION MODULE SCRIPTS =========================

  // ============================ START OF SYSTEM REPORTS SECTION MODULE SCRIPTS ===============================

  // ============================ Start of Orders Report Section ===============================================

  $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("readonly", true)

  // Fill Report Parameter Type when Report Type is selected
	$("#cmbReportTypeSearchOrderReportTypes").on("change", function (e) {
		e.preventDefault()
		var selected_report_type = $(this).val()
		if (selected_report_type == "generalReport") $(".lblOrderTypeText").text("General Report")
    else if (selected_report_type == "orderType") $(".lblOrderTypeText").text("Order Type")
		else if (selected_report_type == "categoryID") $(".lblOrderTypeText").text("Category Name")
		else if (selected_report_type == "productID") $(".lblOrderTypeText").text("Product Name")
		else if (selected_report_type == "servedBy") $(".lblOrderTypeText").text("Served Waiter")
		else if (selected_report_type == "registeredBy") $(".lblOrderTypeText").text("Orderer User")
		
    let post_data = {"action": "fill_order_report_parameter_type", "selected_report_type": selected_report_type}
    $.ajax({
      method: "POST", url: "api/main.php", data: post_data, dataType: "JSON",
      success: function (data) {
        var Message = data.Message
        var status = data.Status
        var html = ""
        if (status == true) {
          html += `<option value="">General (All)</option>`
          Message.forEach(function (returned_data) {
            html += `<option value="${returned_data[0]}">${returned_data[1]}</option>`
          })
          $("#cmbReportTypeParameterSearchOrderReportTypes").html(html)
        }
      }, error: function (data) { },
    })
	})

    
  $("#cmbCustomDateSearchOrderReportTypes").on("change", function () {
    if ($(this).val() == 1) {
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("readonly", true)
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").val(todays_date)
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("max", todays_date)
    } else if ($(this).val() == 2) {
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("readonly", true)
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").val(yesterday_date)
    } else if ($(this).val() == 3) {
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("readonly", true)
      $("#txtFromDateSearchOrderReportTypes").val(last3days_date)
      $("#txtToDateSearchOrderReportTypes").val(todays_date)
    } else if ($(this).val() == 4) {
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("readonly", true)
      $("#txtFromDateSearchOrderReportTypes").val(lastSaturday_date)
      $("#txtToDateSearchOrderReportTypes").val(todays_date)
    } else if ($(this).val() == 5) {
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("readonly", true)
      $("#txtFromDateSearchOrderReportTypes").val(last7days_date)
      $("#txtToDateSearchOrderReportTypes").val(todays_date)
    } else if ($(this).val() == 6) {
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("readonly", true)
      $("#txtFromDateSearchOrderReportTypes").val(last10days_date)
      $("#txtToDateSearchOrderReportTypes").val(todays_date)
    } else if ($(this).val() == 7) {
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("readonly", true)
      $("#txtFromDateSearchOrderReportTypes").val(thisMonth_start)
      $("#txtToDateSearchOrderReportTypes").val(todays_date)
    } else if ($(this).val() == 8) {
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("readonly", true)
      $("#txtFromDateSearchOrderReportTypes").val(lastMonth_start)
      $("#txtToDateSearchOrderReportTypes").val(lastMonth_end)
    } else if ($(this).val() == 9) {
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("readonly", true)
      $("#txtFromDateSearchOrderReportTypes").val(thisYear_start)
      $("#txtToDateSearchOrderReportTypes").val(todays_date)
    } else if ($(this).val() == 10) {
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("readonly", true)
      $("#txtFromDateSearchOrderReportTypes").val(lastYear_start)
      $("#txtToDateSearchOrderReportTypes").val(lastYear_end)
    } else {
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("readonly", false)
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").val(todays_date)
      $("#txtFromDateSearchOrderReportTypes, #txtToDateSearchOrderReportTypes").prop("max", todays_date)
    }
  })
      
  $("#searchRentedPropertiesReportForm").on('submit', function (e) {
    e.preventDefault()
    var selected_property_type = $("#cmbPropertyTypeSearchRentedPropertiesReport").val()
    var selected_date_type = $("#cmbCustomDateSearchOrderReportTypes").val() + " 00:00:00"
    var selected_start_date = $("#txtFromDateSearchOrderReportTypes").val() + " 23:59:59"
    var selected_end_date = $("#txtToDateSearchOrderReportTypes").val()
    var post = {
      "action": "restaurant_orders_report", 
      "selected_property_type" : selected_property_type, 
      "selected_date_type" : selected_date_type, 
      "selected_start_date" : selected_start_date, 
      "selected_end_date" : selected_end_date
    }
    
    $.ajax({
      type: "POST", url: "api/main.php", data: post, dataType: "text",
      beforeSend:function(){
        $("#btnSearchRentedPropertiesReport").prop('disabled', true)
        $("#btnSearchRentedPropertiesReport").html("<i class='fa fa-spinner fa-pulse' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i>")
      },
      success: function (response) {
        $("#btnSearchRentedPropertiesReport").prop('disabled', false)
        $("#btnSearchRentedPropertiesReport").html("<i class='fa fa-search' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i>")
        $("#rentedPropertiesReportSection").html(response)
      }
    })
  })
        
  $(document).on('click', '#printRentedPropertiesReport', function () {
    //Display and open the print dialog box to print the report
    var report_restore_page = document.body.innerHTML
    var report_print_area = document.getElementById("rentedPropertiesReportPrintArea").innerHTML
    document.body.innerHTML = report_print_area
    window.print()
    document.body.innerHTML = report_restore_page
  })

    // ============================ End of Orders Report Section =================================================
  
    // ============================ Start of General Report Section ==============================================

    $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", true)
    
    $("#cmbCustomDateSearchGeneralReport").on("change", function () {
        if ($(this).val() == 0) {
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", true)
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").val("")
        } else if ($(this).val() == 1) {
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", true)
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").val(todays_date)
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("max", todays_date)
        } else if ($(this).val() == 2) {
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", true)
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").val(yesterday_date)
        } else if ($(this).val() == 3) {
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", true)
            $("#txtFromDateSearchGeneralReport").val(last3days_date)
            $("#txtToDateSearchGeneralReport").val(todays_date)
        } else if ($(this).val() == 4) {
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", true)
            $("#txtFromDateSearchGeneralReport").val(lastSaturday_date)
            $("#txtToDateSearchGeneralReport").val(todays_date)
        } else if ($(this).val() == 5) {
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", true)
            $("#txtFromDateSearchGeneralReport").val(last7days_date)
            $("#txtToDateSearchGeneralReport").val(todays_date)
        } else if ($(this).val() == 6) {
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", true)
            $("#txtFromDateSearchGeneralReport").val(last10days_date)
            $("#txtToDateSearchGeneralReport").val(todays_date)
        } else if ($(this).val() == 7) {
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", true)
            $("#txtFromDateSearchGeneralReport").val(thisMonth_start)
            $("#txtToDateSearchGeneralReport").val(todays_date)
        } else if ($(this).val() == 8) {
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", true)
            $("#txtFromDateSearchGeneralReport").val(lastMonth_start)
            $("#txtToDateSearchGeneralReport").val(lastMonth_end)
        } else if ($(this).val() == 9) {
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", true)
            $("#txtFromDateSearchGeneralReport").val(thisYear_start)
            $("#txtToDateSearchGeneralReport").val(todays_date)
        } else if ($(this).val() == 10) {
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", true)
            $("#txtFromDateSearchGeneralReport").val(lastYear_start)
            $("#txtToDateSearchGeneralReport").val(lastYear_end)
        } else {
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("readonly", false)
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").val(todays_date)
            $("#txtFromDateSearchGeneralReport, #txtToDateSearchGeneralReport").prop("max", todays_date)
        }
    })
      
    $("#searchGeneralReportForm").on('submit', function (e) {
        e.preventDefault()
        var selected_date_type = $("#cmbCustomDateSearchGeneralReport").val()
        var selected_start_date = $("#txtFromDateSearchGeneralReport").val() + " 06:00"
        var selected_end_date = $("#txtToDateSearchGeneralReport").val() + " 06:00"
        var post = {
            "action": "restaurant_general_report", 
            "selected_date_type" : selected_date_type, 
            "selected_start_date" : selected_start_date, 
            "selected_end_date" : selected_end_date
        }
    
        $.ajax({
            type: "POST", url: "api/main.php", data: post, dataType: "text",
            beforeSend:function(){
                $("#btnSearchGeneralReport").prop('disabled', true)
                $("#btnSearchGeneralReport").html("<i class='fa fa-spinner fa-pulse' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i> Please wait")
            },
            success: function (response) {
                $("#btnSearchGeneralReport").prop('disabled', false)
                $("#btnSearchGeneralReport").html("<i class='fa fa-search' style='font-size: 18px; margin-left: 5px; margin-bottom: 3px;'></i> Search")
                $("#generalReportSectionArea").html(response)
            }
        })
    })
        
    $(document).on('click', '#printGeneralReport', function () {
        //Display and open the print dialog box to print the report
        var report_restore_page = document.body.innerHTML
        var report_print_area = document.getElementById("generalReportPrintArea").innerHTML
        document.body.innerHTML = report_print_area
        window.print()
        document.body.innerHTML = report_restore_page
    })
    
    // ============================ End of General Report Section ================================================

    // ============================ END OF SYSTEM REPORTS SECTION MODULE SCRIPTS =================================
  
    // ============================ START OF DASHBOARD DESIGN MODULE SCRIPTS =====================================
  
    // ============================ Start of Waiter Analytics ====================================================
  
    // Search Waiter Analytics - Dashboard
    $(document).on("click", ".btnSelectDateWaiterAnalyticsDashboard", function () {
        var first_start_date = $(this).attr("first-date-start")
        var first_end_date = $(this).attr("first-date-end")
        var second_start_date = $(this).attr("second-date-start")
        var second_end_date = $(this).attr("second-date-end")
        var analytic_type = $(this).attr("analytic-type")
        var analytic_end_used_word = $(this).attr("end-used-word")
        // alert(first_start_date + " -- " + first_end_date + " -- " + second_start_date + " -- " + second_end_date + " -- " + analytic_type + " -- " + analytic_end_used_word)
        var post = {"action": "search_waiter_analytics_dashboard", "first_start_date": first_start_date, "first_end_date": first_end_date, "second_start_date": second_start_date, "second_end_date": second_end_date, "analytic_type": analytic_type, "analytic_end_used_word": analytic_end_used_word}
        $.ajax({
            type: "POST", url: "api/main.php", data: post, dataType: "text",
            success: function (response) {
                $(".waiterAnalyticsDashboardAreaSection").html(response)
            }
        })
    })
    
    // Set the end date alweys to be max than the start date
    $("#txtToDateCustomerWaiterAnalyticsDashboard").attr("max", $("#txtFromDateCustomerWaiterAnalyticsDashboard").val())
    // Choose First Date
    $(document).on("change", "#txtFromDateCustomerWaiterAnalyticsDashboard", function () {
        $("#txtToDateCustomerWaiterAnalyticsDashboard").attr("min", $(this).val())
        // alert(333333333333)
    })
  
    //Custom Date Search Waiter Analytics
    $(document).on("change", "#txtToDateCustomerWaiterAnalyticsDashboard", function () {
        $("#txtFromDateCustomerWaiterAnalyticsDashboard").attr("max", $(this).val())

        var first_start_date = $("#txtFromDateCustomerWaiterAnalyticsDashboard").val() + " 00:00"
        var first_end_date = $("#txtToDateCustomerWaiterAnalyticsDashboard").val() + " 23:59"
        var second_start_date = $("#txtFromDateCustomerWaiterAnalyticsDashboard").val() + " 00:00"
        var second_end_date = $("#txtToDateCustomerWaiterAnalyticsDashboard").val() + " 23:59"
        var analytic_type = "custom-date"
        var analytic_end_used_word = ""
        // alert(first_start_date + " -- " + first_end_date + " -- " + second_start_date + " -- " + second_end_date + " -- " + analytic_type + " -- " + analytic_end_used_word)
        var post = {"action": "search_waiter_analytics_dashboard", "first_start_date": first_start_date, "first_end_date": first_end_date, "second_start_date": second_start_date, "second_end_date": second_end_date, "analytic_type": analytic_type, "analytic_end_used_word": analytic_end_used_word}
        $.ajax({
            type: "POST", url: "api/main.php", data: post, dataType: "text",
            success: function (response) {
                $(".waiterAnalyticsDashboardAreaSection").html(response)
            }
        })
  })
  
  // ============================ End of Waiter Analytics ======================================================

  // 
  
  // ============================ END OF DASHBOARD DESIGN MODULE SCRIPTS =======================================
  
  

})
// ========================= AFRICAN DAAFI & PIZZA External Functions ==========================================

// Fill Kitchens
function fillKitchens() {
  $.ajax({
    method: "POST", url: "api/main.php", data: { action: "fill_kitchens" }, dataType: "JSON",
    success: function (data) {
      var Message = data.Message
      var status = data.Status
      var html = ""
      if (status == true) {
        html += `<option value="">Select Kitchen</option>`
        Message.forEach(function (returned_data, i) {
          html += `<option value="${returned_data["kitchenID"]}">${returned_data["kitchenName"]}</option>`
        })
        $("#cmbProcessingKitchenNewRestaurantProduct, #cmbProcessingKitchenUpdateRestaurantProduct").html(html)
      }
    }, error: function (data) { },
  })
}

// Fill Working Areas as Section
function fillWorkingSections() {
	$.ajax({    
		method: "POST", url : "api/main.php", data: {"action" : "fill_working_areas"}, dataType: "JSON",
		success : function(data){
			var Message = data.Message
			var status = data.Status
			var html = '';
			if(status == true){
				html += `<option value="">Select Section</option>`
				Message.forEach(function(returned_data, i){
				    html += `<option value="${returned_data['workingAreaID']}">${returned_data['workingAreaName']}</option>`
				})
				$("#cmbCategorySectionNewRestaurantCategory, #cmbCategorySectionUpdateRestaurantCategory, #cmbProductSectionNewRestaurantProduct, #cmbProductSectionUpdateRestaurantProduct").html(html)  
			}
		},
		error : function(data){

		}
	})
}

// Fill Restaurant Categories
function fillRestaurantCategories() {
  $.ajax({
    method: "POST", url: "api/main.php", data: { action: "fill_restaurant_categories" }, dataType: "JSON",
    success: function (data) {
      var Message = data.Message
      var status = data.Status
      var html = ""
      if (status == true) {
        html += `<option value="">Select Category</option>`
        Message.forEach(function (returned_data, i) {
          html += `<option value="${returned_data["categoryID"]}">${returned_data["categoryName"]} (${returned_data["workingAreaName"]})</option>`
        })
        $("#cmbProductCategoryNewRestaurantProduct, #cmbProductCategoryUpdateRestaurantProduct").html(html)
      }
    }, error: function (data) { },
  })
}

// Fill Active Customers
function fillActiveCustomers() {
  $.ajax({
    method: "POST", url: "api/main.php", data: { action: "fill_active_customers" }, dataType: "JSON",
    success: function (data) {
      var Message = data.Message
      var status = data.Status
      var html = ""
      html += `<option value="CU0001">Walking Customer - 000000000</option>`
      html += `<option value="RegisterNewCustomer">Register New Customer</option>`
      if (status == true) {
        Message.forEach(function (returned_data, i) {
          html += `<option value="${returned_data["customerID"]}">${returned_data["customerName"]} - ${returned_data["customerMobile"]}</option>`
        })
      }
      $("#cmbCustomerIddNewOrderAdminPOSPage, #cmbCustomerIddEditOrderInformation").html(html)
    }, error: function (data) { },
  })
}

// Fill Active Customers
function fillActiveCustomersForWaiters() {
  $.ajax({
    method: "POST", url: "api/main.php", data: { action: "fill_active_customers" }, dataType: "JSON",
    success: function (data) {
      var Message = data.Message
      var status = data.Status
      var html = ""
      html += `<option value="CU0001">Walking Customer - 000000000</option>`
      if (status == true) {
        Message.forEach(function (returned_data, i) {
          html += `<option value="${returned_data["customerID"]}">${returned_data["customerName"]} - ${returned_data["customerMobile"]}</option>`
        })
      }
      $("#cmbCustomerIddNewOrderWaiterPOSPage").html(html)
    }, error: function (data) { },
  })
}

// Fill Stock Categories
function fillStockCategories() {
  $.ajax({    
    method: "POST", url : "api/main.php", data: {"action" : "fill_stock_categories"}, dataType: "JSON",
    success: function(data) {
      var Message = data.Message, status = data.Status, html = ''
      if (status == true) {
        html += `<option value="">Select Category</option>`
        Message.forEach(function(returned_data, i) {
          html += `<option value="${returned_data['categoryID']}">${returned_data['categoryName']}</option>`
          })
        $("#cmbCategoryNameRegisterNewStockItem0, #cmbCategoryNameUpdateStockItem").html(html)
      }
    },error : function(data){ }
  })
} 

// Fill units of items
function fillItemUnits() {
  $.ajax({    
    method: "POST", url : "api/main.php", data: {"action" : "fill_item_units"}, dataType: "JSON",
    success: function(data) {
      var Message = data.Message, status = data.Status, html = ''
      if (status == true) {
        html += `<option value="">Select Unit</option>`
        Message.forEach(function(returned_data, i) {
          html += `<option value="${returned_data['unitID']}">${returned_data['unitName']}</option>`
          })
          $("#cmbUnitNameRegisterNewStockItem0, #cmbUnitNameUpdateStockItem").html(html)
        }
    },error : function(data){ }
  })
}

// Create our number formatter.
const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',

  // These options are needed to round to whole numbers if that's what you want.
  //minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1)
  //maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501)
});

