$(document).ready(function () {

// Sync localStorage token to cookie on load for server-side hold ignoring
(function() {
    var token = localStorage.getItem("_chkseats_token");
    if (token) {
        document.cookie = "_chkseats_token=" + token + "; path=/; max-age=3600";
        // Also populate search form if it exists
        var searchInput = document.getElementById('ticket_token_search');
        if (searchInput) {
            searchInput.value = token;
        }
    }
})();

    // $("#detailpay" ).hide();
    // $("#payment_method").hide();

    var baseurl = $('#baseurl').val();
    var seatclass = "";
    var regularFare = "";


    $('.toggle-seat-select').on('click', function (e) {
        
        if (!$(this).hasClass('collapsed')) {


            var id = $('button', this).attr('id'),
                baseurl = $('#baseurl').val(),
                journeydate = $('#journeydate').val(),
                url = `${baseurl}/modules/backend/tickets/singletrip/${id}/${journeydate}`;

            if ($("#AllSelectedSeatDiv_"+id).length) {
                $("#AllSelectedSeatDiv_"+id).remove();
            }

            var $form = $("#form_" + id),
                $seat = $("#seat_" + id),
                $loader = $("#page-loader");

            $seat.html('').append($loader.clone().removeAttr('id'));
            $form.html('').append($loader.clone().removeAttr('id'));

            setTimeout(() => {
                $.ajax({
                    method: "GET",
                    url: url,
                    dataType: "JSON",
                    success: function (result) {
                        if (!result || result.status !== 'success') {
                            var msg = (result && result.message) ? result.message : 'Could not load trip details.';
                            $seat.html('<div class="alert alert-danger m-3">' + msg + '</div>');
                            $form.html('');
                            return;
                        }
                        console.log("31");
                        console.log(result);
                        $('html, body').animate({ scrollTop: $form.offset().top - 250 }, 500);
                        dynamicseat(result, id).done(function (response) { $seat.html(response); })
                            .fail(function () {
                                $seat.html('<div class="alert alert-danger m-3">Could not load seat layout.</div>');
                            });

                        (async (c) => {
                            await c.web_settings.init();
                            await c.lang.init();

                            $form.html(dynamichtml(result, id));
                        })(bdtaskIlmCommonJs);
                    },
                    error: function (xhr) {
                        var msg = 'Could not load trip details.';
                        if (xhr.responseJSON && xhr.responseJSON.message) {
                            msg = xhr.responseJSON.message;
                        }
                        $seat.html('<div class="alert alert-danger m-3">' + msg + '</div>');
                        $form.html('');
                    }
                });
            }, 500);

        }
    });

    $("#partial").hide();

    $("#payment_status").change(function () {

        var paystats = $("#payment_status").val();

        if ((paystats == "paid")) {
            $("#detailpay").show();
            $("#payment_method").show();
            $("#partial").hide();
            $("#partialpay").val(0);
            $("#couponcode").show();
            $("#less").show();
        }

        if ((paystats == "partial")) {
            var payamount = $("#grandtotal").val();

            $("#detailpay").show();
            $("#payment_method").show();
            $("#partial").show();
            $("#partialpay").val(payamount);
            $("#couponcode").show();
            $("#discount").show();
        }

        if (paystats == "unpaid") {
            var oldGrandtotal = $("#oldgrandtotal").val();
            $("#discount").attr('readonly', false);
            $("#coupon").attr('readonly', false);
            $("#detailpay").hide();
            $("#payment_method").hide();
            $("#couponcode").hide();
            $("#less").hide();
            $("#grandtotal").val(parseFloat(oldGrandtotal).toFixed(2));
            $("#discount").val(0);
            $("#partialpay").val(parseFloat(oldGrandtotal).toFixed(2));
            $("#coupon").val("");
            $("#couponmessage").html("");
            $("#partial").val("");
            $("#partial").hide();
        }
    });

    $("#discount").on('input', function () {
        // Allow numeric discount only (digits and one decimal point).
        var raw = String($(this).val() || '');
        var cleaned = raw.replace(/[^0-9.]/g, '');
        var parts = cleaned.split('.');
        if (parts.length > 2) {
            cleaned = parts[0] + '.' + parts.slice(1).join('');
        }
        $(this).val(cleaned);
    });

    $("#discount").focusout(function () {
        if (!$("#less").length) {
            return;
        }

        var oldtotal = parseFloat($("#oldgrandtotal").val());
        var discount = parseFloat($("#discount").val());
        oldtotal = isNaN(oldtotal) ? 0 : oldtotal;
        discount = isNaN(discount) ? 0 : discount;

        if (discount < 0) {
            discount = 0;
        }
        if (discount > oldtotal) {
            discount = oldtotal;
        }

        var newgrandtotal = oldtotal - discount;
        $("#discount").val(discount.toFixed(2));
        $("#grandtotal").val(newgrandtotal.toFixed(2));
        $("#partialpay").val(newgrandtotal.toFixed(2)).prop('max', newgrandtotal.toFixed(2));
    });
});

function dynamicseat(result, id) {
    var baseurl = $('#baseurl').val(),
        subtrip = JSON.parse(result.subtrips)[0],
        seatnumber = subtrip.seat_number,
        seatbook = JSON.parse(result.bookseat);
        seathold = JSON.parse(result.holdseat);
        seatblock = JSON.parse(result.blockseat);

    function parseSeatCsv(str) {
        if (str === null || str === undefined || str === '') {
            return [];
        }
        return String(str).split(',').map(function (s) { return s.trim(); }).filter(function (s) { return s !== ''; });
    }

    var seatarray = parseSeatCsv(seatnumber),
        bookseatarray = parseSeatCsv(seatbook),
        holdseatarray = parseSeatCsv(seathold),
        seatblockarray = parseSeatCsv(seatblock);

    return $.post(`${baseurl}/modules/backend/tickets/seatlayout`, {
        id: id,
        fleet_id: subtrip.fleet_id,
        booked: bookseatarray,
        hold: holdseatarray,
        block: seatblockarray,
    });
}

