//Add Input Field Of Row
"use strict";
function addInputField(t) {
  var row = $("#addinvoice tbody tr").length;
  var count = row + 1;
  var tab1 = 0;
  var tab2 = 0;
  var tab3 = 0;
  var tab4 = 0;
  var tab5 = 0;
  var tab6 = 0;
  var tab7 = 0;
  var tab8 = 0;
  var tab9 = 0;
  var limits = 500;
  var taxnumber = $("#txfieldnum").val();
  var tbfild = "";
  for (var i = 0; i < taxnumber; i++) {
    var taxincrefield =
      '<input id="total_tax' +
      i +
      "_" +
      count +
      '" class="total_tax' +
      i +
      "_" +
      count +
      '" type="hidden"><input id="all_tax' +
      i +
      "_" +
      count +
      '" class="total_tax' +
      i +
      '" type="hidden" name="tax[]">';
    tbfild += taxincrefield;
  }
  if (count == limits)
    alert("You have reached the limit of adding " + count + " inputs");
  else {
    var a = "product_name_" + count,
      tabindex = count * 5,
      e = document.createElement("tr");
    tab1 = tabindex + 1;
    tab2 = tabindex + 2;
    tab3 = tabindex + 3;
    tab4 = tabindex + 4;
    tab5 = tabindex + 5;
    tab6 = tabindex + 6;
    tab7 = tabindex + 7;
    tab8 = tabindex + 8;
    tab9 = tabindex + 9;
    (e.innerHTML =
      "<td><input type='text' name='product_name' onkeypress='invoice_productList(" +
      count +
      ");' class='form-control productSelection common_product' placeholder='Product Name' id='" +
      a +
      "' required tabindex='" +
      tab1 +
      "'><input type='hidden' class='common_product autocomplete_hidden_value  product_id_" +
      count +
      "' name='product_id[]' id='SchoolHiddenId'/></td><td><input type='text' name='desc[]'' class='form-control text-right ' /></td><td><select class='form-control' id='serial_no_" +
      count +
      "' name='serial_no[]'><option></option></select></td> <td><input type='text' name='available_quantity[]' id='' class='form-control text-right common_avail_qnt available_quantity_" +
      count +
      "' value='0' readonly='readonly' /></td><td><input class='form-control text-right common_name unit_" +
      count +
      " valid' value='None' readonly='' aria-invalid='false' type='text'></td><td> <input type='text' name='product_quantity[]' required='required' onkeyup='quantity_calculate(" +
      count +
      ");' onchange='quantity_calculate(" +
      count +
      ");' id='total_qntt_" +
      count +
      "' class='common_qnt total_qntt_" +
      count +
      " form-control text-right'  placeholder='0.00' min='0' tabindex='" +
      tab2 +
      "' value='1'/></td><td><input type='text' name='product_rate[]' onkeyup='quantity_calculate(" +
      count +
      ");' onchange='quantity_calculate(" +
      count +
      ");' id='price_item_" +
      count +
      "' class='common_rate price_item" +
      count +
      " form-control text-right' required placeholder='0.00' min='0' tabindex='" +
      tab3 +
      "'/></td><td><input type='text' name='discount[]' onkeyup='quantity_calculate(" +
      count +
      ");' onchange='quantity_calculate(" +
      count +
      ");' id='discount_" +
      count +
      "' class='form-control text-right common_discount' placeholder='0.00' min='0' tabindex='" +
      tab4 +
      "' /><input type='hidden' value='' name='discount_type' id='discount_type_" +
      count +
      "'></td><td class='text-right'><input class='common_total_price total_price form-control text-right' type='text' name='total_price[]' id='total_price_" +
      count +
      "' value='0.00' readonly='readonly'/></td><td>" +
      tbfild +
      "<input type='hidden' id='all_discount_" +
      count +
      "' class='total_discount' name='discount_amount[]'/><button tabindex='" +
      tab5 +
      "' style='text-align: center;' class='btn btn-danger btn-xs' type='button'  onclick='deleteRow(this)'><i class='fa fa-close'></i></button></td>"),
      document.getElementById(t).appendChild(e),
      document.getElementById(a).focus(),
      document
        .getElementById("add_invoice_item")
        .setAttribute("tabindex", tab6);
    document.getElementById("paidAmount").setAttribute("tabindex", tab7);
    document.getElementById("full_paid_tab").setAttribute("tabindex", tab8);
    document.getElementById("add_invoice").setAttribute("tabindex", tab9);
    count++;
  }
}
//Quantity calculat
("use strict");
function quantity_calculate(item) {
  var quantity = $("#total_qntt_" + item).val();
  var available_quantity = $(".available_quantity_" + item).val();
  var price_item = $("#price_item_" + item).val();
  var invoice_discount = $("#invoice_discount").val();
  var discount = $("#discount_" + item).val();
  var vat_percent = $("#vat_percent_" + item).val();
  var total_tax = $("#total_tax_" + item).val();
  var total_discount = $("#total_discount_" + item).val();
  var taxnumber = $("#txfieldnum").val();
  var dis_type = $("#discount_type").val();
  if (
    parseInt(available_quantity) == 0 &&
    parseInt(quantity) > parseInt(available_quantity)
  ) {
    var message = "This Item is Out of Stock";
    toastr["error"](message);
    $("table#addinvoice tr#row_" + item).remove();
    $("#image-active_" + item).removeClass("active");
    $("#image-active_count_" + item).removeClass("quantity");
    $("#active_pro_" + id).text("");
    $("#total_qntt_" + item).val(0);
    var quantity = 0;
    $("#total_price_" + item).val(0);
    for (var i = 0; i < taxnumber; i++) 
      {
      $("#all_tax" + i + "_" + item).val(0);
      quantity_calculate(item);
     }
  }
  if (
    parseInt(available_quantity) > 0 &&
    parseInt(quantity) > parseInt(available_quantity)
  ) {
    var message = "You can Sale maximum " + available_quantity + " Items";
    toastr["error"](message);
    $("#total_qntt_" + item).val(available_quantity);
    quantity_calculate(item);
  }

  if (quantity > 0 || discount > 0 || vat_percent > 0) {
    if (dis_type == 1) {
      var price = quantity * price_item;
      var dis = +((price * discount) / 100);
      $("#discount_value_" + item).val(dis);
      $("#all_discount_" + item).val(dis);
      //Total price calculate per product
      var temp = price - dis;
      // product wise vat start
      var vat = +((temp * vat_percent) / 100);
      $("#vat_value_" + item).val(vat);
      // product wise vat end
      var ttletax = 0;
      $("#total_price_" + item).val(temp);
      for (var i = 0; i < taxnumber; i++) {
        var tax = temp * $("#total_tax" + i + "_" + item).val();
        ttletax += Number(tax);
        $("#all_tax" + i + "_" + item).val(tax);
      }
    } else if (dis_type == 2) {
      var price = quantity * price_item;
      // Discount cal per product
      var dis = discount * quantity;
      $("#discount_value_" + item).val(dis);
      $("#all_discount_" + item).val(dis);
      //Total price calculate per product
      var temp = price - dis;
      // product wise vat start
      var vat = +((temp * vat_percent) / 100);
      $("#vat_value_" + item).val(vat);
      // product wise vat end
      $("#total_price_" + item).val(temp);

      var ttletax = 0;
      for (var i = 0; i < taxnumber; i++) {
        var tax = temp * $("#total_tax" + i + "_" + item).val();
        ttletax += Number(tax);
        $("#all_tax" + i + "_" + item).val(tax);
      }
    } else if (dis_type == 3) {
      var total_price = quantity * price_item;
      var dis = discount;
      // Discount cal per product
      $("#discount_value_" + item).val(dis);
      $("#all_discount_" + item).val(dis);
      //Total price calculate per product
      var price = total_price - dis;
      // product wise vat start
      var vat = +((price * vat_percent) / 100);
      $("#vat_value_" + item).val(vat);
      // product wise vat end
      $("#total_price_" + item).val(price);

      var ttletax = 0;
      for (var i = 0; i < taxnumber; i++) {
        var tax = price * $("#total_tax" + i + "_" + item).val();
        ttletax += Number(tax);
        $("#all_tax" + i + "_" + item).val(tax);
      }
    }
  } else {
    var n = quantity * price_item;
    var c = quantity * price_item * total_tax;
    $("#total_price_" + item).val(n), $("#all_tax_" + item).val(c);
  }
  calculateSum(item);
  invoice_paidamount();
  image_activation(item);
}
//Calculate Sum
("use strict");
function calculateSum(nid) {
  var taxnumber = $("#txfieldnum").val();
  var t = 0, // total price
      p = 0, // total discount
      v = 0, // total VAT amount
      f = 0, // total tax
      ad = 0, // additional payments (dppr)
      s_cost = parseFloat($("#shipping_cost").val()) || 0;

  // Total Tax Breakdown per field
  for (var i = 0; i < taxnumber; i++) {
    var j = 0;
    $(".total_tax" + i).each(function () {
      if (!isNaN(this.value) && this.value.length !== 0) {
        j += parseFloat(this.value);
      }
    });
    $("#total_tax_ammount" + i).val(j.toFixed(2));
  }

  // Total Discount
  $(".total_discount").each(function () {
    if (!isNaN(this.value) && this.value.length !== 0) {
      p += parseFloat(this.value);
    }
  });
  $("#total_discount_ammount").val(p.toFixed(2));

  // Total VAT
  $(".total_vatamnt").each(function () {
    if (!isNaN(this.value) && this.value.length !== 0) {
      v += parseFloat(this.value);
    }
  });
  $("#total_vat_amnt").val(v.toFixed(2));

  // Total Tax (if different from VAT)
  $(".totalTax").each(function () {
    if (!isNaN(this.value) && this.value.length !== 0) {
      f += parseFloat(this.value);
    }
  });
  $("#total_tax_amount").val(f.toFixed(2));

  // Total Item Prices
  // $(".total_price").each(function () {
  //   if (!isNaN(this.value) && this.value.length !== 0) {
  //     t += parseFloat(this.value);
  //     console.log(this.value);
  //   }
  // });

  // Log the count of .total_price elements
  console.log("Total .total_price inputs:", $(".total_price").length);

  $(".total_price").each(function () {
    console.log("Product ID:", $(this).attr("id"), "Price found:", this.value);  // Log product ID and price
    if (!isNaN(this.value) && this.value.length !== 0) {
        t += parseFloat(this.value);
    }
});


  console.log("Total Grand Total:", t);
  $("#net_total_text").text(t.toFixed(2)); // Display the total price

  // Additional Amounts (dppr fields)
  $(".dppr").each(function () {
    if (!isNaN(this.value) && this.value.length !== 0) {
      ad += parseFloat(this.value);
    }
  });

  // Final grand total calculation (VAT already included in item prices)
  var grand_total = t + s_cost + ad - p;

  // Set calculated values
  // $("#grandTotal").val(grand_total.toFixed(2));
  $("#grandTotal").text(grand_total.toFixed(2));
  $("#net_total_text").text(grand_total.toFixed(2));
  $("#pamount_by_method").val(grand_total);
  $("#paidAmount").val(grand_total);

  // Optional: update payment modal if on edit page
  var invoice_edit_page = $("#invoice_edit_page").val();
  var preload_pay_view = $("#preload_pay_view").val();
  $("#add_new_payment").empty();
  $("#pay-amount").text("0");

  if (invoice_edit_page == 1) {
    var base_url = $("#base_url").val();
    var csrf_test_name = $('[name="csrf_test_name"]').val();
    var gtotal = $(".grandTotalamnt").val();
    var url = base_url + "invoice/invoice/bdtask_showpaymentmodal";
    $.ajax({
      type: "GET",
      url: url,
      data: { csrf_test_name: csrf_test_name },
      success: function (data) {
        $("#add_new_payment").append(data);
        $("#pamount_by_method").val(gtotal);
        $("#preload_pay_view").val("1");
      },
    });
  }
}


