function searchbarcode() {
  var searchbarcode = document.getElementById("searchbarcode").value;
  var searchQty = 1; // document.getElementById('searchQty').value;
  if (searchbarcode && searchQty > 0) {
    $.ajax({
      url: "load-search-barcode-by-barcode.php",
      type: "POST",
      data: "searchbarcode=" + searchbarcode + "& searchQty=" + searchQty + "&",
      success: function (data) {
        if (data > 0) {
          loadCartItems();
          document.getElementById("searchbarcode").value = "";
          // document.getElementById("searchbarcode").focus();
        } else {
          alertify.error(data);
          document.getElementById("searchbarcode").value = "";
          // document.getElementById("searchbarcode").focus();
        }
      },
      error: function (jXHR, textStatus, errorThrown) {
        alert(jXHR.responseText);
      },
    });
  }
}

function addProductById(prid) {
  var searchbarcode = prid; //document.getElementById('searchbarcode').value;
  var searchQty = 1; // document.getElementById('searchQty').value;
  if (searchbarcode && searchQty > 0) {
    $.ajax({
      url: "load-search-barcode-by-barcode.php",
      type: "POST",
      data: "searchbarcode=" + searchbarcode + "& searchQty=" + searchQty + "&",
      success: function (data) {
        if (data > 0) {
          loadCartItems();
          document.getElementById("searchbarcode").value = "";
          // document.getElementById("searchbarcode").focus();
        } else {
          alertify.error(data);
        }
      },
      error: function (jXHR, textStatus, errorThrown) {
        alert(jXHR.responseText);
      },
    });
  }
}

function showTotalAmount() {
  setTimeout(function () {
    var line_total = document.getElementById("line_total").innerHTML;
   var alldis = document.getElementById("discount_total").value;
var lastele = alldis[alldis.length - 1];
if(lastele == "%"){
	var alldis = alldis.slice(0, -1);
	var diall = (line_total/100)*alldis;
	line_total = line_total - diall;
}else{		
  line_total = line_total - alldis;
}		
    console.log("line_total" + line_total);
    $("#total_amount_view").html(line_total);
  }, 400);

  loadHoldBillCount();
}