function seacClick_BKP(seatElem, subtripid, seatlabel) {
    console.log("132");
    console.log(seatElem.className + "133");
    console.log(seatElem);
    console.log($(seatElem).data('seatnumber'));
    console.log(seatlabel);
    // alert(subtripid);
    var seatArray = [],
        seatvalue = $("#seatnumber" + subtripid).val(),
        // id = seatindex.getAttribute('id'),
        numberseat = $(seatElem).data('seatnumber'),
        baseurl = $('#baseurl').val();

    if ($(seatElem).hasClass('seat-checked') || seatlabel == 'booked') {
        return;
    }

    // if($(seatElem).hasClass('seat-checked')){
    //     $(seatElem).removeClass('seat-checked');
    //     $('img', seatElem).attr('src', `${baseurl}/public/image/seatavailable.svg`);

    //     // Remove the seat from the selected list
    //     var seats = seatvalue.split(',');
    //     seats = seats.filter(seat => seat !== numberseat); // Remove the current seat
    //     $("#seatnumber" + subtripid).val(seats.join(','));

    //     // Optional: Update seat count after unchecking
    //     latestupdateSeatCount("remove", subtripid, numberseat);

    //     return; // Exit since we've handled the unchecking
    // }


    selectedSeatClass = getSeatClassBySeatNo(numberseat);
    selectedSeatPrice = getSeatPriceBySeatNo(numberseat);
    // console.log("145");
    console.log(selectedSeatPrice);

    if (sessionStorage.getItem("tripid")) {
        if (sessionStorage.getItem("tripid") != subtripid) {
            var removeid = sessionStorage.getItem("tripid");
            sessionStorage.removeItem('tripid')
            var removeclass = [];
            var removeseat = $("#seatnumber" + removeid).val();
            if (typeof removeseat !== 'undefined' && removeseat != "") {
                removeclass = removeseat.split(',');
            }

            removeclass = $.grep(removeclass, function (value) {
                $("#seat_" + removeid + '_' + value).removeClass("btn btn-success").addClass("btn btn-light");
            });

            var newseatValue = "";
            $("#seatnumber" + removeid).val(newseatValue);
        }
    }

    if (seatvalue == "") {
        $("#seatnumber" + subtripid).val(numberseat);

        sessionStorage.removeItem('tripid')
        sessionStorage.setItem("tripid", subtripid);

        // highlight selected
        $(seatElem).addClass('seat-checked');
        $('img', seatElem).attr('src', `${baseurl}/public/image/seatselected.svg`);
    } else {
        if ((sessionStorage.getItem("tripid")) && (sessionStorage.getItem("tripid") == subtripid)) {
            var totalseat = seatvalue.split(',');
            var hasVal = Object.values(totalseat).includes(numberseat);

            if (hasVal) {
                totalseat = $.grep(totalseat, function (value) {
                    return value != numberseat;
                });

                let newSeats = totalseat.toString();
                $("#seatnumber" + subtripid).val(newSeats);

                // highlight de-selected
                $(seatElem).removeClass('seat-checked');
                $('img', seatElem).attr('src', `${baseurl}/public/image/seatavailable.svg`);
            } else {
                totalseat.push(numberseat);
                let newSeats = totalseat.toString();
                $("#seatnumber" + subtripid).val(newSeats);

                // highlight selected
                $(seatElem).addClass('seat-checked');
                $('img', seatElem).attr('src', `${baseurl}/public/image/seatselected.svg`);
            }
        } else {
            sessionStorage.removeItem('tripid')
            sessionStorage.setItem("tripid", subtripid);
            let newSeats = "";
            $("#seatnumber" + subtripid).val(newSeats);
            $("#seatnumber" + subtripid).val(numberseat);

            // highlight selected
            $(seatElem).addClass('seat-checked');
            $('img', seatElem).attr('src', `${baseurl}/public/image/seatselected.svg`);
        }
    }
    console.log(selectedSeatClass);

    latestupdateSeatCount("add", subtripid,numberseat,selectedSeatClass,selectedSeatPrice);
}

function latestupdateSeatCount_BKP(type, subtripid, numberseat ="", selectedSeatClass ="", selectedSeatPrice="") {
    

    var selectedSeatClass = selectedSeatClass ? selectedSeatClass : "0"; // Replace null with empty string
    
    var numberseat = numberseat ? numberseat : ""; // Replace null with empty string
    var divId = "AllSelectedSeatDiv_"+subtripid;
    
    if(type == "add"){

        if ($("#" + divId).length === 0) {       
            
            var newDiv = $("<div>", { id: divId });
            console.log(newDiv, 258);
            // Create a new input field
            var inputField = $("<input>", {
                type: "hidden",
                id: "selectedAllClass" + selectedSeatClass + "_" + numberseat,
                name: "selectedAllClass[]",
                value: selectedSeatClass,
                class: "selectedAllClassInput"
            }).attr("data-price", selectedSeatPrice);

            newDiv.append(inputField);
            $("body").append(newDiv);
                
        } else {

            // Create a new input field
            var inputField = $("<input>", {
                type: "hidden",
                id: "selectedAllClass" + selectedSeatClass + "_" + numberseat,
                name: "selectedAllClass[]",
                value: selectedSeatClass,
                class: "selectedAllClassInput"
            }).attr("data-price", selectedSeatPrice);

            $("#" + divId).append(inputField);
        }
    } else {
        $("#selectedAllClass" + selectedSeatClass + "_" + numberseat).remove();      
    }
    
    var AddedClassArr = [];
    var TotalSelectedSeats = 0
    $(".selectedAllClassInput").each(function () {

        var seatclass = $(this).val(); // Get input value
        var seatprice = $(this).attr("data-price"); // Get data-price attribute
        var seatprice = parseFloat(seatprice) || 0; // Convert to number safely
        var div = "seat_total_"+seatclass+"_"+ subtripid;


        if (!AddedClassArr.includes(seatclass)) {
            AddedClassArr.push(seatclass);
            $("#"+div).text(0.00);
        }
        var currentTotal = parseFloat($("#"+div).text()) || 0; // Handle NaN case
        var updatedTotal = currentTotal + seatprice;
        updatedTotal = parseFloat(updatedTotal).toFixed(2);
        $("#"+div).text(updatedTotal);

        TotalSelectedSeats++;
    });
    toprice(subtripid);



    /* var $slotElem = $("#seat_" + subtripid),
        $childInputElem = $("#child_seat" + subtripid),
        $specialInputElem = $("#special_seat" + subtripid),
        $vipInputElem = $("#vip_seat" + subtripid),
        $adultInputElem = $("#adult_seat" + subtripid),
        $selectedSeats = $slotElem.find('.seat-checked'),
        totalSelectedSeats, totalChild, totalSpecial, totalAdult, seatDiff, actualAdultValue,totalvip;
        console.log("228",$selectedSeats);


    totalSelectedSeats = parseInt($selectedSeats.length) || 0;
    totalChild = parseInt($childInputElem.val()) || 0;
    totalSpecial = parseInt($specialInputElem.val()) || 0;
    totalvip = parseInt($vipInputElem.val()) || 0;
    totalAdult = parseInt($adultInputElem.val()) || 0;

    var dynamicSeatTotal = 0;
    $slotElem.find("input[name^='seat_class_']").each(function () {
        dynamicSeatTotal += parseInt($(this).val()) || 0;
    });

    seatDiff = totalSelectedSeats - (totalChild + totalSpecial + totalvip + totalAdult + dynamicSeatTotal);
    actualAdultValue = totalAdult + seatDiff;

    $adultInputElem.val((actualAdultValue > -1) ? actualAdultValue : 0).trigger('change'); */
}

