$(document).ready(function () {

  // Check/Uncheck All
  $("#shipchkall").click(function () {
    $(".selectchk").prop("checked", $(this).prop("checked"));

    if ($(this).prop("checked")) {
      $(".shiptable tr").addClass("selected");
    } else {
      $(".shiptable tr").removeClass("selected");
    }
  });

  // Row click toggle
  $(document).on("click", ".shiptable tr", function (e) {
    if (!$(e.target).is("input[type=checkbox]")) {
      let chk = $(this).find(".selectchk");
      chk.prop("checked", !chk.prop("checked"));
    }

    $(this).toggleClass("selected", $(this).find(".selectchk").prop("checked"));
  });

  $(document).off("click", ".sendwhatsapp").on("click", ".sendwhatsapp", function () {
    var selected = [];

    $(".shiptable tr").each(function () {
      if ($(this).find(".selectchk").is(":checked")) {
        var row = [];
        $(this).find("td").each(function (i) {
          if (i > 0) { // skip checkbox column
            row.push($(this).text().trim());
          }
        });
        selected.push(row);
      }
    });

    if (selected.length === 0) {
      alert("Please select at least one row.");
      return;
    }

    var mobileno = $("#mobileno").val();
    var customer = $("#customer").val();

    $.ajax({
      url: "generate_excel_csv.php",
      type: "POST",
      data: { rows: JSON.stringify(selected), mobileno: mobileno, customer: customer },
      success: function (res) {
        alert("Excel sent to WhatsApp!");
        // console.log(res);
        location.reload();
      }
    });
  });





});
