$(document).ready(function () {
  $("body").off("click").on("click", ".remove", remove);
  $("body").on("click", ".createsched", createSchedule);
  $("body").on("click", ".aprov", selDate);
  $("body").on("click", ".treatdet", getTreatDet);
  $("body").on("click", ".saverec", saveRec);
  $("body").on("change blur", ".treatment", getRate);
  $("body").on("change", ".medicine", getMedRate);
  $("body").on("change keyup blur", ".qty,.treatment, .aprvqty, .rate", calAmt);
  $("body").on("change keyup blur", ".mqty, .mrate", calMAmt);
  $("body").on(
    "click blur",
    ".remove, .consultfees, .aprov, .discamt, .invdt, .meddiscamt, .meddiscperc,.trdiscamt, .trdiscperc",
    MainCal
  );
  //   $("body").on("change keyup blur", ".discamt", discount);
  $("body").on("click", "#addnewpay", openPay);
  $("body").on("click", ".savdep", savDeposit);
  $("body").on("change", ".trpaytype", shwHide);


//   $('.nav-tabs li a').click(function(e) {
//     e.preventDefault(); // Prevent default behavior

//     var $clickedTab = $(this).parent(); // Get the clicked tab's <li>
    
//     if ($clickedTab.hasClass('active')) {
//         // If clicked tab is already active, toggle other tabs
//         $('.nav-tabs li').not($clickedTab).toggle();
//     } else {
//         // Make clicked tab active and show it, hide others
//         $('.nav-tabs li').removeClass('active').hide(); // Hide all tabs
//         $clickedTab.addClass('active').show(); // Show only the clicked tab
//     }
// });


  shwHide();
  function shwHide() {
    var trpaytype = $(".trpaytype").val();
    if (trpaytype == "I") {
      $(".insttable").show();
    } else {
      $(".insttable").hide();
    }
  }
  function savDeposit() {
    var party = $(".party").val(),
      vouchno = $(".vouchno").val(),
      paydate = $(".paydate").val(),
      bankname = $(".bankname").val(),
      recvamt = $(".recvamt").val();
    $.post(
      "savePayment.php",
      {
        recvamt: recvamt,
        party: party,
        vouchno: vouchno,
        bankname: bankname,
        paydate: paydate,
      },
      function (data) {
        if (data > 0) {
          location.reload();
        }
      }
    );
  }

  var invdate = $(".invdt").val();
  if (invdate == "0000-00-00" || invdate == "") {
    $("#addnewpay").hide();
  }

  function openPay() {
    $(".addpayModal").modal("show");
  }

  $(".billprt").hide();

  $("#hedit").click(function () {
    $(".addflg").val("0");
  });

  $(".imgbef").change(function () {
    readURL1(this);
  });
  $(".imgaft").change(function () {
    readURL2(this);
  });

  $(".closeModal").on("click", function () {
    $("#pdfModal").modal("hide");
  });
  $(".visapdf").on("click", function () {
    // Get the PDF URL from the data attribute
    var pdfUrl = $(this).data("pdf-url");

    // Set the PDF URL in the iframe
    $("#pdfFrame").attr("src", pdfUrl);

    // Show the modal
    $("#pdfModal").modal("show");
  });

  function readURL1(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        $(".view1").attr("src", e.target.result);
      };

      reader.readAsDataURL(input.files[0]);
    }
  }
  function readURL2(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        $(".view2").attr("src", e.target.result);
      };

      reader.readAsDataURL(input.files[0]);
    }
  }

  function calMAmt() {
    var tr = $(this).closest("tr"),
      qty = tr.find(".mqty").val(),
      rate = tr.find(".mrate").val(),
      amt = Math.round(qty * rate);
    tr.find(".mamt").val(amt);
    MainCal();
  }
  function calAmt() {
    var tr = $(this).closest("tr"),
      qty = tr.find(".qty").val(),
      aprvrate = tr.find(".rate").val(),
      amt = Math.round(qty * aprvrate);
    tr.find(".amt").val(amt);
    MainCal();
  }
  function MainCal() {
    var tamt = 0;
    $(".caltreat").each(function () {
      // Assuming each row has a class 'row'
      var isChecked = $(this).find("input[type='checkbox']").is(":checked"); // Adjust the selector as needed

      if (isChecked) {
        $(this)
          .find(".amt")
          .each(function () {
            // Assuming .amt is within the same row
            if (!isNaN(this.value) && this.value.length != 0) {
              tamt += parseFloat(this.value);
            }
          });
      }
    });

    //        var tamt = 0;
    //        $(".amt").each(function () {
    //            if (!isNaN(this.value) && this.value.length != 0) {
    //                tamt += parseFloat(this.value);
    //            }
    //        });
    $(".treattotal").val(tamt);

    var namt = 0;
    $(".mamt").each(function () {
      if (!isNaN(this.value) && this.value.length != 0) {
        namt += parseFloat(this.value);
      }
    });
    $(".medtotal").val(namt);

    // commented by obaid

    var trdiscperc = $(".trdiscperc").val(),
      trdiscamt = $(".trdiscamt").val();
    if (parseFloat(trdiscamt) <= 0) {
      trdiscamt = (tamt * trdiscperc) / 100;
    }
    $(".trdiscamt").val(trdiscamt);
    var meddiscperc = $(".meddiscperc").val(),
      meddiscamt = $(".meddiscamt").val();
    if (parseFloat(meddiscamt) <= 0) {
      meddiscamt = (namt * meddiscperc) / 100;
    }
    $(".meddiscamt").val(meddiscamt);

    var discamt = parseFloat(meddiscamt) + parseFloat(trdiscamt);

    //        var newamount = tamt - trdiscamt,
    //                tmedamt = namt - meddiscamt;

    $(".discamt").val(discamt);
    $(".newamount").val(tamt);
    $(".tmedamount").val(namt);
    var consultfees = $(".consultfees").val(),
      subtot = parseFloat(consultfees) + parseFloat(tamt) + parseFloat(namt);
    $(".subtot").val(subtot);

    var billamt = parseFloat(subtot) - parseFloat(discamt);
    $(".billamt").val(billamt);
  }

  var invdate = $(".invdt").val();
  if (invdate === "") {
    $("#invprint").hide();
    $("#estprint").show();
  } else {
    $("#invprint").show();
    $("#estprint").hide();
  }

  //   function discount() {
  //     var discamt = $(".discamt").val(),
  //       subtotamt = $(".subtot").val(),
  //       discount = parsefloat(discamt) - parsefloat(subtotamt);
  //     $("billamt").val(discount);
  //   }

  function getMedRate() {
    var tr = $(this).closest("tr"),
      medicine = tr.find(".medicine").val();
    $.post(
      "getTreatDet.php",
      { medicine: medicine, paraM: "M" },
      function (data) {
        tr.find(".mrate").val(data);
      }
    );
  }

  function getRate() {
    var tr = $(this).closest("tr"),
      treatment = tr.find(".treatment").val();
    //        alert(1);
    $.post(
      "getTreatDet.php",
      { treatment: treatment, paraR: "R" },
      function (data) {
        tr.find(".treatrate").val(data);
      }
    );
  }

  function getTreatDet() {
    var tr = $(this).closest("tr"),
      vouchno = $(".vouchno").val(),
      vouchdt = $(".vouchdt").val(),
      accode = $(".accode").val(),
      addflg = $(".addflg").val(),
      scheddate = tr.find(".scheddate").val(),
      treatment = tr.find(".streatment").val();
    $.post(
      "getTreatDet.php",
      {
        vouchno: vouchno,
        vouchdt: vouchdt,
        accode: accode,
        scheddate: scheddate,
        treatment: treatment,
        addflg: addflg,
      },
      function (data) {
        $(".dettreatment").html(data);
        $(".detTreatModal").modal("show");
      }
    );
  }

  function saveRec() {
    var formData = {};
    $(".dettreatment")
      .find("input, textarea, select")
      .each(function () {
        var fieldName = $(this).attr("name");
        var fieldValue;
        var fieldType = $(this).attr("type"); // Get the type of the field

        // Only add to the object if the field has a name attribute

        if (fieldType === "checkbox" || fieldType === "radio") {
          // For checkboxes and radios, check if they are checked
          fieldValue = $(this).is(":checked") ? $(this).val() : null;
        } else {
          // For other fields (text, textarea, select), get the value directly
          fieldValue = $(this).val();
        }
        if (fieldName && fieldValue !== null) {
          formData[fieldName] = fieldValue;
        }
      });
    var jsonData = JSON.stringify(formData);
    var newv = 0;
    $.ajax({
      url: "saveTreatDet.php", // Replace with your server URL
      type: "POST",
      contentType: "application/json",
      data: jsonData,
      success: function (response) {
        //                console.log('Success:', response);
        var m = response;
        if (m.success == true) {
          //                    event.preventDefault();
          alert("Treatement Detail Saved");
          $(".detTreatModal").modal("hide");
        }
      },
      error: function (xhr, status, error) {
        console.error("Error:", status, error);
      },
    });
  }

  function selDate() {
    var tr = $(this).closest("tr");
    if (tr.find(".aprov").is(":checked")) {
    } else {
      tr.find(".firstdate").val("");
    }
  }

  function createSchedule() {
    var isChecked = false; // Flag to track if any checkbox is checked
    var vouchno = $(".vouchno").val();
    var schedcnt = $("#schedcnt").val();
    $(".treatbillbody")
      .find("tr")
      .each(function () {
        // Find the checkboxes within the current row
        var tr = $(this);
        var checkboxes = $(this).find('input[type="checkbox"]');
        var treatment = tr.find(".ftreatment").val(),
          qty = tr.find(".qty").val(),
          firstdate = tr.find(".firstdate").val(),
          duration = tr.find(".duration").val();
        // Check if any checkbox is checked
        if (checkboxes.is(":checked")) {
          isChecked = true; // Set the flag to true if a checked checkbox is found

          if (firstdate != "0000-00-00" || firstdate != "") {
            $.post(
              "createSchedule.php",
              {
                treatment: treatment,
                qty: qty,
                duration: duration,
                vouchno: vouchno,
                firstdate: firstdate,
              },
              function (data) {}
            );
          } else {
            alert("Select First Date For Ticked Appointment");
            return false;
          }

          //                return false; // Exit the loop early
        } else {
          $.post(
            "createSchedule.php",
            {
              treatment: treatment,
              qty: qty,
              duration: duration,
              vouchno: vouchno,
              firstdate: firstdate,
              para: "D",
            },
            function (data) {}
          );
        }
      });
    if (isChecked) {
      alert("Schedule Created.Check Under Schedule Tab");
      $.post(
        "genSchedule.php",
        { vouchno: vouchno, schedcnt: schedcnt },
        function (data) {
          if (data != "") {
            $(".schedbody").html("");
            $(data).appendTo(".schedbody");
            $(".tab5").show();
          }
        }
      );
    } else {
      alert("Approve Atleast One Treatment for Creating Schedule");
      return false;
    }
  }

  $("#submit").click(function () {
    $("#submit").hide();
  });
  $("form").submit(function () {
    var party = $(".party").val(),
      godown = $(".godown").val(),
      totbillamt = $(".totbillamt").val(),
      valid = true;
    if (party == "") {
      var message = "Party Cannot Be Empty";
      alert(message);
      $("#submit").show();
      return false;
      valid = false;
    }
    if (godown == "") {
      var message = "Godown Cannot Be Empty";
      alert(message);
      $("#submit").show();
      return false;
      valid = false;
    }

    if (parseFloat(totbillamt) <= 0 || totbillamt == "") {
      var message = "Netamt Cannot zero";
      alert(message);
      $("#submit").show();
      return false;
      valid = false;
    }

    if (valid) {
      var isValid = true;
      if (isValid) {
        $("#submit").hide();
        $("#cancel").hide();
      }
    }
  });
  $("#addsymp").click(function () {
    AddRowsSymp();
  });
  $("#addtreat").click(function () {
    AddRowsTreat();
  });
  $("#addmed").click(function () {
    AddRowsMed();
  });
  function remove() {
    $(this).closest("tr").remove();
    calDetail();
    caltran();
    mainCal();
  }

  function AddRowsMed() {
    var ctr = $("#medcnt").val();
    var hide_check = "",
      dosage = $(".medbody tr:last").find(".dosage").val();
    if ($("#del_all").prop("checked")) {
      hide_check = 0;
    } else {
      hide_check = 1;
    }
    var focusFld = ".focusFld_" + ctr;
    $.post(
      "med_add.php",
      { ctr: ctr, hide: hide_check, dosage: dosage },
      function (data) {
        $(data).appendTo(".medbody");
        $(focusFld).focus();
      }
    );
    ctr++;
    $("#medcnt").val(ctr);
  }

  function AddRowsSymp() {
    var ctr = $("#sympcnt").val();
    var prodtype = $(".prodtype").val();
    var hide_check = "";
    if ($("#del_all").prop("checked")) {
      hide_check = 0;
    } else {
      hide_check = 1;
    }
    var focusFld = ".focusFld_" + ctr;
    $.post(
      "symptoms_add.php",
      { ctr: ctr, hide: hide_check, prodtype: prodtype },
      function (data) {
        $(data).appendTo(".sympbody");
        $(focusFld).focus();
      }
    );
    ctr++;
    $("#sympcnt").val(ctr);
  }

  function AddRowsTreat() {
    var ctr = $("#treatcnt").val();
    var hide_check = "";
    if ($("#del_all").prop("checked")) {
      hide_check = 0;
    } else {
      hide_check = 1;
    }
    var focusFld = ".focusFld_" + ctr;
    var detail = ".fetchpart_" + ctr;
    $.post(
      "treatment_add.php",
      { ctr: ctr, hide: hide_check },
      function (data) {
        $(data).appendTo(".treatbody");
        ctr++;
        $("#treatcnt").val(ctr);
        $(focusFld).focus();
        //            alert(detail);
        //            $(detail).select2();
      }
    );
  }
});