function toprice_BKP(subtripid) {
    var totalClassAmount = 0.00;

    $('.classTotalAmount').each(function () {
        var amount = parseFloat($(this).text().trim()); // Get the text, trim spaces, and parse as float
        if (!isNaN(amount)) { // Ignore NaN or invalid numbers
            totalClassAmount += amount;
        }
    });


    // var cprice = $("#special_price_show" + subtripid).text();
    // var sprice = $("#child_price_show" + subtripid).text();
    // var vprice = $("#vip_price_show" + subtripid).text();
    // var aprice = $("#adult_price_show" + subtripid).text();
    // var totalprice = parseInt(cprice) + parseInt(vprice) + parseInt(sprice) + parseInt(aprice);
    // $("#totalprice" + subtripid).text(totalprice);
    totalClassAmount = parseFloat(totalClassAmount).toFixed(2)
    $("#totalprice" + subtripid).text(totalClassAmount);

    taxcaltulation(subtripid, totalClassAmount);
}

function taxcaltulation_BKP(subtripid, totalvalue) {
    var taxvalues = $("#tax" + subtripid).val();
    var totaltaxval = [];
    var newtaxarray = taxvalues.split(',');

    newtaxarray.forEach((value) => {
        var caltax = (value * totalvalue) / 100
        totaltaxval.push(caltax);

    });

    var total = 0;
    totaltaxval.forEach((value) => {
        console.log(value);
        total += parseFloat(value);

    });
    var taxtype = $("#tax_type").val();
    var grandtotal;
    var totalseat;

    if (taxtype == "inclusive") {
        grandtotal = parseFloat(totalvalue) - parseFloat(total);
        grandtotal = totalvalue;

    }
    else {
        grandtotal = parseFloat(total) + parseFloat(totalvalue);
        grandtotal = parseFloat(grandtotal).toFixed(2);
    }
    totalseat = $(".selectedAllClassInput").length;
    
    $("#totaltax" + subtripid).text(parseFloat(total).toFixed(2));
    $("#grandtotal" + subtripid).text(parseFloat(grandtotal).toFixed(2));
    $("#totalseat" + subtripid).text(totalseat);

}

function seacClick(seatElem, subtripid, seatlabel) {
    console.log("132");
    console.log(seatElem.className + "133");
    console.log(seatElem);
    console.log($(seatElem).data('seatnumber'));
    console.log(seatlabel);
    // alert(subtripid);
    var seatvalue = $("#seatnumber" + subtripid).val(), numberseat = $(seatElem).data('seatnumber'), baseurl = $('#baseurl').val();

    // Only explicitly selectable seats (booked / hold / blocked must never toggle selection)
    if (seatlabel !== 'available') {
        return;
    }

    selectedSeatClass = getSeatClassBySeatNo(numberseat);
    selectedSeatPrice = getSeatPriceBySeatNo(numberseat);
    
    if (sessionStorage.getItem("tripid")) {
        
        if (sessionStorage.getItem("tripid") != subtripid) {
            
            var removeid = sessionStorage.getItem("tripid");
            sessionStorage.removeItem('tripid')
            var removeclass = [];
            var removeseat = $("#seatnumber" + removeid).val();
            if (typeof removeseat !== 'undefined' && removeseat != "") {
                removeclass = removeseat.split(',');
            }

            removeclass = $.grep(removeclass, function (value) {
                $("#seat_" + removeid + '_' + value).removeClass("btn btn-success").addClass("btn btn-light");
            });

            var newseatValue = "";
            $("#seatnumber" + removeid).val(newseatValue);
        }
    }

    let seatArray = seatvalue ? seatvalue.split(',') : [];

    if ($(seatElem).hasClass('seat-checked')) {
        
        // If the seat is already selected, remove it (deselect)
        seatArray = seatArray.filter(seat => seat.toString() !== numberseat.toString());
        $(seatElem).removeClass('seat-checked');
        $('img', seatElem).attr('src', `${baseurl}/public/image/seatavailable.svg`);
        if(seatArray.length == 0){
            sessionStorage.removeItem('tripid');
        }
        $("#seatnumber"+subtripid).val(seatArray.join(",")); // Update input field
        latestupdateSeatCount("remove", subtripid, numberseat, selectedSeatClass, selectedSeatPrice);

    } else {

        if(seatArray.length == 0){
            sessionStorage.removeItem('tripid');
            sessionStorage.setItem("tripid", subtripid);
        }
        // Otherwise, select the seat
        seatArray.push(numberseat);
        $(seatElem).addClass('seat-checked');
        $('img', seatElem).attr('src', `${baseurl}/public/image/seatselected.svg`);
        $("#seatnumber"+subtripid).val(seatArray.join(",")); // Update input field
        
        latestupdateSeatCount("add", subtripid, numberseat, selectedSeatClass, selectedSeatPrice);
    }
}