$(document).on("click", "#add_invoice", function () {
  var total = 0;
  $(".pay").each(function () {
    total += parseFloat($(this).val()) || 0;
  });

  var gtotal = $("#paidAmount").val();
  if (total != gtotal) {
    toastr.error("Paid Amount Should Equal To Payment Amount");
    return false;
  }
});

// ******* new payment add start *******
$(document).on("click", "#add_new_payment_type", function () {
  var base_url = $("#base_url").val();
  var csrf_test_name = $('[name="csrf_test_name"]').val();
  var gtotal = $("#paidAmount").val();

  var total = 0;
  $(".pay").each(function () {
    total += parseFloat($(this).val()) || 0;
  });

  if (total >= gtotal) {
    alert("Paid amount is exceed to Total amount.");
    return false;
  }

  var url = base_url + "invoice/invoice/bdtask_showpaymentmodal";
  $.ajax({
    type: "GET",
    url: url,
    data: { csrf_test_name: csrf_test_name },
    success: function (data) {
      $($("#add_new_payment").append(data)).show("slow", function () {});
      var length = $(".number").length;
      $(".number:eq(" + (length - 1) + ")").val(
        parseFloat($("#pay-amount").text())
      );
      var total2 = 0;
      $(".number").each(function () {
        total2 += parseFloat($(this).val()) || 0;
      });
      $("#paidAmount").val(total2.toFixed(2, 2));
      var dueamnt = parseFloat(gtotal) - total2;
      $("#dueAmmount").val(dueamnt);
    },
  });
});