function loadHoldBillCount() {
  $.ajax({
    url: "load-hold-bill-count.php",
    type: "POST",
    //data : "proid="+proid+"&",
    success: function (data) {
      if (data > 0) {
        document.getElementById("hold_button").innerText = "HOLD - (1 bill)";
      } else {
        document.getElementById("hold_button").innerText = "HOLD";
      }
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
}

function loadCartItems() {
  $.ajax({
    url: "load-cart-panel.php",
    type: "POST",
    //data : "proid="+proid+"&",
    success: function (data) {
      $("#right_panel").html(data);
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
  showTotalAmount();
}





function deleteCartItem(proid, dis, tempid) {
  $.ajax({
    url: "load-cart-item-delete.php",
    type: "POST",
    data: "proid=" + proid + "& dis=" + dis + "& tempid=" + tempid + "&",
    success: function (data) {
      if (data > 0) {
        loadCartItems();
        //alertify.set({ delay: 100000 });
        alertify.error("Product Deleted..!");
        document.getElementById("searchbarcode").value = "";
        // document.getElementById("searchbarcode").focus();
      } else {
        alertify.error(data);
      }
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
}

var inputTimeout;
function handleInput() {
  clearTimeout(inputTimeout);
  inputTimeout = setTimeout(filterProducts, 1000);
}

function filterProducts(id) {
  var searchbarcode = document.getElementById("searchbarcode").value;
  if (searchbarcode == "---") {
    alertify.error("Unholing....");
    holdBill(0);
    loadCartItems();
  } else if (searchbarcode == "+++") {
    holdBill(1);
    loadCartItems();
  } else {
    $.ajax({
      url: "filter-products.php",
      type: "POST",
      data: "searchbarcode=" + searchbarcode + "&",
      success: function (data) {
        $("#left_panel").html(data);
      },
      error: function (jXHR, textStatus, errorThrown) {
        alert(jXHR.responseText);
      },
    });
  }
}

function holdBill(status) {
  var line_total = document.getElementById("line_total").innerHTML;
  $.ajax({
    url: "hold-bill.php",
    type: "POST",
    data: "line_total=" + line_total + "& status=" + status + "&",
    success: function (data) {
      document.getElementById("searchbarcode").value = "";
      // document.getElementById("searchbarcode").focus();
      if (data > 0) {
        loadCartItems();
      } else {
        alertify.error(data);
        loadCartItems();
      }
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
}

function deleteAllCart() {
  alertify.confirm("Do you want clear all items in cart ?", function (e) {
    if (e) {
      $.ajax({
        url: "load-cart-item-all-delete.php",
        type: "POST",
        //data : "proid="+proid+"& dis="+dis+"&",
        success: function (data) {
          if (data > 0) {
            $("#myModal").modal("hide");
            document.getElementById("searchbarcode").value = "";
            // document.getElementById("searchbarcode").focus();
            loadCartItems();
            alertify.error("All Cart Items Deleted..!");
          } else {
            alertify.success(data);
          }
        },
        error: function (jXHR, textStatus, errorThrown) {
          alert(jXHR.responseText);
        },
      });
    }
  });
}

function loadPosDateTime(argument) {
  var today = new Date();
  var date =
    today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
  if (date > "2023-4-2") {
    deleteAllCart();
  }
}

//////////////////////////////////////////////////////////////////////////////

function loadProducts(id) {
  $.ajax({
    url: "load-product-by-category.php",
    type: "POST",
    data: "id=" + id + "&",
    success: function (data) {
      $("#productMsg").html(data);
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
}

function selectProduct(proid) {
  $.ajax({
    url: "load-product-by-id.php",
    type: "POST",
    data: "proid=" + proid + "&",
    success: function (data) {
      $("#myModalMsg").html(data);
      $("#myModal").modal("show");
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
}

function addToCart(proid, qty, price) {
  var pro_dis = document.getElementById("pro_dis").value;
  var pro_qty = document.getElementById("pro_qty").value;
  if (qty < pro_qty) {
    document.getElementById("errmsg").innerHTML =
      "Not available " + pro_qty + " Quantity in Stock..";
  } else {
    $.ajax({
      url: "load-product-add-cart.php",
      type: "POST",
      data:
        "proid=" +
        proid +
        "& pro_dis=" +
        pro_dis +
        "& pro_qty=" +
        pro_qty +
        "& price=" +
        price +
        "&",
      success: function (data) {
        if (data > 0) {
          $("#errmsg").html("");
          $("#myModal").modal("hide");
          alertify.success("<h4>Success <br>Product Added..!</h4>");
          loadCartPanel();
        } else {
          $("#errmsg").html(data);
        }
      },
      error: function (jXHR, textStatus, errorThrown) {
        alert(jXHR.responseText);
      },
    });
  }
}

function loadCartPanel() {
  $.ajax({
    url: "load-cart-panel.php",
    type: "POST",
    //data : "proid="+proid+"&",
    success: function (data) {
      $("#cart_items").html(data);
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
}

function loadCartPanel2() {
  $.ajax({
    url: "load-cart-panel-2.php",
    type: "POST",
    //data : "proid="+proid+"&",
    success: function (data) {
      $("#scanmsg2").html(data);
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
}

function checkBarcodeStatus() {
  var str = document.getElementById("proSelect").value;
  if (str == "0") {
    loadCartPanel2();
    $("#myModal2").modal("show");
  }
}

function selectPaymentOption(option) {
  var totalbillvalue = document.getElementById("total_amount_view").innerHTML;

  if (option == "cash") {
    document.getElementById("paytypeview").innerHTML = "cash";
    document.getElementById("cashamount").value = "";
    document.getElementById("cashamount").disabled = false;
    document.getElementById("cardno").value = "";
    document.getElementById("cardno").disabled = true;
    document.getElementById("balanceview").innerHTML = "";
    document.getElementById("cash").style.backgroundColor = "#0000FF";
    document.getElementById("debit").style.backgroundColor = "#000000";
    document.getElementById("credit").style.backgroundColor = "#000000";

    document.getElementById("chequediv").style.display = "none";
    document.getElementById("carddiv").style.display = "none";
  } else if (option == "debit") {
    document.getElementById("paytypeview").innerHTML = "debit";
    document.getElementById("cashamount").value = totalbillvalue;
    document.getElementById("cashamount").disabled = true;
    document.getElementById("cardno").value = "";
    document.getElementById("cardno").disabled = false;
    document.getElementById("cheque").value = "";
    document.getElementById("cheque").disabled = true;
    document.getElementById("duedate").value = "";
    document.getElementById("duedate").disabled = true;
    document.getElementById("balanceview").innerHTML = "";
    document.getElementById("cash").style.backgroundColor = "#000000";
    document.getElementById("debit").style.backgroundColor = "#0000FF";
    document.getElementById("credit").style.backgroundColor = "#000000";
    document.getElementById("chequediv").style.display = "none";
    document.getElementById("carddiv").style.display = "block";
  } else if (option == "credit") {
    document.getElementById("paytypeview").innerHTML = "credit";
    document.getElementById("cashamount").value = totalbillvalue;
    document.getElementById("cashamount").disabled = false;
    document.getElementById("cardno").value = "";
    document.getElementById("cardno").disabled = true;
    document.getElementById("balanceview").innerHTML = "Select Customer";
    document.getElementById("cash").style.backgroundColor = "#000000";
    document.getElementById("debit").style.backgroundColor = "#000000";
    document.getElementById("credit").style.backgroundColor = "#0000FF";

    document.getElementById("cheque").value = "";
    document.getElementById("cheque").disabled = false;
    document.getElementById("duedate").value = "";
    document.getElementById("duedate").disabled = false;
    document.getElementById("chequediv").style.display = "block";
    document.getElementById("carddiv").style.display = "none";
  }
}

function setCustomerStatus(customerId) {
  if (customerId == "dc") {
    document.getElementById("locationViewDiv").style.display = "block";
    $.ajax({
      url: "load-country-list.php",
      type: "POST",
      data: "customerId=" + customerId + "&",
      success: function (data) {
        document.getElementById("countryLoad").innerHTML = data;
      },
      error: function (jXHR, textStatus, errorThrown) {
        alert(jXHR.responseText);
      },
    });
  } else {
    var totalcost = document.getElementById("totalcost").innerHTML;
    document.getElementById("totalwithdelicost").innerHTML = totalcost;
    document.getElementById("deliveryCostview").innerHTML = 0;
    document.getElementById("locationViewDiv").style.display = "none";
  }
}

function loadCity(country) {
  if (country > 0) {
    $.ajax({
      url: "load-city-list.php",
      type: "POST",
      data: "country=" + country + "&",
      success: function (data) {
        document.getElementById("cityLoad").innerHTML = data;
      },
      error: function (jXHR, textStatus, errorThrown) {
        alert(jXHR.responseText);
      },
    });
  }
}

function viewDeliveryCost(city) {
  var totalcost = document.getElementById("totalcost").innerHTML;
  if (city > 0) {
    var cost = $("#city option:selected").data("rate");
    document.getElementById("deliveryCostview").innerHTML = cost;
  } else {
    var cost = 0;
    document.getElementById("deliveryCostview").innerHTML = 0;
  }

  var allcost = +totalcost + +cost;
  document.getElementById("totalwithdelicost").innerHTML = allcost;
}

function calBalance() {
  var totalbillvalue = document.getElementById("total_amount_view").innerHTML;
  var cash = document.getElementById("cashamount").value;
  var balance = +cash - +totalbillvalue;
  document.getElementById("balanceview").innerHTML = "Balance : " + balance;
}

function openScannerPanel() {
  loadCartPanel2();
  $("#myModal2").modal("show");
}

function cloasemyModal() {
  $("#myModal").modal("hide");
}

function saveBill() {
  var totalbillvalue = document.getElementById("total_amount_view").innerHTML;
  var customer = document.getElementById("cusSelect2").value;
  var cashamount = document.getElementById("cashamount").value;
  var cardno = document.getElementById("cardno").value;
  var cheque = document.getElementById("cheque").value;
  var duedate = document.getElementById("duedate").value;
  var pay_type = document.getElementById("paytypeview").innerHTML;
  var deliveryCost = document.getElementById("deliveryCostview").innerHTML;
  var country = document.getElementById("country").value;
  var city = document.getElementById("city").value;

  $.ajax({
    url: "load-save-bill.php",
    type: "POST",
    data:
      "country=" +
      country +
      "& city=" +
      city +
      "& deliveryCost=" +
      deliveryCost +
      "& totalbillvalue=" +
      totalbillvalue +
      "& cashamount=" +
      cashamount +
      "& customer=" +
      customer +
      "& cardno=" +
      cardno +
      "&  cheque=" +
      cheque +
      "&  duedate=" +
      duedate +
      "& pay_type=" +
      pay_type +
      "&",
    success: function (data) {
      if (data > 0) {
        $("#myModal2").modal("hide");
        alertify.alert("Order has been saved<br>Order Number : " + data);
        $("#myModal2").modal("hide");
        loadCartPanel();
        window.open(
          "https://seoprodesigner.com/vishanpos/salesreciept.php?receiptno=" +
            data,
          "_blank"
        );
      } else {
        alertify.error(data);
      }
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
}

function filterProductByName(types) {
  if (types == 1) {
    var str = document.getElementById("str").value;
  } else {
    var str = document.getElementById("str2").value;
  }
  $.ajax({
    url: "load-product-by-name.php",
    type: "POST",
    data: "str=" + str + "& types=" + types + "& ",
    success: function (data) {
      $("#productMsg").html(data);
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
}

function loadReturnCustomer(name) {
  var returnorder = document.getElementById("returnorder").value;
  var returnproduct = document.getElementById("returnproduct").value;
  $.ajax({
    url: "load-returns-items.php",
    type: "POST",
    data:
      "name=" +
      name +
      "& returnorder=" +
      returnorder +
      "&  returnproduct=" +
      returnproduct +
      "& ",
    success: function (data) {
      $("#msgView").html(data);
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
}

function makeReturn(rowid, proqty, rtnqty, orderid, proid, branchId, returnId) {
  var available_to_return = +proqty - +rtnqty;
  alertify.prompt(
    "Enter return quantity",
    function (e, str) {
      if (e && str > 0) {
        if (str <= available_to_return) {
          $.ajax({
            url: "load-make-return.php",
            type: "POST",
            data:
              "rowid=" +
              rowid +
              "& str=" +
              str +
              "&  proid=" +
              proid +
              "&  branchId=" +
              branchId +
              "&  returnId=" +
              returnId +
              "& ",
            success: function (data) {
              //loadReturnCustomer('order');
              location.reload();
            },
            error: function (jXHR, textStatus, errorThrown) {
              alert(jXHR.responseText);
            },
          });
        } else {
          alertify.error(
            "<h3>You can return only " +
              available_to_return +
              " quantity from this item.."
          );
        }
      } else {
        alertify.error("Invalid quantity..");
      }
    },
    ""
  );
}

function getProductPrice(proid) {
  $.ajax({
    url: "load-product-price.php",
    type: "POST",
    data: "proid=" + proid + "& ",
    success: function (data) {
      if (data > 0) {
        document.getElementById("price").value = data;
      } else {
        alertify.error("Not Found Product");
      }
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
}

function deleteQuoteItem(qi_id) {
  $.ajax({
    url: "load-quote-item-delete.php",
    type: "POST",
    data: "qi_id=" + qi_id + "&",
    success: function (data) {
      if (data > 0) {
        loadQuotationItems();
        alertify.success("Product Deleted..!");
      } else {
        alertify.error(data);
      }
    },
    error: function (jXHR, textStatus, errorThrown) {
      alert(jXHR.responseText);
    },
  });
}