function latestupdateSeatCount(type, subtripid, numberseat ="", selectedSeatClass ="", selectedSeatPrice="") {
    

    var selectedSeatClass = selectedSeatClass ? selectedSeatClass : "0"; // Replace null with empty string
    
    var numberseat = numberseat ? numberseat : ""; // Replace null with empty string
    var divId = "AllSelectedSeatDiv_"+subtripid;
    
    if(type == "add"){

        if ($("#" + divId).length === 0) { 
            
            var newDiv = $("<div>", { id: divId });
            console.log(newDiv, 258);
            
            // Create a new input field
            var inputField = $("<input>", {
                type: "hidden",
                id: "selectedAllClass" + selectedSeatClass + "_" + numberseat,
                name: "selectedAllClass[]",
                value: selectedSeatClass,
                class: "selectedAllClassInput"
            }).attr("data-price", selectedSeatPrice);

            newDiv.append(inputField);
            $("body").append(newDiv);
                
        } else {

            // Create a new input field
            var inputField = $("<input>", {
                type: "hidden",
                id: "selectedAllClass" + selectedSeatClass + "_" + numberseat,
                name: "selectedAllClass[]",
                value: selectedSeatClass,
                class: "selectedAllClassInput"
            }).attr("data-price", selectedSeatPrice);

            $("#" + divId).append(inputField);
        }
    } else {

        var totalclassseatamount = parseFloat($("#seat_total_" + selectedSeatClass + "_" + subtripid).text()) || 0.00;
        var Alltotalseatamount = parseFloat($("#totalprice" + subtripid).text()) || 0.00;
        var seatAmount = 700; // Ensure seatAmount is a number

        var newtotalclassseatamount = totalclassseatamount - selectedSeatPrice;
        var newAlltotalseatamount = Alltotalseatamount - selectedSeatPrice;

        // Update the HTML elements with the new calculated values
        $("#seat_total_" + selectedSeatClass + "_" + subtripid).text(newtotalclassseatamount.toFixed(2));
        $("#totalprice" + subtripid).text(newAlltotalseatamount.toFixed(2));
        $("#selectedAllClass" + selectedSeatClass + "_" + numberseat).remove();      
    }
    
    var AddedClassArr = [];
    var TotalSelectedSeats = 0
    $(".selectedAllClassInput").each(function () {

        var seatclass = $(this).val(); // Get input value
        var seatprice = $(this).attr("data-price"); // Get data-price attribute
        var seatprice = parseFloat(seatprice) || 0; // Convert to number safely
        var div = "seat_total_"+seatclass+"_"+ subtripid;


        if (!AddedClassArr.includes(seatclass)) {
            AddedClassArr.push(seatclass);
            $("#"+div).text(0);
        }
        var currentTotal = parseFloat($("#"+div).text()) || 0.00; // Handle NaN case
        var updatedTotal = currentTotal + seatprice;
        updatedTotal = parseFloat(updatedTotal).toFixed(2);
        $("#"+div).text(updatedTotal);
        TotalSelectedSeats++;
    });
    toprice(subtripid);



    /* var $slotElem = $("#seat_" + subtripid),
        $childInputElem = $("#child_seat" + subtripid),
        $specialInputElem = $("#special_seat" + subtripid),
        $vipInputElem = $("#vip_seat" + subtripid),
        $adultInputElem = $("#adult_seat" + subtripid),
        $selectedSeats = $slotElem.find('.seat-checked'),
        totalSelectedSeats, totalChild, totalSpecial, totalAdult, seatDiff, actualAdultValue,totalvip;
        console.log("228",$selectedSeats);


    totalSelectedSeats = parseInt($selectedSeats.length) || 0;
    totalChild = parseInt($childInputElem.val()) || 0;
    totalSpecial = parseInt($specialInputElem.val()) || 0;
    totalvip = parseInt($vipInputElem.val()) || 0;
    totalAdult = parseInt($adultInputElem.val()) || 0;

    var dynamicSeatTotal = 0;
    $slotElem.find("input[name^='seat_class_']").each(function () {
        dynamicSeatTotal += parseInt($(this).val()) || 0;
    });

    seatDiff = totalSelectedSeats - (totalChild + totalSpecial + totalvip + totalAdult + dynamicSeatTotal);
    actualAdultValue = totalAdult + seatDiff;

    $adultInputElem.val((actualAdultValue > -1) ? actualAdultValue : 0).trigger('change'); */
}

function toprice(subtripid) {
    var totalClassAmount = 0;

    $('.classTotalAmount').each(function () {
        var amount = parseFloat($(this).text().trim()); // Get the text, trim spaces, and parse as float
        if (!isNaN(amount)) { // Ignore NaN or invalid numbers
            totalClassAmount += amount;
        }
    });


    // var cprice = $("#special_price_show" + subtripid).text();
    // var sprice = $("#child_price_show" + subtripid).text();
    // var vprice = $("#vip_price_show" + subtripid).text();
    // var aprice = $("#adult_price_show" + subtripid).text();
    // var totalprice = parseInt(cprice) + parseInt(vprice) + parseInt(sprice) + parseInt(aprice);
    // $("#totalprice" + subtripid).text(totalprice);
    totalClassAmount = parseFloat(totalClassAmount).toFixed(2);
    $("#totalprice" + subtripid).text(totalClassAmount);

    taxcaltulation(subtripid, totalClassAmount);
}

function taxcaltulation(subtripid, totalvalue) {
    var taxvalues = $("#tax" + subtripid).val();
    var totaltaxval = [];
    var newtaxarray = taxvalues.split(',');

    newtaxarray.forEach((value) => {
        var caltax = (value * totalvalue) / 100
        totaltaxval.push(caltax);

    });

    var total = 0;
    totaltaxval.forEach((value) => {
        console.log(value);
        total += parseFloat(value);

    });
    var taxtype = $("#tax_type").val();
    var grandtotal;
    var totalseat;

    if (taxtype == "inclusive") {
        grandtotal = parseFloat(totalvalue) - parseFloat(total);
        grandtotal = totalvalue;

    }
    else {
        grandtotal = parseFloat(total) + parseFloat(totalvalue);
        grandtotal = parseFloat(grandtotal).toFixed(2);
    }
    totalseat = $(".selectedAllClassInput").length;

    $("#totaltax" + subtripid).text(parseFloat(total).toFixed(2));
    $("#grandtotal" + subtripid).text(parseFloat(grandtotal).toFixed(2));
    $("#totalseat" + subtripid).text(totalseat);

}