function changedueamount() {
  var inputval = parseFloat(0);
  var maintotalamount = $(".grandTotalamnt").val();

  $(".number").each(function () {
    var inputdata = parseFloat($(this).val());
    inputval = inputval + inputdata;
  });

  var restamount = parseFloat(maintotalamount) - parseFloat(inputval);
  var changes = restamount.toFixed(3);
  if (changes <= 0) {
    $("#change-amount").text(Math.abs(changes));
    $("#pay-amount").text(0);
  } else {
    $("#change-amount").text(0);
    $("#pay-amount").text(changes);
  }
}

// ******* new payment add end *******

//Invoice Paid Amount
("use strict");
function invoice_paidamount() {
  var prb = parseFloat($("#previous").val(), 10);  // previous balance
  var pr = (prb != 0) ? prb : 0;                   // if previous is non-zero, use it
  var d = 0;                                       // change amount (if overpaid)
  
  var t = parseFloat($("#grandTotal").val(), 10);  // grand total
  var a = parseFloat($("#paidAmount").val(), 10);  // paid amount
  
  var e = t - a;       // amount still due
  var f = e + pr;      // due + previous balance
  var nt = t + pr;     // net total (grand total + previous balance)
  d = a - nt;          // change to return to customer if overpaid

  $("#pamount_by_method").val(a);
  $("#add_new_payment").empty();
  $("#pay-amount").text("0");

  $("#n_total").val(nt.toFixed(2));
  $("#net_total_text").text(nt.toFixed(2));

  if (e > 0) {
    $("#dueAmmount").val(f.toFixed(2));
    $("#due_text").text(f.toFixed(2));
    if (a <= f) {
      $("#change").val(0);
    }
  } else {
    if (a < f) {
      $("#change").val(0);
    }
    if (a > f) {
      $("#change").val(d.toFixed(2));
    }
    $("#dueAmmount").val(0);
    $("#due_text").text(0);
  }
}


//Stock Limit
("use strict");
function stockLimit(t) {
  var a = $("#total_qntt_" + t).val(),
    e = $(".product_id_" + t).val(),
    o = $(".baseUrl").val();

  $.ajax({
    type: "POST",
    url: o + "Cinvoice/product_stock_check",
    data: {
      product_id: e,
    },
    cache: !1,
    success: function (e) {
      alert(e);
      if (a > Number(e)) {
        var o = "You can Sale maximum " + e + " Items";
        alert(o),
          $("#qty_item_" + t).val("0"),
          $("#total_qntt_" + t).val("0"),
          $("#total_price_" + t).val("0");
      }
    },
  });
}

("use strict");
function stockLimitAjax(t) {
  var a = $("#total_qntt_" + t).val(),
    e = $(".product_id_" + t).val(),
    o = $(".baseUrl").val();

  $.ajax({
    type: "POST",
    url: o + "Cinvoice/product_stock_check",
    data: {
      product_id: e,
    },
    cache: !1,
    success: function (e) {
      alert(e);
      if (a > Number(e)) {
        var o = "You can Sale maximum " + e + " Items";
        alert(o),
          $("#qty_item_" + t).val("0"),
          $("#total_qntt_" + t).val("0"),
          $("#total_price_" + t).val("0.00"),
          calculateSum();
      }
    },
  });
}

//Invoice full paid
("use strict");
function full_paid() {
  var grandTotal = $("#n_total").val();
  $("#paidAmount").val(grandTotal);
  invoice_paidamount();
  calculateSum();
}

