$(document).ready(function () {
    $("body").on("keyup", ".ssearch", getSearchData);
    $("body").on("click", ".sload", getSearchData);
    $("body").on("click", "#search", getSearchData);
    $("body").on("blur", ".marka", showCMBModal);
    $("body").on("change", ".customer", getCustMarka);
    $("body").on("keyup change blur", ".len, .brea, .heig, .cartcount", calCMB);
    //    $("body").on("click", ".closeModal", closeCMBModal);
    $("body").off('click').on("click", '.remove', remove);
    $("body").on("change", ".cbmdetail", RemoveRD);

    RemoveRD();
    function RemoveRD() {
        var cbmdetail = $('.cbmdetail').val();

        if (cbmdetail == "Y") {
            $('.nocart, .totcbm').attr('readonly', true);
            $('.totcbm').attr({
                'readonly': true,
                'tabindex': -1
            });
        } else {
            $('.nocart, .totcbm').removeAttr('readonly tabindex');
        }
    }

    toggleRemarksDiv();
    function toggleRemarksDiv() {
        var overflowValue = $('#overflowInput').val();

        if (parseFloat(overflowValue) > 0) {
            $('#remarksDiv').show(); // Show the remarks div
        } else {
            $('#remarksDiv').hide(); // Hide the remarks div
        }
    }

    // Trigger check when overflow input changes
    $('#overflowInput').on('input', function () {
        toggleRemarksDiv();
    });


    $("body").on("click", ".cartlabel", function () {
        showCMBModal(1);
    });

    sessionStorage.removeItem('cartonTableData');


    $('#addnew').click(function () {
        AddRows();
    });
    function remove() {
        $(this).closest("tr").remove();
        calCMB();
    }

    function AddRows() {
        var ctr = $('#items').val();
        var focusFld = ".focusFld_" + ctr;
        $.post('shipment_add.php', { ctr: ctr }, function (data) {
            $(data).appendTo('.detbody');

            $(focusFld).focus();
            ctr++;
            $('#items').val(ctr);
        });
    }


    function getCustMarka() {
        var customer = $(".customer").val();
        $.post('getcustmarka.php', { customer: customer }, function (data) {
            $('.mobileno').val(data.mobileno);
            // $('.marka').val(data.marka);
        }, 'json');
    }

    $('.closeModal').click(function () {
        $('.cmbModal').modal('hide'); // Hide the Bootstrap modal

        // Save table data
        var tableData = [];

        $('.detbody tr').each(function () {
            var row = {
                srno: $(this).find('input[name^="srno"]').val(),
                len: $(this).find('input[name^="len"]').val(),
                brea: $(this).find('input[name^="brea"]').val(),
                heig: $(this).find('input[name^="heig"]').val(),
                cartcount: $(this).find('input[name^="cartcount"]').val(),
                cbm: $(this).find('input[name^="cbm"]').val(),
                canRemove: true
            };
            tableData.push(row);
        });

        // Store the data in sessionStorage (can be changed to localStorage)
        sessionStorage.setItem('cartonTableData', JSON.stringify(tableData));

        console.log('Stored carton table data:', tableData);
    });

    function calCMB() {
        var tr = $(this).closest("tr"),
            totcbm = 0,
            totcart = 0,
            len = tr.find(".len").val(),
            brea = tr.find(".brea").val(),
            heig = tr.find(".heig").val(),
            cartcount = tr.find(".cartcount").val(),
            cbm = ((len * brea * heig) / 1000000).toFixed(2);
        if (parseFloat(cartcount) > 1) {
            cbm = cbm * cartcount;
        }
        tr.find(".cbm").val(cbm);

        $(".cartcount").each(function () {
            if (!isNaN(this.value) && this.value.lenght != 0) {
                totcart += parseFloat(this.value);
            }
        });
        $(".nocart").val(totcart);
        $(".tcart").text(totcart);
        $(".cbm").each(function () {
            if (!isNaN(this.value) && this.value.lenght != 0) {
                totcbm += parseFloat(this.value);
            }
        });
        $(".totcbm").val(totcbm.toFixed(2));
        $(".tcbm").text(totcbm.toFixed(2));
    }



    function showCMBModal(par) {
        var nocart = $(".nocart").val();
        var cbmdetail = $(".cbmdetail").val();
        var vouchno = $(".vouchno").val();
        par = (par > 0) ? par : 0;

        var storedData = sessionStorage.getItem('cartonTableData');

        if (cbmdetail == "Y") {
            if (storedData) {

                var tableData = JSON.parse(storedData);
                $('.detbody').html(""); // clear existing rows

                // Rebuild table from sessionStorage data
                for (var i = 0; i < tableData.length; i++) {
                    var row = tableData[i];
                    var removeIcon = row.canRemove
                        ? `<i class='fa fa-close remove' style='cursor:pointer;'></i>`
                        : '';
                    var html = `<tr>
                        <td>${removeIcon}</td>
                <td><input type="text" name="srno_${i}" class="srno form-control text-right formins" value="${row.srno}" readonly tabindex="-1"></td>
                <td><input type="number" step="any" name="len_${i}" class="len form-control text-right formins" value="${row.len}"></td>
                <td><input type="number" step="any" name="brea_${i}" class="brea form-control text-right formins" value="${row.brea}"></td>
                <td><input type="number" step="any" name="heig_${i}" class="heig form-control text-right formins" value="${row.heig}"></td>
                <td><input type="number" step="any" name="cartcount_${i}" class="cartcount form-control text-right formins" value="${row.cartcount}"></td>
                <td><input type="number" step="any" name="cbm_${i}" class="cbm form-control text-right formins" value="${row.cbm}" readonly tabindex="-1"></td>
            </tr>`;
                    $('.detbody').append(html);
                }

                $('.detbody').append(`<input type="hidden" name="items" id="items" value="${tableData.length}">
                              <input type="hidden" id="par" value="${par}">`);

                // Apply read-only logic if par == 1
                if (par == 1) {
                    $(".formins").prop("readonly", true);
                }

                $(".cmbModal").modal("show");

            } else {
                // No sessionStorage data, proceed with AJAX
                $.post('get_cbmdata.php', { vouchno: vouchno, par: par }, function (data) {
                    $('.detbody').html("");
                    $(data).appendTo('.detbody');
                    $(".cmbModal").modal("show");
                });
            }
        }
    }


    ////////////////////////////////////////////// Search Part - Start //////////////////////////////////////////////
    $(".snoRecord").hide();
    $(".sloader").hide();


    var imrangeFrom = 0,
        imrangeTo = 40;

    function getSearchData(pagination) {

        $(".sloader").show();

        if (pagination == 'prev') {
            if (imrangeFrom > 0) {
                imrangeFrom = (imrangeFrom - 40);
                imrangeTo = (imrangeTo - 40);
            }
        }
        if (pagination == 'next') {
            imrangeFrom = (imrangeFrom + 40);
            imrangeTo = (imrangeTo + 40);
        }

        var series = $(".series").val(),
            vouchno = $(".vouchno").val(),
            ssearch = $(".ssearch").val(),
            sfield = $(".sfield").val(),
            sortBy = $(".sortBy").val(),
            orderAs = $(".orderAs").val(),
            soperator = $(".soperator").val(),
            data = {
                ssearch: ssearch, sfield: sfield, sortBy: sortBy, orderAs: orderAs, soperator: soperator,
                series: series, vouchno: vouchno, rangeFrom: imrangeFrom, rangeTo: imrangeTo
            },
            values = "";
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: "shipment_search.php",
            data: data,
            success: function (response) {
                if (response == "") {
                    $(".snoRecord").show();
                    $(".snext").hide();
                } else {
                    $(".snext").show();
                    $(".snoRecord").hide();

                    $.each(response, function () {
                        values += "<tr class='clickable-row' data-href='" + this.action + "'>" +
                            "<td align='left'>" + this.vouchno + "</td>" +
                            "<td align='left'>" + this.mydt + "</td>" +
                            "<td align='left'>" + this.customer + "</td>" +
                            "<td align='left'>" + this.supplier + "</td>" +
                            "<td align='left'>" + this.marka + "</td>" +
                            "<td align='left'>" + this.origin + "</td>" +
                            "<td align='left'>" + this.containerno + "</td>" +
                            "<td align='left'>" + this.destination + "</td>" +
                            "<td align='left'><a href='" + this.action + "' ><i class='fa fa-pencil'></i></a></td>" +
                            "</tr>";
                    });
                    $(".sloader").hide();
                    $(".sTbody").empty();
                    $(".sTbody").html(values);
                    if (response) {
                        $(".search-action-bar").show();
                    }
                }
                $(".ssearch").focus();

            },
            error: function (request, textStatus, errorThrown) {

            }
        });
    }
    $("#search").click(function () {
        $(".searchModal").on('shown.bs.modal', function () {
            $(".ssearch").focus();
            $(".ssearch").val("");
            $(".sfield").val("1");
            getSearchData();
        });

        getSearchData();
    });
    $(".sprev").click(function () {
        getSearchData('prev');
    });
    $(".snext").click(function () {
        getSearchData('next');
    });
    ////////////////////////////////////////////// Search Part - End //////////////////////////////////////////////
});