function updateSeatCount(subtripid) {
    var $slotElem = $("#seat_" + subtripid),
        $childInputElem = $("#child_seat" + subtripid),
        $specialInputElem = $("#special_seat" + subtripid),
        $vipInputElem = $("#vip_seat" + subtripid),
        $adultInputElem = $("#adult_seat" + subtripid),
        $selectedSeats = $slotElem.find('.seat-checked'),
        totalSelectedSeats, totalChild, totalSpecial, totalAdult, seatDiff, actualAdultValue,totalvip;

    totalSelectedSeats = parseInt($selectedSeats.length) || 0;
    totalChild = parseInt($childInputElem.val()) || 0;
    totalSpecial = parseInt($specialInputElem.val()) || 0;
    totalvip = parseInt($vipInputElem.val()) || 0;
    totalAdult = parseInt($adultInputElem.val()) || 0;

    var dynamicSeatTotal = 0;
    $slotElem.find("input[name^='seat_class_']").each(function () {
        dynamicSeatTotal += parseInt($(this).val()) || 0;
    });

    seatDiff = totalSelectedSeats - (totalChild + totalSpecial + totalvip + totalAdult + dynamicSeatTotal);
    actualAdultValue = totalAdult + seatDiff;

    $adultInputElem.val((actualAdultValue > -1) ? actualAdultValue : 0).trigger('change');
}