//Delete a row of table
("use strict");
function deleteRow(t, nid) {
  var a = $("#addinvoice > tbody > tr").length;

  if (1 == a) alert("There only one row you can't delete.");
  else {
    var e = t.parentNode.parentNode;
    e.parentNode.removeChild(e), calculateSum();
    invoice_paidamount();

    $("#active_pro_" + nid).text("");
    $("#image-active_" + nid).removeClass("active");
    $("#image-active_count_" + nid).removeClass("quantity");

    var current = 1;
    $("#addinvoice > tbody > tr td input.productSelection").each(function () {
      current++;
      $(this).attr("id", "product_name" + current);
    });
    var common_qnt = 1;
    $("#addinvoice > tbody > tr td input.common_qnt").each(function () {
      common_qnt++;
      $(this).attr("id", "total_qntt_" + common_qnt);
      $(this).attr("onkeyup", "quantity_calculate(" + common_qnt + ");");
      $(this).attr("onchange", "quantity_calculate(" + common_qnt + ");");
    });
    var common_rate = 1;
    $("#addinvoice > tbody > tr td input.common_rate").each(function () {
      common_rate++;
      $(this).attr("id", "price_item_" + common_rate);
      $(this).attr("onkeyup", "quantity_calculate(" + common_qnt + ");");
      $(this).attr("onchange", "quantity_calculate(" + common_qnt + ");");
    });
    var common_discount = 1;
    $("#addinvoice > tbody > tr td input.common_discount").each(function () {
      common_discount++;
      $(this).attr("id", "discount_" + common_discount);
      $(this).attr("onkeyup", "quantity_calculate(" + common_qnt + ");");
      $(this).attr("onchange", "quantity_calculate(" + common_qnt + ");");
    });
    var common_total_price = 1;
    $("#addinvoice > tbody > tr td input.common_total_price").each(function () {
      common_total_price++;
      $(this).attr("id", "total_price_" + common_total_price);
    });
    var invoice_edit_page = $("#invoice_edit_page").val();

    $("#add_new_payment").empty();

    $("#pay-amount").text("0");
    if (invoice_edit_page == 1) {
      var base_url = $("#base_url").val();
      var csrf_test_name = $('[name="csrf_test_name"]').val();
      var gtotal = $(".grandTotalamnt").val();
      var url = base_url + "invoice/invoice/bdtask_showpaymentmodal";
      $.ajax({
        type: "GET",
        url: url,
        data: { csrf_test_name: csrf_test_name },
        success: function (data) {
          $($("#add_new_payment").append(data));
          $("#pamount_by_method").val(gtotal);
        },
      });
    }
  }
}
var count = 2,
  limits = 500;
("use strict");
function customer_autocomplete(sl) {
  var customer_id = $("#customer_id").val();
  // Auto complete
  var options = {
    minLength: 0,
    source: function (request, response) {
      var customer_name = $("#customer_name").val();
      var csrf_test_name = $('[name="csrf_test_name"]').val();
      var base_url = $("#base_url").val();

      $.ajax({
        url: base_url + "invoice/invoice/bdtask_customer_autocomplete",
        method: "post",
        dataType: "json",
        data: {
          term: request.term,
          customer_id: customer_name,
          csrf_test_name: csrf_test_name,
        },
        success: function (data) {
          response(data);
        },
      });
    },
    focus: function (event, ui) {
      $(this).val(ui.item.label);
      return false;
    },
    select: function (event, ui) {
      $(this)
        .parent()
        .parent()
        .find("#autocomplete_customer_id")
        .val(ui.item.value);
      var customer_id = ui.item.value;
      customer_due(customer_id);

      $(this).unbind("change");
      return false;
    },
  };

  $("body").on("keypress.autocomplete", "#customer_name", function () {
    $(this).autocomplete(options);
  });
}

("use strict");
function customer_due(id) {
  var csrf_test_name = $('[name="csrf_test_name"]').val();
  var base_url = $("#base_url").val();
  $.ajax({
    url: base_url + "invoice/invoice/previous",
    type: "post",
    data: { customer_id: id, csrf_test_name: csrf_test_name },
    success: function (msg) {
      $("#previous").val(msg);
    },
    error: function (xhr, desc, err) {
      alert("failed");
    },
  });
}

$(document).ready(function () {
  "use strict";

  $("#full_paid_tab").keydown(function (event) {
    if (event.keyCode == 13) {
      $("#add_invoice").trigger("click");
    }
  });
});

$(document).ready(function () {
  "use strict";

  var frm = $("#gui_sale_insert");
  var output = $("#output");
  var invoice_no = $("#gui_invoice_no").text();

  var nextinvoice = parseInt(invoice_no) + +1;
  frm.on("submit", function (e) {
    e.preventDefault();
    $.ajax({
      url: $(this).attr("action"),
      method: $(this).attr("method"),
      dataType: "json",
      data: frm.serialize(),
      success: function (data) {
        if (data.status == true) {
          toastr["success"](data.message);
          $(".quantity").removeClass("quantity");
          $(".product-panel").removeClass("active");
          $(".active_qty").text("");

          swal(
            {
              title: "Success!",
              showCancelButton: true,
              cancelButtonText: "NO",
              cancelButtonColor: "red",
              confirmButtonText: "Yes",
              confirmButtonColor: "#008000",
              text: "Do You Want To Print ?",
              type: "success",
            },
            function (inputValue) {
              if (inputValue === true) {
                $("#addinvoice tbody tr").remove();
                $("#gui_sale_insert").trigger("reset");
                $("#n_total").val("");
                $("#net_total_text").text("0.00");
                $("#dueAmmount").val("");
                $("#due_text").text("0.00");
                $("#invoice_no").val(nextinvoice);
                $("#gui_invoice_no").text(nextinvoice);
                $(".card_typesl").val(null).trigger("change");

                printRawHtml(data.details);
              } else {
                $("#addinvoice tbody tr").remove();
                $("#gui_sale_insert").trigger("reset");
                $("#n_total").val("");
                $("#net_total_text").text("0.00");
                $("#dueAmmount").val("");
                $("#due_text").text("0.00");
                $("#invoice_no").val(nextinvoice);
                $("#gui_invoice_no").text(nextinvoice);
                $(".card_typesl").val(null).trigger("change");
                invoice_no_check();
              }
            }
          );

          $("#inv_id").val(data.invoice_id);

          if (data.status == true && event.keyCode == 13) {
          }
        } else {
          toastr["error"](data.exception);
        }
      },
      error: function (xhr) {
        alert("failed!");
      },
    });
  });
});

