$(document).ready(function () {
    $("body").on("keyup blur change", ".vouchdt", getSaleData);
    $("body").on("blur change", ".frmdt", chgTodt);
    $("body").on("blur", ".timesheetno", chkSheetno);
    $("body").on("blur change", ".frmtime, .totime,.type, .frmdate, .todate, .vouchdt", chkTime);
    $("body").on("keyup", ".frmtime, .totime", timeAlert);
    $("body").on("keyup blur change", ".rate, .otamt", calMain);

    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();
            }
        });
    }

    // 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();
    }
  });

    $("pretcs").val();

    $("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);
        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;
            }
        }
    });

    getSaleData();
    function getSaleData() {
        var vouchdt = $(".vouchdt").val();
        var vehicle = $(".vehicle").val();
        var addflag = $(".addflag").val();
        $.post('get_sale_data.php', {vouchdt: vouchdt, addflag: addflag, vehicle: vehicle}, function (data) {
            $(".tbodyy").html(data);
        });
    }

    var addflag = $(".addflag").val(),
            par = $(".par").val();
    if (addflag == 1) {
        if (par == "A") {
            $(".PartySrchTbl").show();
            $(".party").focus();
        }
    }

    $('.srchparty').on('keydown', function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode == 40) {
            $(".PTbody tr:visible:first").find(".disblsrchparty").focus();
            e.preventDefault();
            return false;
        }
    });


    $(".PartySrchTbl").hide();
    $('.srchparty').on('keyup', function (e) {
        var value = $(".srchparty").val().toLowerCase();
        $(".PartySrchTbl").show();
        $(".PTbody tr").filter(function () {

            var tr = $(this).closest("tr");
            if (tr.find(".disblsrchparty").val().toLowerCase().substr(0, value.length) == value.substr(0, value.length)) {
                tr.show();
            } else {
                tr.hide();
            }

        });

    });

    $('.PartySrchTbl input').on('keydown', function (e) {

        var keyCode = e.keyCode || e.which;
        if (keyCode == 40) {
            $(this).closest("tr").nextAll().filter(":visible:first").find('.disblsrchparty').focus();
            e.preventDefault();
            return false;
        }

        if (keyCode == 38) {
            $(this).closest("tr").prevAll().filter(":visible:first").find('.disblsrchparty').focus();
            e.preventDefault();
            return false;
        }

        if (keyCode == 13) {
            var tr = $(this).closest("tr"),
                    partyname = tr.find(".disblsrchparty").val();
            $(".PartySrchTbl").hide();
            $.post('get_party_rate.php', {party: partyname}, function (data) {
                $(".rate").val(data);
            });
            $(".party").val(partyname);
            e.preventDefault();
            return false;
        }


        if (keyCode != 13 || keyCode != 18 || keyCode != 38) {
            e.preventDefault();
            return false;
        }
    });


    $(".disblsrchparty").click(function () {
        var tr = $(this).closest("tr"),
                partyname = tr.find(".disblsrchparty").val();
        $(".PartySrchTbl").hide();

        $(".party").val(partyname);
    });

    $("#hedit").click(function () {
        $(".pdf").hide();
    });

        function chgTodt() {
        var type = $(".type").val(),
        frmdt = $(".frmdt").val();
        if (type  == 'H') {
            $('.todt').val(frmdt);
            }
        }
        
        function timeAlert() {
            $(this).val($(this).val().replace(/\D/g, '').substring(0, 4));
        }

        function chkTime() {
            var type = $('.type').val();
            if (type == 'H') {
                $('.chalamt').attr('readonly', true).attr('disabled', true);
            $('.frmtime').removeAttr('readonly').removeAttr('disabled');
            $('.totime').removeAttr('readonly').removeAttr('disabled');
            $('.nomin').removeAttr('readonly').removeAttr('disabled');
            $('.nohrs').removeAttr('readonly').removeAttr('disabled');
            $('.rate').removeAttr('readonly').removeAttr('disabled');
            let ftime = $('.frmtime').val();
            let ttime = $('.totime').val();
        
            const timeRegex = /^(?:[01]\d|2[0-3])(?:00|15|30|45)$/;
        
            // Validate From Time
            if (ftime != '') {
                if (!timeRegex.test(ftime)) {
                    $('.frmtime').val('');
                    alert('Please enter a valid time in 24-hour format at 15-minute intervals (e.g., 0015, 0030).');
                    $('.frmtime').focus();
                    return;
                }
            }
        
            // Validate To Time
            if (ttime != '') {
                if (!timeRegex.test(ttime)) {
                    $('.totime').val('');
                    alert('Please enter a valid time in 24-hour format at 15-minute intervals (e.g., 0015, 0030).');
                    $('.totime').focus();
                    return;
                }
            }
        
            var startDate = new Date($('.frmdt').val());
            var endDate = new Date($('.todt').val());
            var addFlag = $('.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');
                $('.totime').val('');
                $('.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');
                $('.totime').val('');
                $('.totime').focus();
                return false;
            }
        
            // Calculate hours and minutes
            const nohrs = Math.floor(totalMinutes / 60);
            const nomin = totalMinutes % 60;
        
            // Set the values in the input fields
            $('.nohrs').val(nohrs);
            $('.nomin').val(nomin);
        
            calMain(); // Call the main calculation function
        } else {
            $('.frmtime').attr('readonly', true).attr('disabled', true);
            $('.totime').attr('readonly', true).attr('disabled', true);
            $('.nomin').attr('readonly', true).attr('disabled', true);
            $('.nohrs').attr('readonly', true).attr('disabled', true);
            $('.rate').attr('readonly', true).attr('disabled', true);
            $('.chalamt').removeAttr('readonly').removeAttr('disabled');
            $('.chalamt').focus();
        }

        }

            function calMain() {
                var rate = parseInt($('.rate').val()); 
                var otamt = parseInt($('.otamt').val()); 
                var nohrs = parseInt($('.nohrs').val()); 
                var nomin = parseInt($('.nomin').val()); 
                var totalHours = nohrs + nomin / 60;
                var chalamt = rate * totalHours + otamt;
                $('.chalamt').val(chalamt.toFixed(2)); 
            }

});