function dynamichtml(result, id) {
    var seat = null;
    var subtrip = null;
    var picdrop = null;
    var taxval = null;
    var childseat = null;
    var childprice = null;
    var adultprice = null;
    var specialseat = null;
    var spacialprice = null;
    var vipseat = null;
    var vipprice = null;
    var taxarray = [];

    subtrip = JSON.parse(result.subtrips);
    picdrop = JSON.parse(result.pickdrop);
    taxval = JSON.parse(result.tax);
    seatclass = JSON.parse(result.seatClass);
    regularFare = JSON.parse(result.adultfare);



    $.each(subtrip, function (index, value) {
        specialseat = value.special_seat || 0;
        spacialprice = value.special_fair;

        vipseat = value.vip_seat || 0;
        vipprice = value.vip_fair;

        childseat = value.child_seat || 0;
        childprice = value.child_fair;

        adultprice = value.adult_fair;
    });


    $.each(picdrop, function (index, pvalue) {
        // console.log(pvalue);
    });

    $.each(taxval, function (index, taxvalue) {
        taxarray.push(taxvalue.value);
    });


    var html = '<div class="row">',
        $requiredSign = $('<abbr/>');

    $requiredSign.attr('title', 'Required field').text('*');

    // Seat count
    // var $childSeatCount = $('<div/>'),
    //     $childSeatCountLbl = $('<label/>'),
    //     $childSeatCountInp = $('<input/>');

        
    // $childSeatCountLbl
    //     .attr('for', `child_seat${id}`)
    //     .addClass('form-label text-capitalize')
    //     .text(bdtaskIlmCommonJs.lang.getPhrase('booking_page_children_seat'));

    // $childSeatCountInp
    //     .attr({
    //         type: 'number',
    //         id: `child_seat${id}`,
    //         class: 'form-control',
    //         name: `child_seat`,
    //         value: 0,
    //         min: 0,
    //         max: childseat,
    //         tabindex: 1,
    //         onchange: `childseat(this, ${id})`
    //     });

    // $childSeatCount
    //     .addClass('col-4')
    //     .append([$childSeatCountLbl, $childSeatCountInp]);

    // $childSeatCountInp.bind('change', () => { console.log(this); /* childseat_func(this, id) */ });

    // var $specialSeatCount = $childSeatCount.clone();
    // $('label', $specialSeatCount)
    //     .attr('for', `special_seat${id}`)
    //     .text(bdtaskIlmCommonJs.lang.getPhrase('booking_page_special_seat'));

    // $('input', $specialSeatCount)
    //     .attr({
    //         type: 'number',
    //         id: `special_seat${id}`,
    //         name: `special_seat`,
    //         max: specialseat,
    //         onchange: `specialseat(this, ${id})`
    //     });

    // var $vipSeatCount = $childSeatCount.clone();
    // $('label', $vipSeatCount)
    //     .attr('for', `vip_seat${id}`)
    //     .text(bdtaskIlmCommonJs.lang.getPhrase('booking_page_vip_seat'));

    // $('input', $vipSeatCount)
    //     .attr({
    //         type: 'number',
    //         id: `vip_seat${id}`,
    //         name: `vip_seat`,
    //         max: vipseat,
    //         onchange: `vipseat(this, ${id})`
    //     });

    // var $adultSeatCount = $childSeatCount.clone();
    // $('label', $adultSeatCount)
    //     .attr('for', `adult_seat${id}`)
    //     .text(bdtaskIlmCommonJs.lang.getPhrase('booking_page_adul_seat'));

    // $('input', $adultSeatCount)
    //     .attr({
    //         type: 'number',
    //         id: `adult_seat${id}`,
    //         name: `adult_seat`,
    //         max: null,
    //         onchange: `adultseat(this, ${id})`
    //     });

    // html += $childSeatCount.prop('outerHTML') + $specialSeatCount.prop('outerHTML') + $vipSeatCount.prop('outerHTML')+ $adultSeatCount.prop('outerHTML');

    // Pick location and drop location
    var $pick = $('<div/>'),
        $pickLbl = $('<label/>'),
        $pickSelect = $('<select/>'),
        $selectOption = $('<option/>'),
        $drop = $pick.clone(),
        $dropLbl, $dropSelect;

    $pickLbl.attr('for', `pickupstand${id}`)
        .addClass('form-label text-capitalize')
        .text(bdtaskIlmCommonJs.lang.getPhrase('selected_boarding_title'))
        .append($requiredSign.clone());

    $dropLbl = $pickLbl.clone()
        .attr('for', `dropstand${id}`)
        .text(bdtaskIlmCommonJs.lang.getPhrase('selected_dropping_title'))
        .append($requiredSign.clone());

    $pickSelect
        .attr({
            name: `pickupstand${id}`,
            id: `pickupstand${id}`,
            tabindex: 1
        })
        .addClass('form-select testselect1')
        .prop('required', true);

    $dropSelect = $pickSelect.clone()
        .attr({
            name: `dropstand${id}`,
            id: `dropstand${id}`,
            tabindex: 1
        });

    // Force explicit user selection for boarding/dropping points.
    $pickSelect.append(
        $selectOption.clone()
            .attr('value', '')
            .prop('selected', true)
            .text(bdtaskIlmCommonJs.lang.getPhrase('key_select_boarding_point'))
    );
    $dropSelect.append(
        $selectOption.clone()
            .attr('value', '')
            .prop('selected', true)
            .text(bdtaskIlmCommonJs.lang.getPhrase('key_select_dropping_point'))
    );

    $.each(picdrop, function (i, v) {
        var $pickSelectOptionSingle = $selectOption.clone().attr('value', v.pickdropid).text(v.name + " ( " + v.time + " )");
        v.type == 1 ? $pickSelect.append($pickSelectOptionSingle) : $dropSelect.append($pickSelectOptionSingle);
    });

    $pick.addClass('col-6 my-3').append([$pickLbl, $pickSelect]);
    $drop.addClass('col-6 my-3').append([$dropLbl, $dropSelect]);

    html += $pick.prop('outerHTML') + $drop.prop('outerHTML');

    html += '<div class="col-4 mt-2">';
    html += '   <h6 class="form-label fw-bold">' + bdtaskIlmCommonJs.lang.getPhrase('type') + '</h6>';
    html += '</div>';

    html += '<div class="col-4 mt-2">';
    html += '   <h6 class="form-label fw-bold">' + bdtaskIlmCommonJs.lang.getPhrase('price') + '</h6>';
    html += '</div>';

    html += '<div class="col-4 mt-2">';
    html += '   <h6 class="form-label fw-bold">' + bdtaskIlmCommonJs.lang.getPhrase('total') + '</h6>';
    html += '</div>';
    totalregularfare = 0.00;
    if (typeof $('#regular_seat' + id).val() !== "undefined") {
        totalregularfare = $('#regular_seat' + id).val() * regularFare;
    }

    html += '<div class="col-4 mt-1">';
    html += '   <h6 class="form-label">' + bdtaskIlmCommonJs.lang.getPhrase('booking_page_adul_seat') + '</h6>';
    html += '</div>';
    html += '<div class="col-4 mt-1">';
    html += '   <h6 class="form-label" id="seat_price_0_' + id + '">' + parseFloat(regularFare).toFixed(2) + '</h6>';
    html += '</div>';
    html += '<div class="col-4 mt-1">';
    html += '   <h6 class="form-label classTotalAmount" id="seat_total_0_' +id + '">' + parseFloat(totalregularfare).toFixed(2) + '</h6>';
    html += '</div>';

    $.each(seatclass, function (index, seatInfo) {
        var seatClass = seatInfo.seatClass;
        var fare = seatInfo.fare;
        var seatCount = 0; // This will hold the selected seat count for each class
        var totalFare = 0;
        var class_seats = seatInfo.seatNo;
        console.log("423");
        console.log(seatClass);
        seatCount = $('#'+seatClass+'_seat' + id).val();
        console.log("seatcount " +seatCount);
        if (typeof seatCount !== "undefined") {
            console.log("seatCount: " + seatCount);
            totalFare = seatCount * fare;    
        }

        

        // Add the HTML for each seat class and its total fare
        html += '<div class="col-4 mt-1">';
        html += '   <h6 class="form-label">' + bdtaskIlmCommonJs.lang.getPhrase('seat_class_' + seatClass) + ' ('+class_seats+')</h6>';
        html += '</div>';
        html += '<div class="col-4 mt-1">';
        html += '   <h6 class="form-label" id="seat_price_' + seatClass +'_' + id + '">' + fare + '</h6>';
        html += '</div>';
        html += '<div class="col-4 mt-1">';
        html += '   <h6 class="form-label classTotalAmount" id="seat_total_' + seatClass + '_' +id + '">' + parseFloat(totalFare).toFixed(2) + '</h6>';
        html += '</div>';
    });

    html += '<div class="col-md-4">';
    html += `   <h6 class="form-label">${bdtaskIlmCommonJs.lang.getPhrase('ticket')} ${bdtaskIlmCommonJs.lang.getPhrase('price')}</h6>`;
    html += '</div>';

    html += '<div class="col-md-4">';
    html += '   <h6 class="form-label" ></h6>';
    html += '</div>';

    html += '<div class="col-md-4 ">';
    html += '   <h6 class="form-label" id="totalprice' + id + '">0.00</h6>';
    html += '</div>';


    html += '<div class="col-md-4">';
    html += `   <h6 class="form-label">${bdtaskIlmCommonJs.lang.getPhrase('tax')}</h6>`;
    html += '</div>';

    html += '<div class="col-md-4">';
    html += '   <h6 class="form-label" ></h6>';
    html += '</div>';

    html += '<div class="col-md-4 ">';
    html += '   <h6 class="form-label" id="totaltax' + id + '">0.00</h6>';
    html += '</div>';

    html += '<div class="col-md-4">';
    html += `   <h6 class="form-label">${bdtaskIlmCommonJs.lang.getPhrase('grand')} ${bdtaskIlmCommonJs.lang.getPhrase('total')}</h6>`;
    html += '</div>';

    html += '<div class="col-md-4">';
    html += '   <h6 class="form-label"></h6>';
    html += '</div>';

    html += '<div class="col-md-4 ">';
    html += '<h6  class="form-label" id="grandtotal' + id + '">0.00</h6>';
    html += '</div>';

    html += '<div class="col-md-4">';
    html += `<h6 class="form-label">${bdtaskIlmCommonJs.lang.getPhrase('total')} ${bdtaskIlmCommonJs.lang.getPhrase('seat')}</h6>`;
    html += '</div>';

    html += '<div class="col-md-4">';
    html += '   <h6 class="form-label"></h6>';
    html += '</div>';

    html += '<div class="col-md-4 ">';
    html += '<h6  class="form-label" id="totalseat' + id + '">0</h6>';
    html += '</div>';

    html += '<input type="hidden" id="tax' + id + '" name="tax' + id + '[]" value ="' + taxarray + '">';
    html += '</div>';

    return html;
}