("use strict");
function onselectimage(id) {
  var product_id = id;
  var base_url = $("#base_url").val();
  var csrf_test_name = $('[name="csrf_test_name"]').val();
  var exist = $("#SchoolHiddenId_" + product_id).val();
  var qty = $("#total_qntt_" + product_id).val();
  var add_qty = parseInt(qty) + 1;
  var url = "";
  var taxtype = $("#tax_type").val();
  if (taxtype == "fixed") {
      url = base_url + "invoice/invoice/gui_pos_invoice";
  }
  if (taxtype == "dynamic") {
      url = base_url + "invoice/invoice/gui_pos_invoice_dynamic";
  }

  if (product_id == exist) {
      var batch_id = $("#serial_no_" + product_id).val();
      if (batch_id != "") {
          $("#total_qntt_" + product_id).val(add_qty);
          quantity_calculate(product_id);
          calculateSum();
          invoice_paidamount();
          image_activation(product_id);
      } else {
          alert("Please Select Batch No");
      }
  } else {
      // Before appending the new product, ensure to remove any existing row with this product_id
      $("#row_" + product_id).remove(); // Remove any previous row of the same product

      $.ajax({
          type: "post",
          async: false,
          url: url,
          data: { product_id: product_id, csrf_test_name: csrf_test_name },
          success: function (data) {
              if (data == false) {
                  alert("This Product Not Found !");
              } else {
                  // Append the new product row
                  $("#addinvoice tbody").append(data);
                  quantity_calculate(product_id);
                  calculateSum();
                  invoice_paidamount();
                  image_activation(product_id);
              }
          },
          error: function () {
              alert("Request Failed, Please check your code and try again!");
          },
      });
  }
}




("use strict");
$("body").on("keyup", "#product_name", function () {
  var product_name = $(this).val();
  var csrf_test_name = $('[name="csrf_test_name"]').val();
  var myurl = $("#posurl_productname").val();
  $.ajax({
    type: "post",
    async: false,
    url: myurl,
    data: { product_name: product_name, csrf_test_name: csrf_test_name },
    success: function (data) {
      if (data == "420") {
        $("#product_search").html(
          '<h1 class"srcalrt">Product not found !</h1>'
        );
      } else {
        $("#product_search").html(data);
      }
    },
    error: function () {
      alert("Request Failed, Please check your code and try again!");
    },
  });
});

function getslcategory(category_id) {
  var base_url = $("#base_url").val();
  var csrf_test_name = $('[name="csrf_test_name"]').val();
  var product_name = $("#product_name").val();
  var myurl = $("#posurl").val();
  $.ajax({
    type: "post",
    async: false,
    url: myurl,
    data: {
      product_name: product_name,
      category_id: category_id,
      csrf_test_name: csrf_test_name,
    },
    success: function (data) {
      if (data == "420") {
        $("#product_search").html(data);
      } else {
        $("#product_search").html(data);
      }
    },
    error: function () {
      alert("Request Failed, Please check your code and try again!");
    },
  });
}

function check_category(category) {
  var base_url = $("#base_url").val();
  var csrf_test_name = $('[name="csrf_test_name"]').val();
  var myurl = $("#posurl").val();
  $.ajax({
    type: "post",
    async: false,
    url: myurl,
    data: { category_id: category, csrf_test_name: csrf_test_name },
    success: function (data) {
      if (data == "420") {
        $("#product_search").html(data);
      } else {
        $("#product_search").html(data);
      }
    },
    error: function () {
      alert("Request Failed, Please check your code and try again!");
    },
  });
}

function image_activation(id) {
  var qty = $("#total_qntt_" + id).val();
  $("#image-active_" + id).addClass("active");
  $("#image-active_count_" + id).addClass("quantity");
  var active_product = $("#active_pro_" + id).text(qty);
}

("use strict");
function checkallCategory() {
  $("#box-0").change(function () {
    var checked = $(this).is(":checked");
    if (checked) {
      $(".cat-check").each(function () {
        $(this).prop("checked", true);
        check_category();
      });
    } else {
      $(".cat-check").each(function () {
        $(this).prop("checked", false);
        check_category();
      });
    }
  });
}

$("body").on("click", "#search_button", function () {
  var product_name = $("#product_name").val();
  var csrf_test_name = $('[name="csrf_test_name"]').val();
  var category_id = $("#category_id").val();
  var myurl = $("#posurl").val();
  $.ajax({
    type: "post",
    async: false,
    url: myurl,
    data: {
      product_name: product_name,
      category_id: category_id,
      csrf_test_name: csrf_test_name,
    },
    success: function (data) {
      if (data == "420") {
        $("#product_search").html(
          '<h1 class"srcalrt text-center">Product not found !</h1>'
        );
      } else {
        $("#product_search").html(data);
      }
    },
    error: function () {
      alert("Request Failed, Please check your code and try again!");
    },
  });
});

("use strict");
function detailsmodal(productname, stock, model, unit, price, image) {
  $("#detailsmodal").modal("show");
  var base_url = document.getElementById("baseurl").value;
  document.getElementById("modal_productname").innerHTML = productname;
  document.getElementById("modal_productstock").innerHTML = stock;
  document.getElementById("modal_productmodel").innerHTML = model;
  document.getElementById("modal_productunit").innerHTML = unit;
  document.getElementById("modal_productprice").innerHTML = price;
  document.getElementById("modalimg").innerHTML =
    '<img src="' + image + '" alt="image" style="width:100px; height:60px;" />';
}

let currentEditingProductId = null;

