$(document).ready(function () {
  $("body").off("click").on("click", ".remove", remove);
  $("body").on("blur", ".timesheetno", chkSheetno);
  $("body").on("keyup", ".frmtime, .totime", timeAlert);
  $("body").on("blur change", ".vouchdt", chgFrmdt);
  $(".tbody").on("blur change", ".frmdt", chgTodt);
  $(".tbody").on("blur change", ".frmtime, .totime,.type, .frmdate, .rate, .otamt, .todate, .vouchdt, .amount", chkTime);
  $(".tbody").on("blur", '.otamt', autoAddRows);
  // $("body").on("blur", '.voucher', autoManNo);
  // autoManNo();
  // function autoManNo () {
  //   var vouchVal = $('.voucher').val();
  //   $('.manualno').val(vouchVal);
  // }
  
  function chgFrmdt() {
      vouchdt = $(".vouchdt").val();
      $(".frmdt").val(vouchdt);
  }
    // When the image is clicked, open the modal
    $("#openModal").click(function(){
      $("#myModal").fadeIn();
    });
    
    // When the close button is clicked, close the modal
    $(".close-btn").click(function(){
      $("#myModal").fadeOut();
    });
    
    // Close the modal if the user clicks outside of the modal content
    $(window).click(function(event){
      if ($(event.target).is("#myModal")) {
        $("#myModal").fadeOut();
      }
    });

  $("form").submit(function () {
    $('.rate').prop('disabled', false);
    $('.chalamt').prop('disabled', false);
    $('.frmtime').prop('disabled', false);
    $('.totime').prop('disabled', false);
    $('.nohrs').prop('disabled', false);
    $('.nomin').prop('disabled', false);
    $('.otamt').prop('disabled', false);
    var date = $('.vouchdt').val();
    var stdate = $('.zstdate').val();
    var endate = $('.zenddate').val();
    var amount = $('.chalamt').val();

    if (amount <= 0) {
        alert("Amount Cannot Be 0 (Zero)");
        return false;
    }

    if (date != '') {
        if (date >= stdate && date <= endate) {
        } else {
            alert("Date Does Not Belong To Finacial Year");
            $(".vouchdt").val("0000-00-00");
            $(".vouchdt").focus();
            return false;
        }
    }
});

  function chgTodt() {
    var $row = $(this).closest("tr");
    var type = $row.find(".type").val(),
      frmdt = $row.find(".frmdt").val();
    if (type == "H") {
      $row.find(".todt").val(frmdt);
    }
  }

  function timeAlert() {
            $(this).val($(this).val().replace(/\D/g, '').substring(0, 4));
        }

  function chkSheetno() {
    var timesheetno = $(".timesheetno").val();
    $.post("chkSheetno.php", { timesheetno: timesheetno }, function (data) {
      m = data;
      if (m == 1) {
        $(".timesheetno").val("");
        alert("Time Sheet No Already Exist");
        $(".timesheetno").focus();
      }
    });
  }

  function chkTime() {
    var tr = $(this).closest("tr");
    var type = tr.find('.type').val();
    var party = $('.party').val();

    if (type == 'H') {
        tr.find('.chalamt').attr('readonly', true).attr('disabled', true);
        tr.find('.frmtime').removeAttr('readonly').removeAttr('disabled');
        tr.find('.totime').removeAttr('readonly').removeAttr('disabled');
        tr.find('.nomin').attr('readonly', true).attr('disabled', true);
        tr.find('.nohrs').attr('readonly', true).attr('disabled', true);
        tr.find('.rate').removeAttr('readonly').removeAttr('disabled');
    let ftime = tr.find('.frmtime').val();
    let ttime = tr.find('.totime').val();

    const timeRegex = /^(?:[01]\d|2[0-3])(?:00|15|30|45)$/;

    // Validate From Time
    if (ftime != '') {
        if (!timeRegex.test(ftime)) {
            tr.find('.frmtime').val('');
            alert('Please enter a valid time in 24-hour format at 15-minute intervals (e.g., 0015, 0030).');
            tr.find('.frmtime').focus();
            return;
        }
    }

    // Validate To Time
    if (ttime != '') {
        if (!timeRegex.test(ttime)) {
            tr.find('.totime').val('');
            alert('Please enter a valid time in 24-hour format at 15-minute intervals (e.g., 0015, 0030).');
            tr.find('.totime').focus();
            return;
        }
    }

      $.ajax({
        type: "POST",
        dataType: "json",
        url: "get_party_rate.php",
        data: {party: party},
        success: function (response) {
          if (response != "") {
            var rate = response.rate,
                crewot = response.crewot,
                crewot2 = response.crewot2;
        
            var fcheck = tr.find(".frmtime").val();
            var tcheck = tr.find(".totime").val();
        
            var fcheckNum = parseInt(fcheck, 10);
            var tcheckNum = parseInt(tcheck, 10);
        
            // Set rate if empty or zero
            if (tr.find(".rate").val() === '' || tr.find(".rate").val() === '0') {
                tr.find(".rate").val(rate);
            }
            // Set otamt only if it's empty or zero
            if (tr.find(".otamt").val() === '' || tr.find(".otamt").val() === '0' || tr.find(".otamt").val() === '0.00') {
                // Special case: fcheck between 1800-2215 AND tcheck between 2230-0800
                if ((fcheckNum >= 1800 && fcheckNum <= 2215) && (tcheckNum >= 2230 || tcheckNum <= 800)) {
                    tr.find(".otamt").val(crewot2);
                // If fcheck or tcheck between 1800-2215
                } else if ((fcheckNum >= 1800 && fcheckNum <= 2215) || (tcheckNum >= 1800 && tcheckNum <= 2215)) {
                    tr.find(".otamt").val(crewot);
                // If fcheck or tcheck between 2230-0800
                } else if ((fcheckNum >= 2230 || fcheckNum <= 745) || (tcheckNum >= 2230 || tcheckNum <= 745)) {
                    tr.find(".otamt").val(crewot2);
                } else {
                    tr.find(".otamt").val('');
                }
            }
        }
        //   if (response != "") {
        //     var rate = response.rate,
        //         crewot = response.crewot,
        //         crewot2 = response.crewot2;
        
        //     var fcheck = tr.find(".frmtime").val();
        //     var tcheck = tr.find(".totime").val();
        
        //     var fcheckNum = parseInt(fcheck, 10);
        //     var tcheckNum = parseInt(tcheck, 10);
        
        //     // Set rate if empty or zero
        //     if (tr.find(".rate").val() === '' || tr.find(".rate").val() === '0') {
        //         tr.find(".rate").val(rate);
        //     }
        
        //     // Set otamt only if it's empty or zero
        //     if (tr.find(".otamt").val() === '' || tr.find(".otamt").val() === '0' || tr.find(".otamt").val() === '0.00') {
        //         if (tcheckNum >= 1800 && tcheckNum <= 2215) {
        //             tr.find(".otamt").val(crewot);
        //         } else if (tcheckNum >= 2230 || tcheckNum <= 800) {
        //             tr.find(".otamt").val(crewot2);
        //         } else {
        //             tr.find(".otamt").val('');
        //         }
        //     }
        // }
            // if (response != "") {
            //     var rate = response.rate,
            //     crewot = response.crewot,
            //             crewot2 = response.crewot2;
            //             var fcheck = tr.find(".frmtime").val();
            //             var tcheck = tr.find(".totime").val();
            //             if (tr.find(".rate").val() == '' || tr.find(".rate").val() == '0') {
            //               tr.find(".rate").val(rate);
            //           }  
            //           if (tr.find(".otamt").val() == '' || tr.find(".otamt").val() == '0') {
            //             var fcheckNum = parseInt(fcheck, 10);
            //             var tcheckNum = parseInt(tcheck, 10);
                    
            //             if (fcheckNum >= 1700 && tcheckNum <= 2200 && tcheckNum > fcheckNum) {
            //                 tr.find(".otamt").val(crewot);
            //             } else if ((fcheckNum >= 2200 && fcheckNum <= 2359) || (fcheckNum >= 0 && fcheckNum < 800) ||
            //                        (tcheckNum >= 2200 && tcheckNum <= 2359) || (tcheckNum >= 0 && tcheckNum < 800)) {
            //                 tr.find(".otamt").val(crewot2);
            //             } else {
            //                 tr.find(".otamt").val('');
            //             }
            //         }
            // }
        },
        error: function (request, textStatus, errorThrown) {
        },
    });

    var startDate = new Date(tr.find('.frmdt').val());
    var endDate = new Date(tr.find('.todt').val());
    var addFlag = tr.find('.addflag').val();
    if (addFlag != 1) {
        if (isNaN(startDate) || isNaN(endDate)) {
            alert('Please select valid dates.');
            return false;
        }
    }

    // Check if From Time and To Time are the same
    if (ftime === ttime && startDate === endDate) {
        alert('From Time & To Time Cannot Be Same');
        tr.find('.totime').val('');
        tr.find('.totime').focus();
        return false;
    }

    // Convert time to minutes
    const timeToMinutes = (time) => {
        const hours = parseInt(time.slice(0, 2), 10);
        const minutes = parseInt(time.slice(2), 10);
        return hours * 60 + minutes;
    };

    const fromMinutes = timeToMinutes(ftime);
    const toMinutes = timeToMinutes(ttime);

    // Handle Cross-Day Scenarios
    

    const dayDifference = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));

    let totalMinutes = toMinutes - fromMinutes;

    // Adjust for cross-day scenarios
    if (dayDifference > 0) {
        totalMinutes += dayDifference * 24 * 60;
    } else if (toMinutes < fromMinutes) {
        alert('To Time cannot be earlier than From Time');
        tr.find('.totime').val('');
        tr.find('.totime').focus();
        return false;
    }

    // Calculate hours and minutes
    const nohrs = Math.floor(totalMinutes / 60);
    const nomin = totalMinutes % 60;


    tr.find('.nohrs').val(nohrs);
    tr.find('.nomin').val(nomin);

    var rate = parseFloat(tr.find('.rate').val()) || 0;
var otamt = parseFloat(tr.find('.otamt').val()) || 0;
// var totalMinutes = nohrs * 60 + nomin;

var rateMultiplier = 0;

// Handle the quarter-hour-based calculations
if (totalMinutes % 60 === 15) {
    rateMultiplier = nohrs + 0.25;
} else if (totalMinutes % 60 === 30) {
    rateMultiplier = nohrs + 0.5;
} else if (totalMinutes % 60 === 45) {
    rateMultiplier = nohrs + 0.75;
} else {
    rateMultiplier = totalMinutes / 60; // Default exact fraction for anything else
}
var calcamt = rate * rateMultiplier; 
 tr.find(".calcamt").val(calcamt);
 var roundcalCamt = Math.round(calcamt);
var amount = roundcalCamt + otamt;
tr.find('.amount').val(amount.toFixed(2));

    // var rate = parseInt(tr.find('.rate').val()); 
    // var otamt = parseInt(tr.find('.otamt').val()); 
    // var totalHours = nohrs + nomin / 60;
    // var amount = rate * totalHours + otamt;
    // tr.find('.amount').val(amount.toFixed(2));   
    
calMain ();
} else {
  // tr.find('.frmtime').attr('readonly', true).attr('disabled', true);
  // tr.find('.totime').attr('readonly', true).attr('disabled', true);
  tr.find('.nomin').attr('readonly', true).attr('disabled', true);
  tr.find('.nohrs').attr('readonly', true).attr('disabled', true);
    tr.find('.rate').attr('readonly', true).attr('disabled', true);
    tr.find('.otamt').attr('readonly', true).attr('disabled', true);
    tr.find('.amount').removeAttr('readonly').removeAttr('disabled');
    // if (tr.find('.amount').val() <= 0) {
    // tr.find('.amount').focus();
    // }
    calMain ();
}
  }

  function calMain () {
    var val = 0;
            $(".amount").each(function () {
              if (!isNaN(this.value) && this.value.length != 0) {
                  val += parseFloat(this.value);
              }
          });
          var tot = parseFloat(val);
          $('.chalamt').val(tot);
  }

  $("#addnew").click(function () {
    AddRows();
  });

  function autoAddRows() {
    var ctr = $("#items").val();
    var tr = $(this).closest("tr");
    var srno = tr.find(".srno").val();
    if (srno == ctr) {
      AddRows();
    }
  }

  function remove() {
    $(this).closest("tr").remove();
    chkTime();
  }

  function AddRows() {
    var ctr = $("#items").val();
    var hide_check = "";
    if ($("#del_all").prop("checked")) {
      hide_check = 0;
    } else {
      hide_check = 1;
    }
    var detail = ".fetchpart_" + ctr;
    var detail2 = ".fetchpart2_" + ctr;
    $.post("challan_add.php", { ctr: ctr, hide: hide_check }, function (data) {
      $(data).appendTo(".tbody");
      ctr++;
      $("#items").val(ctr);
      $(detail).select2();
      $(detail2).select2();
      $(detail).focus();
    });
  }
});