function childseat(cseat, subtripid) {
    var $field = $(cseat),
        maxChild = $field.prop('max'),
        filteredValue = parseInt($field.val()) || 0;

    if (filteredValue > maxChild) {
        alert(`Maximum child seat selection is: ${maxChild}`);
        filteredValue = maxChild;
    }

    $field.val(filteredValue);

    var price = $("#child_price" + subtripid).text();
    var totalprice = filteredValue * parseInt(price);
    $("#child_price_show" + subtripid).text(parseFloat(totalprice).toFixed(2));

    toprice(subtripid);
    updateSeatCount(subtripid);
}

function adultseat(cseat, subtripid) {
    var $field = $(cseat),
        filteredValue = parseInt($field.val()) || 0;

    $field.val(filteredValue);

    var id = cseat.getAttribute('id');
    var numberseat = $("#" + id).val();
    var price = $("#adult_price" + subtripid).text();
    var totalprice = parseInt(numberseat) * parseInt(price);
    $("#adult_price_show" + subtripid).text(parseFloat(totalprice).toFixed(2));
    toprice(subtripid);
}

function specialseat(cseat, subtripid) {
    var $field = $(cseat),
        maxSpecial = $field.prop('max'),
        filteredValue = parseInt($field.val()) || 0;

    if (filteredValue > maxSpecial) {
        alert(`Maximum special seat selection is: ${maxSpecial}`);
        filteredValue = maxSpecial;
    }

    $field.val(filteredValue);

    var id = cseat.getAttribute('id');
    var numberseat = $("#" + id).val();
    var price = $("#special_price" + subtripid).text();
    var totalprice = parseInt(numberseat) * parseInt(price);
    $("#special_price_show" + subtripid).text(parseFloat(totalprice).toFixed(2));

    toprice(subtripid);
    updateSeatCount(subtripid);
}

function vipseat(cseat, subtripid) {
    var $field = $(cseat),
        maxvip = $field.prop('max'),
        filteredValue = parseInt($field.val()) || 0;

    if (filteredValue > maxvip) {
        alert(`Maximum VIP seat selection is: ${maxvip}`);
        filteredValue = maxvip;
    }

    $field.val(filteredValue);

    var id = cseat.getAttribute('id');
    var numberseat = $("#" + id).val();
    var price = $("#vip_price" + subtripid).text();
    var totalprice = parseInt(numberseat) * parseInt(price);
    $("#vip_price_show" + subtripid).text(parseFloat(totalprice).toFixed(2));

    toprice(subtripid);
    updateSeatCount(subtripid);
}

function formsubmit(index, subtripid) {
    var allseatnumber = $("#seatnumber" + subtripid).val(),
        childseat = $("#child_seat" + subtripid).val(),
        specialseat = $("#special_seat" + subtripid).val(),
        vipseat = $("#vip_seat" + subtripid).val(),
        adultseat = $("#adult_seat" + subtripid).val();

    var totalprice = $("#totalprice" + subtripid).text(),
        tax = $("#totaltax" + subtripid).text(),
        grandtotal = $("#grandtotal" + subtripid).text(),
        pickstand = $("#pickupstand" + subtripid).val(),
        dropstand = $("#dropstand" + subtripid).val(),
        journeydate = $('#journeydate').val();


    totalprice = parseInt(totalprice);
    tax = parseInt(tax);
    grandtotal = parseInt(grandtotal);
    childseat = parseInt(childseat);
    specialseat = parseInt(specialseat);
    vipseat = parseInt(vipseat);
    adultseat = parseInt(adultseat);

    //var totalpassanger = parseInt(childseat + adultseat + specialseat + vipseat);
    var totalpassanger = $(".selectedAllClassInput").length;

    if (allseatnumber) {
        $("#seatnumbers").val(allseatnumber);
    } else {
        alert("no seat selected");
        return false
    }

    if (totalpassanger <= 0) {
        alert("please enter passagenr");
        return false
    } else {
        $("#aseat").val(adultseat);
        $("#spseat").val(specialseat);
        $("#vpseat").val(vipseat);
        $("#cseat").val(childseat);
    }

    if (pickstand) {
        $("#pickstand").val(pickstand);
    } else {
        setTimeout(() => $("#pickupstand" + subtripid).focus(), 400);
        alert("Please select pick stand");
        return false
    }

    if (dropstand) {
        $("#dropstand").val(dropstand);
    } else {
        alert("Please select drop stand");
        setTimeout(() => $("#dropstand" + subtripid).focus(), 400);
        return false
    }

    var totalseatarray = allseatnumber.split(','),
        seatlength = totalseatarray.length;

    if (totalpassanger != seatlength) {
        alert("Selected seat and passenger number are not matching");
        return false
    }
    var singeltriptotalseat = parseInt($("#totalseat").val());

    if (isNaN(singeltriptotalseat)) {
        singeltriptotalseat = 0;
    }

    if (singeltriptotalseat > 0) {
        if (totalpassanger != singeltriptotalseat) {
            alert("Your single trip and round trip passenger number are not matching. Your single trip Passanger " + singeltriptotalseat + " Your Round trip Passanger " + totalpassanger + "");
            return false
        }
    }

    $("#subtripId").val(subtripid);
    $("#totalprice").val(parseFloat(totalprice).toFixed(2));
    $("#tax").val(tax);
    $("#grandtotal").val(parseFloat(grandtotal).toFixed(2));

    // check selected seats
    var base_url = $('#baseurl').val(),
        random_token = localStorage.getItem("_chkseats_token") || get_random_token(16),
        seats_check_api_endpoint = `${base_url}/modules/api/v1/tickets/checkseats/admin`,
        seats_check_api_booking = `${base_url}/modules/api/v1/tickets/bookingcheck`;

    // Persist token immediately to avoid deadlock if the request fails
    localStorage.setItem("_chkseats_token", random_token);
    document.cookie = "_chkseats_token=" + random_token + "; path=/; max-age=3600";

        $.ajax({
            type: 'POST',
            url: seats_check_api_booking,
            dataType: 'json',
            data: {
                subtrip_id: subtripid,
                seat_names: allseatnumber,
                pickstand: pickstand,
                dropstand: dropstand,
                journeydate: journeydate,
                ticket_token: random_token
            },
            success: function (response) {
                if (response.status === "success") {
                    // ✅ Proceed with seat check only if bookingcheck is success
                    $.ajax({
                        type: 'POST',
                        url: seats_check_api_endpoint,
                        dataType: 'json',
                        data: {
                            subtrip_id: subtripid,
                            ticket_token: random_token,
                            seat_names: allseatnumber,
                            journey_date: journeydate,
                            pickstand: pickstand,
                            dropstand: dropstand
                        },
                        success: function (response2) {
                            if (response2.status == "success") {
                                localStorage.setItem("_chkseats_token", random_token);
                                
                                // Inject ticket_token into form before submit
                                if ($("#booking input[name='ticket_token']").length === 0) {
                                    $("<input>").attr({
                                        type: "hidden",
                                        name: "ticket_token",
                                        value: random_token
                                    }).appendTo("#booking");
                                } else {
                                    $("#booking input[name='ticket_token']").val(random_token);
                                }
                                
                                // Submit the form using native DOM method to avoid triggering the jQuery submit handler again (recursion)
                                document.getElementById("booking").submit();
                                return true;
                            }
                            alert(response2.message);
                        }
                    });
                } else {
                    // ❌ bookingcheck failed
                    alert(response.message);
                }
            },
            error: function () {
                alert("Something went wrong in booking check.");
            }
        });

    // $.ajax({
    //     type: 'POST',
    //     url: seats_check_api_endpoint,
    //     dataType: 'json',
    //     data: {
    //         subtrip_id: subtripid,
    //         ticket_token: random_token,
    //         seat_names: allseatnumber,
    //         journey_date: journeydate
    //     },
    //     success: function (response) {
    //         if (response.status == "success") {
    //             localStorage.setItem("_chkseats_token", random_token);
    //             $("#booking").submit();
    //             return true;
    //         }

    //         alert(response.message);
    //     }
    // });
}