function updateProductModal(productname, stock, model, unit, price, productId) 
{
    // $("#updated_product").modal("show");
    currentEditingProductId = productId;
    var totalPriceElement = document.getElementById("total_price_" + productId);
    var quantity = document.getElementById("total_qntt_" + productId);
    var discount = document.getElementById("discount_" + productId);
    var vat = document.getElementById("vat_percent_" + productId);
    var vat_value = document.getElementById("vat_value_" + productId);
    var discount_value = document.getElementById("discount_value_" + productId);
    if (totalPriceElement) {
      console.log("totalPrice:", totalPriceElement.value);
    } else 
    {
      console.warn("Element with ID total_price_" + productId + " not found!");
    }
    document.getElementById("pmodel_rate").value = price;
    document.getElementById("pmodel_item_qty").value = quantity.value;
    document.getElementById("total_price_").innerHTML = totalPriceElement.value;
    var base_url = document.getElementById("baseurl").value;
    document.getElementById("pmodel_product_name").innerHTML = productname;
    document.getElementById("pmodel_quantity").value = quantity.value;
    document.getElementById("pmodel_discount").value = discount.value;
    document.getElementById("pmodel_discount_value").value = discount_value.value;
    document.getElementById("pmodel_vat").value = vat.value;
    document.getElementById("pmodel_vat_value").value = vat_value.value;
    quantity_calculate(productId)
}

function applyProductUpdate() 
{
  const productId = currentEditingProductId;

  const qty = document.getElementById("pmodel_quantity").value || 0;
  const rate = document.getElementById("pmodel_rate").value || 0;
  const discount = document.getElementById("pmodel_discount").value || 0;
  const discountValue = document.getElementById("pmodel_discount_value").value || 0;
  const vat = document.getElementById("pmodel_vat").value || 0;
  const vatValue = document.getElementById("pmodel_vat_value").value || 0;
  const invoiceDiscount = document.getElementById("invoice_discount_percent").value || 0;

  // Update values in table row fields
  document.getElementById("total_qntt_" + productId).value = qty;
  document.getElementById("price_item_" + productId).value = rate;
  document.getElementById("discount_" + productId).value = discount;
  document.getElementById("discount_value_" + productId).value = discountValue;
  document.getElementById("vat_percent_" + productId).value = vat;
  document.getElementById("vat_value_" + productId).value = vatValue;
  document.getElementById("vat_amount_").innerHTML = vatValue;
  document.getElementById("total_discount_amount").innerHTML = invoiceDiscount;

  // Calculate new total price
  const total = (qty * rate) - discountValue + parseFloat(vatValue);
  document.getElementById("total_price_" + productId).value = total.toFixed(2);
  quantity_calculate(productId)

  // Optional: close modal if needed
  $('#updated_product').modal('hide');
  $('#discount_modal').modal('hide');
}

$(document).on("click", ".taxbutton", function (e) {
  var $this = $(this);
  var icon = $this.find("i");
  if (icon.hasClass("fa fa-angle-double-up")) {
    $this
      .find("i")
      .removeClass("fa fa-angle-double-up")
      .addClass("fa fa-angle-double-down");
  } else {
    $this
      .find("i")
      .removeClass("fa fa-angle-double-down")
      .addClass("fa fa-angle-double-up");
  }
});

$(document).ready(function () {
  $(".paymentpart").click(function () {
    var $header = $(this);
    var $content = $header.next();
    $content.slideToggle(500, function () {
      $header.html(function () {
        return $content.is(":visible")
          ? "<span  class='btn btn-warning'><i class='fa fa-angle-double-down'></i></span>"
          : "<span  class='btn btn-warning'><i class='fa fa-angle-double-up'></i></span>";
      });
    });
  });
});

("use strict");
function bank_info_show(payment_type) {
  if (payment_type.value == "1") {
    document.getElementById("bank_info_hide").style.display = "none";
  } else {
    document.getElementById("bank_info_hide").style.display = "block";
  }
}

("use strict");
function active_customer(status) {
  if (status == "payment_from_2") {
    document.getElementById("payment_from_2").style.display = "none";
    document.getElementById("payment_from_1").style.display = "block";
    document.getElementById("myRadioButton_2").checked = false;
    document.getElementById("myRadioButton_1").checked = true;
  } else {
    document.getElementById("payment_from_1").style.display = "none";
    document.getElementById("payment_from_2").style.display = "block";
    document.getElementById("myRadioButton_2").checked = false;
    document.getElementById("myRadioButton_1").checked = true;
  }
}

$(document).ready(function () {
  "use strict";
  $("#addinvoice .toggle").on("click", function () {
    $("#addinvoice .hideableRow").toggleClass("hiddenRow");
  });
  $(".bankpayment").css("width", "100%");
});

("use strict");
function bank_paymet(val) {
  if (val == 2) {
    var style = "block";
    document.getElementById("bank_id").setAttribute("required", true);
  } else {
    var style = "none";
    document.getElementById("bank_id").removeAttribute("required");
  }

  document.getElementById("bank_div").style.display = style;
}

/*pos invoice part*/
$(document).ready(function () {
  "use strict";
  var barcodeScannerTimerP;
  var barcodeStringPos = "";
  $("#add_item_m_p").keydown(function (e) {
    if (e.keyCode == 13) {
      var product_id = $(this).val();
      var product_id = $(this).val();
      var exist = $("#SchoolHiddenId_" + product_id).val();
      var qty = $("#total_qntt_" + product_id).val();
      var add_qty = parseInt(qty) + 1;
      var csrf_test_name = $('[name="csrf_test_name"]').val();
      var base_url = $("#base_url").val();
      if (product_id == exist) {
        $("#total_qntt_" + product_id).val(add_qty);
        quantity_calculate(product_id);
        calculateSum();
        invoice_paidamount();
        document.getElementById("add_item_m_p").value = "";
        document.getElementById("add_item_m_p").focus();
      } else {
        $.ajax({
          type: "post",
          async: false,
          url: base_url + "invoice/invoice/insert_pos_invoice",
          data: { product_id: product_id, csrf_test_name: csrf_test_name },
          success: function (data) {
            if (data == false) {
              alert("This Product Not Found !");
              document.getElementById("add_item_m_p").value = "";
              document.getElementById("add_item_m_p").focus();
              quantity_calculate(product_id);
              calculateSum();
              invoice_paidamount();
            } else {
              $("#hidden_tr").css("display", "none");
              document.getElementById("add_item_m_p").value = "";
              document.getElementById("add_item_m_p").focus();
              $("#addinvoice tbody").append(data);
              quantity_calculate(product_id);
              calculateSum();
              invoice_paidamount();
            }
          },
          error: function () {
            alert("Request Failed, Please check your code and try again!");
          },
        });
      }
    }
  });

  // capture barcode scanner input
  $("#add_item_p").on("keypress", function (e) {
    barcodeStringPos = barcodeStringPos + String.fromCharCode(e.charCode);
    clearTimeout(barcodeScannerTimerP);
    barcodeScannerTimerP = setTimeout(function () {
      processBarcodePosinvoice();
    }, 300);
  });

  ("use strict");
  function processBarcodePosinvoice() {
    if (barcodeStringPos != "") {
      var product_id = barcodeStringPos;
      var exist = $("#SchoolHiddenId_" + product_id).val();
      var qty = $("#total_qntt_" + product_id).val();
      var add_qty = parseInt(qty) + 1;
      var csrf_test_name = $('[name="csrf_test_name"]').val();
      var base_url = $("#base_url").val();
      if (product_id == exist) {
        $("#total_qntt_" + product_id).val(add_qty);
        quantity_calculate(product_id);
        calculateSum();
        invoice_paidamount();
        document.getElementById("add_item_p").value = "";
        document.getElementById("add_item_p").focus();
      } else {
        $.ajax({
          type: "post",
          async: false,
          url: base_url + "invoice/invoice/insert_pos_invoice",
          data: { product_id: product_id, csrf_test_name: csrf_test_name },
          success: function (data) {
            if (data == false) {
              alert("This Product Not Found !");
              document.getElementById("add_item_p").value = "";
              document.getElementById("add_item_p").focus();
              quantity_calculate(product_id);
              calculateSum();
              invoice_paidamount();
            } else {
              $("#hidden_tr").css("display", "none");
              document.getElementById("add_item_p").value = "";
              document.getElementById("add_item_p").focus();
              $("#addinvoice tbody").append(data);
              quantity_calculate(product_id);
              calculateSum();
              invoice_paidamount();
            }
          },
          error: function () {
            alert("Request Failed, Please check your code and try again!");
          },
        });
      }
    } else {
      alert("barcode is invalid: " + barcodeStringPos);
    }

    barcodeStringPos = ""; // reset
  }
});

$(document).ready(function () {
  "use strict";
  var frm = $("#pos_sale_insert");
  var output = $("#output");
  frm.on("submit", function (e) {
    e.preventDefault();
    $.ajax({
      url: $(this).attr("action"),
      method: $(this).attr("method"),
      dataType: "json",
      data: frm.serialize(),
      success: function (data) {
        if (data.status == true) {
          toastr["success"](data.message);
          $("#image-active_count_" + 54258082).removeClass("quantity");
          $("#inv_id").val(data.invoice_id);
          $("#printconfirmodal").modal("show");
          $("#pos_sale_insert").trigger("reset");
          if (data.status == true && event.keyCode == 13) {
          }
        } else {
          toastr["error"](data.exception);
        }
      },
      error: function (xhr) {
        alert("failed!");
      },
    });
  });
});

$("#printconfirmodal").on("keydown", function (e) {
  var key = e.which || e.keyCode;
  if (key == 13) {
    $("#yes").trigger("click");
  }
});

function cancelprint() {
  location.reload();
}

("use strict");
function invoice_productList(sl) {
  var csrf_test_name = $('[name="csrf_test_name"]').val();
  var base_url = $("#base_url").val();
  var priceClass = "price_item" + sl;
  var available_quantity = "available_quantity_" + sl;
  var unit = "unit_" + sl;
  var tax = "total_tax_" + sl;
  var serial_no = "serial_no_" + sl;
  var discount_type = "discount_type_" + sl;

  // Auto complete
  var options = {
    minLength: 0,
    source: function (request, response) {
      var product_name = $("#product_name_" + sl).val();
      $.ajax({
        url: base_url + "invoice/invoice/bdtask_autocomplete_product",
        method: "post",
        dataType: "json",
        data: {
          term: request.term,
          product_name: product_name,
          csrf_test_name: csrf_test_name,
        },
        success: function (data) {
          response(data);
        },
      });
    },
    focus: function (event, ui) {
      $(this).val(ui.item.label);
      return false;
    },
    select: function (event, ui) {
      $(this)
        .parent()
        .parent()
        .find(".autocomplete_hidden_value")
        .val(ui.item.value);
      $(this).val(ui.item.label);
      var sl = $(this).parent().parent().find(".sl").val();
      var id = ui.item.value;
      var dataString = "product_id=" + id;
      var base_url = $(".baseUrl").val();

      $.ajax({
        type: "POST",
        url: base_url + "invoice/invoice/retrieve_product_data_inv",
        data: { product_id: id, csrf_test_name: csrf_test_name },
        cache: false,
        success: function (data) {
          var obj = jQuery.parseJSON(data);
          for (var i = 0; i < obj.txnmber; i++) {
            var txam = obj.taxdta[i];
            var txclass = "total_tax" + i + "_" + sl;
            $("." + txclass).val(obj.taxdta[i]);
          }
          $("." + priceClass).val(obj.price);
          $("." + available_quantity).val(obj.total_product.toFixed(2, 2));
          $("." + unit).val(obj.unit);
          $("." + tax).val(obj.tax);
          $("#txfieldnum").val(obj.txnmber);
          $("#" + serial_no).html(obj.serial);
          $("#" + discount_type).val(obj.discount_type);

          //This Function Stay on others.js page
          quantity_calculate(sl);
        },
      });

      $(this).unbind("change");
      return false;
    },
  };

  $("body").on("keypress.autocomplete", ".productSelection", function () {
    $(this).autocomplete(options);
  });
}