function get_random_token(length) {
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const charactersLength = characters.length;
    let counter = 0;
    while (counter < length) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
        counter += 1;
    }
    return 'backend' + result;
}

function getSeatClassBySeatNo(seatNo) {

    if (!Array.isArray(seatclass)) {
        return 0;
    }
    // Loop through the seatClassData array
    for (let i = 0; i < seatclass.length; i++) {
        console.log(seatclass[i].seatNo, typeof seatclass[i].seatNo);

        if (seatclass[i].seatNo.includes(seatNo.toString())) {
        // if (seatclass[i].seatNo.split(',').includes(seatNo.toString())) {
        // if (seatclass[i].seatNo[0].split(',').includes(seatNo.toString())) {
            return seatclass[i].seatClass;
        }
    }
    // Return null if the seat number is not found
    return "0";
}

function getSeatPriceBySeatNo(seatNo) {

    if (!Array.isArray(seatclass)) {
        return regularFare;
    }
    // Loop through the seatClassData array
    console.log(seatclass);
    for (let i = 0; i < seatclass.length; i++) {
        console.log(seatclass[i].seatNo, typeof seatclass[i].seatNo);

        if (seatclass[i].seatNo.includes(seatNo.toString())) {
        // if (seatclass[i].seatNo.split(',').includes(seatNo.toString())) {
        // if (seatclass[i].seatNo[0].split(',').includes(seatNo.toString())) {

            console.log("asdasdasdasdasdasdas");
            return seatclass[i].fare;
        }
    }
    // Return null if the seat number is not found
    return regularFare;
}

// function latestupdateSeatCount(type, subtripid, numberseat = "", selectedSeatClass = "", selectedSeatPrice = "") {
//     selectedSeatClass = selectedSeatClass || "0";
//     numberseat = numberseat || "";

//     var divId = "AllSelectedSeatDiv_" + subtripid;
//     var seatTotalDiv = "seat_total_" + selectedSeatClass + "_" + subtripid;

//     if (type === "add") {
//         // Add the seat if not already present
//         if ($("#selectedAllClass" + selectedSeatClass + "_" + numberseat).length === 0) {
//             var inputField = $("<input>", {
//                 type: "hidden",
//                 id: "selectedAllClass" + selectedSeatClass + "_" + numberseat,
//                 name: "selectedAllClass[]",
//                 value: selectedSeatClass,
//                 class: "selectedAllClassInput"
//             }).attr("data-price", selectedSeatPrice);

//             if ($("#" + divId).length === 0) {
//                 $("<div>", { id: divId }).append(inputField).appendTo("body");
//             } else {
//                 $("#" + divId).append(inputField);
//             }
//         }
//     } 
    
//     else if (type === "remove") {
//         var inputId = "selectedAllClass" + selectedSeatClass + "_" + numberseat;
//         $("#" + inputId).remove();
//     }

//     var totalFare = 0;
//     var seatClassFare = {};  // Store fare by seat class

//     $(".selectedAllClassInput").each(function () {
//         var seatClass = $(this).val();
//         var seatPrice = parseFloat($(this).attr("data-price")) || 0;

//         totalFare += seatPrice;

//         // Group fare by seat class
//         if (!seatClassFare[seatClass]) {
//             seatClassFare[seatClass] = 0;
//         }
//         seatClassFare[seatClass] += seatPrice;
//     });

//     for (let seatClass in seatClassFare) {
//         $("#seat_total_" + seatClass + "_" + subtripid).text(seatClassFare[seatClass]);
//     }

//     $("#total_fare_" + subtripid).text(totalFare);

//     toprice(subtripid); 
// }