window.onload = function () {
  $("body").addClass("sidebar-mini sidebar-collapse");
};

$(".product-grid").each(function () {
  const ps = new PerfectScrollbar($(this)[0]);
});

$(document).ready(function () {
  Mousetrap.bind("ctrl+s", function (e) {
    if (e.preventDefault) {
      e.preventDefault();
    } else {
      e.returnValue = false;
    }
    $("#add_invoice").trigger("click");
  });

  Mousetrap.bind("shift+c", function () {
    $("#cust_info").modal();
    setTimeout(function () {
      $("#m_customer_name").focus();
    }, 500);
  });

  Mousetrap.bind("shift+f", function () {
    $("#full_paid_tab").trigger("click");
  });

  Mousetrap.bind("shift+l", function () {
    $("#todays_salelist").trigger("click");
  });
  Mousetrap.bind("shift+n", function () {
    $("#new_sale").trigger("click");
  });

  Mousetrap.bind("alt+c", function () {
    $("#calculator_modal").trigger("click");
  });
  Mousetrap.bind("alt+n", function () {
    $("#customer_name").focus();
  });

  Mousetrap.bind("ctrl+d", function (e) {
    if (e.preventDefault) {
      e.preventDefault();
    } else {
      e.returnValue = false;
    }
    $("#invoice_discount").focus();
  });

  Mousetrap.bind("alt+p", function () {
    $("#paidAmount").focus();
  });

  Mousetrap.bind("alt+s", function () {
    $("#shipping_cost").focus();
  });
});
function printRawHtml(view) {
  printJS({
    printable: view,
    type: "raw-html",
    onPrintDialogClose: printJobComplete(),
  });
}

function printJobComplete() {
  var invoice_no = $("#gui_invoice_no").text();
  var nextinvoice = parseInt(invoice_no) + +1;
  $("#addinvoice tbody tr").remove();
  $("#gui_sale_insert").trigger("reset");
  $("#n_total").val("");
  $("#net_total_text").text("0.00");
  $("#dueAmmount").val("");
  $("#due_text").text("0.00");
  invoice_no_check();
}

function invoice_no_check() {
  var base_url = $("#base_url").val();
  $.ajax({
    url: base_url + "invoice/invoice/number_generator_ajax",
    method: "GET", // Use 'GET' as the HTTP method
    dataType: "json", // Specify the expected data type
    success: function (msg) {
      $("#gui_invoice_no").text(msg);
      $("#invoice_no").val(msg);
      console.log(msg);
    },
    error: function (xhr, desc, err) {
      alert("Failed to fetch invoice number. Please try again.");
      console.error("Error:", err);
    },
  });
}

function invoice_product_batch(sl) {
  var base_url = $(".baseUrl").val();
  var csrf_test_name = $('[name="csrf_test_name"]').val();
  var prod_id = $(".product_id_" + sl).val();
  var batch_no = $("#serial_no_" + sl).val();
  var taxnumber = $("#txfieldnum").val();
  var available_quantity = $(".available_quantity_" + sl).val();

  $.ajax({
    url: base_url + "invoice/invoice/bdtask_batchwise_productprice",
    method: "post",
    dataType: "json",
    data: {
      prod_id: prod_id,
      batch_no: batch_no,
      csrf_test_name: csrf_test_name,
    },
    success: function (data) {
      if (parseInt(data) >= 0) {
        $(".available_quantity_" + sl).val(data.toFixed(2, 2));
      } else {
        var message = "You can Sale maximum " + available_quantity + " Items";
        toastr["error"](message);
        $("#total_qntt_" + sl).val("");
        var quantity = 0;
        $("#total_price_" + sl).val(0);
        for (var i = 0; i < taxnumber; i++) {
          $("#all_tax" + i + "_" + sl).val(0);
          quantity_calculate(sl);
        }
      }
    },
  });
}

function check_creditsale() {
  var card_typesl = $(".card_typesl").val();
  console.log({ card_typesl });
  if (card_typesl == 0) {
    $("#add_new_payment").empty();
    var gtotal = $(".grandTotalamnt").val();
    $("#pamount_by_method").val(gtotal);
    $("#paidAmount").val(0);
    $("#dueAmmount").val(gtotal);
    $(".number:eq(0)").val(0);
    $("#add_new_payment_type").prop("disabled", true);
  } else {
    $("#add_new_payment_type").prop("disabled", false);
  }
  $("#pay-amount").text("0");

  var invoice_edit_page = $("#invoice_edit_page").val();
  var is_credit_edit = $("#is_credit_edit").val();
  if (invoice_edit_page == 1 && card_typesl == 0) {
    $("#add_new_payment").empty();

    var base_url = $("#base_url").val();
    var csrf_test_name = $('[name="csrf_test_name"]').val();
    var gtotal = $(".grandTotalamnt").val();
    var url = base_url + "invoice/invoice/bdtask_showpaymentmodal";
    $.ajax({
      type: "post",
      url: url,
      data: { csrf_test_name: csrf_test_name, is_credit_edit: is_credit_edit },
      success: function (data) {
        $("#add_new_payment").append(data);
        $("#pamount_by_method").val(gtotal);
        $("#add_new_payment_type").prop("disabled", true);
      },
    });
  }
}
