function showAlert(message, type = "green") {
    Toastify({
        text: `${message}`,
        duration: 3000,
        close: true,
        gravity: "top",
        position: "right",
        backgroundColor: getBackgroundColor(type),
        stopOnFocus: true,
    }).showToast();
}

function handleFileChange(
    event,
    previewContainerId,
    previewImageId,
    fileLabelId = null
) {
    const input = event.target;
    const file = input.files && input.files[0];

    if (file && file.type.startsWith("image/")) {
        const reader = new FileReader();

        reader.onload = function (e) {
            const previewImage = document.getElementById(previewImageId);
            const previewContainer = document.getElementById(previewContainerId);

            if (previewImage && previewContainer) {
                previewImage.src = e.target.result;
                previewContainer.classList.remove("hidden");
            }

            if (fileLabelId) {
                const fileLabel = document.getElementById(fileLabelId);
                if (fileLabel) {
                    fileLabel.textContent = file.name;
                }
            }
        };

        reader.readAsDataURL(file);
    }
}

function formatDate(dateString) {
    if (!dateString) return "N/A";
    const date = new Date(dateString);

    const options = {
        year: "numeric",
        month: "short",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: true,
    };

    return date.toLocaleString("en-US", options);
}

function getBackgroundColor(type) {
    switch (type) {
        case "red":
        case "danger":
            return "#f87171";
        case "yellow":
        case "warning":
            return "#facc15";
        case "blue":
        case "info":
            return "#60a5fa";
        case "green":
        case "success":
        default:
            return "#34d399";
    }
}

    function recalculate_shipping() {
        var adminurl = $("#adminurl").val();
        var ids = $(".rcheckbox:checkbox:checked")
            .map(function () {
                return this.value;
            })
            .get();
    
        if (ids != "") {
            var err = 0;
            $.each(ids, function (i) {
                id = ids[i];
                var cn = $("#row_chk_" + id).data("id");
                update_amounts(cn, "weight", false);
            });
    
            showAlert("Caculation Process Completed.", "success");
            $("#" + "select_all").prop("checked", false);
            $("." + "select_all").prop("checked", false);
    
            setTimeout(function () {
                location.reload();
            }, 1200);
        } else {
            showAlert("No Orders Selected to Fetch Payments.", "error");
            return false;
        }
    }

function toggleActiveStatus(id, status, table, feild = "active") {
    const requestData = {
        id: id,
        status: status ? 1 : 0,
        table: table,
        feild: feild,
    };

    $.ajax({
        url: "/admin/toggleStatus",
        type: "POST",
        data: requestData,
        dataType: "json",
        success: function (response) {
            if (response.success) {
                showAlert(response.message, "green");
            } else {
                const missingFields = response.missing_fields;
                if (missingFields) {
                    for (const [field, message] of Object.entries(missingFields)) {
                        showAlert(`${field}: ${message}`, "red");
                    }
                } else {
                    showAlert(response.message, "red");
                }
            }
        },
        error: function (xhr, status, error) {
            console.error("Error:", xhr);
            showAlert("An error occurred while updating the status.", "red");
        },
    });
}

// Enhanced modal handling
document.addEventListener("DOMContentLoaded", () => {
    // Initialize all modals
    const modals = document.querySelectorAll('[id$="_modal"]');

    // Open modal function
    window.openModal = function (id) {
        const modal = document.getElementById(id);
        if (modal) {
            modal.classList.remove("hidden");
            document.body.classList.add("overflow-hidden");

            // Focus first input if exists
            const input = modal.querySelector("input, select, textarea");
            if (input) input.focus();
        }
    };

    // Close modal function
    window.closeModal = function (id) {
        const modal = document.getElementById(id);
        if (modal) {
            modal.classList.add("hidden");
            document.body.classList.remove("overflow-hidden");
        }
    };

    // Bind close buttons
    document.querySelectorAll("[data-modal-close]").forEach((btn) => {
        btn.addEventListener("click", () => {
            closeModal(btn.getAttribute("data-modal-close"));
        });
    });

    // Bind open buttons
    document.querySelectorAll("[data-modal-target]").forEach((btn) => {
        btn.addEventListener("click", () => {
            openModal(btn.getAttribute("data-modal-target"));
        });
    });

    // Close on ESC key
    document.addEventListener("keydown", (e) => {
        if (e.key === "Escape") {
            modals.forEach((modal) => {
                if (!modal.classList.contains("hidden")) {
                    closeModal(modal.id);
                }
            });
        }
    });

    // Close when clicking outside
    document.addEventListener("click", (e) => {
        if (e.target.classList.contains("backdrop-overlay")) {
            const modal = e.target.closest('[id$="_modal"]');
            if (modal) {
                closeModal(modal.id);
            }
        }
    });

    let shipped_ref = [];

    // Loadsheet generation logic
    window.generate_load_sheet_by_id = function () {
        let packages = $(".select_all:checked")
            .map(function () {
                return this.value;
            })
            .get();

        let err = 0;
        let id = 0;

        if (packages.length === 0) {
            showAlert("No orders selected to generate Load Sheet.", "red");
            return;
        }

        $.each(packages, function (i) {
            id = packages[i];
            let cn = $("#row_chk_" + id).data("cn");
            let ls = $("#row_chk_" + id).data("ls");
            let ss = $("#row_chk_" + id).data("ss");

            shipped_ref.push(cn);

            if (!cn || (ls && ls.length > 1) || ![3, 15, 16].includes(ss)) {
                err = 1;
                return false; // Break loop
            }
        });

        if (err > 0) {
            showAlert("Orders selected to generate Load Sheet are not valid.", "red");
            return;
        }

        // Show Tailwind modal
        openModal("loadsheet_modal");
    };

    // Bind generate button once
    $("#loadsheet_ok").on("click", function () {
        let courier_code = $("#courier_code").val().trim();
        let courier_name = $("#courier_name").val().trim();
        console.log(courier_code + courier_name);
        if (!courier_code || !courier_name) {
            showAlert("Courier details required.", "red");
            return;
        }

        closeModal("loadsheet_modal");

        $.post(
            "/admin/orders/generate-load-sheet-by-id",
            {
                ref: shipped_ref,
                courier_name: courier_name,
                courier_code: courier_code,
            },
            function (data) {
                console.log(data);
                return;
                showAlert("Loadsheet generated successfully.", "green");
                $("#tracking" + id).html(
                    '<div class="text-green-600 font-medium">Loadsheet Generated</div>'
                );
            }
        ).fail(function () {
            console.log(data);
            showAlert("Something went wrong. Please try again.", "red");
        });
    });
});

function download_load_sheet_by_id(loadsheet) {
    /*var adminurl = $("#adminurl").val();*/

    var adminurl = $("#adminurl").val();

    //var orders = $("input[class='select_all']:checked").map(function(){ return this.value; }).get().join(",");
    if (loadsheet !== "") {
        $.post(
            adminurl + "orders/download_load_sheet_by_id",
            { loadsheet: loadsheet },
            function (data) {
                if (data) {
                    var blob = new Blob([data.response], { type: "application/pdf" }); // change resultByte to bytes
                    var link = document.createElement("a");
                    link.href = window.URL.createObjectURL(blob);
                    link.download = "loadsheet.pdf";
                    link.click();
                } else {
                    $("#tracking" + id).html(
                        '<div class="alert alert-info">Loadsheet Generated.</div>'
                    );
                    $(".tracking" + id).html(
                        '<div class="alert alert-info">Loadsheet Generated.</div>'
                    );
                }
            }
        );
    } else {
        showAlert("No Orders Selected to Generate Consignments. ", "error");
        return false;
    }
}

function pay_status_bulk() {
    var id = 0;
    var packages = $(".select_all:checked")
        .map(function () {
            return this.value;
        })
        .get();
    if (packages !== "") {
        var err = 0;
        $.each(packages, function (i) {
            id = packages[i];
            active_paystatus_by_id(id);
        });

        showAlert("Bulk Paid Yes Process Completed. ", "green");
        $("#" + "select_all").prop("checked", false);
        $("." + "select_all").prop("checked", false);
    } else {
        showAlert("No Orders Selected to Paid Yes. ", "red");
        return false;
    }
}

function active_paystatus_by_id(id) {
    var adminurl = $("#adminurl").val();

    var active = 1;

    $.post(
        adminurl + "admin/active_inactive_paystatus_by_id",
        { id: id, active: active },
        function (response) {
            showAlert("Mark as Paid Successfully", "green");
        }
    ).fail(function (xhr) {
        console.error("Error: " + xhr.responseText); // Log detailed error
    });
}

function active_inactive_paystatus_by_id(id) {
    var adminurl = $("#adminurl").val();
    if ($("#active" + id).is(":checked")) {
        var active = 1;
    } else {
        var active = 0;
    }
    $.post(
        adminurl + "admin/active_inactive_paystatus_by_id",
        { id: id, active: active },
        function (response) {
            showAlert("Status Updated", "green");
        }
    ).fail(function (xhr) {
        console.error("Error: " + xhr.responseText); // Log detailed error
    });
}

document.addEventListener("DOMContentLoaded", function () {
    const dynamicChoicesFields = [
        {
            selector: "#city-choices",
            url: "/search-city",
            responseKey: "results",
            valueKey: "id",
            labelKey: "title",
        },
        {
            selector: "#delivery_city_id",
            url: "/search-city",
            responseKey: "results",
            valueKey: "id",
            labelKey: "title",
        },
        {
            selector: "#client-choices",
            url: "/search-client",
            responseKey: "results",
            valueKey: "id",
            labelKey: "company",
        },
        {
            selector: "#client-choices2",
            url: "/search-client",
            responseKey: "results",
            valueKey: "id",
            labelKey: "company",
        },
        {
            selector: "#riders-choices2",
            url: "/search-riders",
            responseKey: "results",
            valueKey: "id",
            labelKey: "rider_name",
        },
        {
            selector: "#riders-choices",
            url: "/search-riders",
            responseKey: "results",
            valueKey: "id",
            labelKey: "rider_name",
        },
    ];

    const instances = {};
    const debounceTimeouts = {};

    dynamicChoicesFields.forEach((field) => {
        const element = document.querySelector(field.selector);
        if (!element) return;

        const instance = new Choices(element, {
            searchEnabled: true,
            itemSelectText: "Press to select",
            removeItemButton: true,
            placeholder: true,
            allowHTML: false,
            renderChoiceLimit: -1,
            shouldSort: false,
            position: "auto",
            classNames: {
                containerOuter: "choices custom-choices-container",
            },
        });

        instances[field.selector] = instance;

        // Attach input listener
        document.addEventListener("input", function (e) {
            if (
                e.target.classList.contains("choices__input") &&
                element.closest(".choices")?.contains(e.target)
            ) {
                const searchTerm = e.target.value.trim();

                clearTimeout(debounceTimeouts[field.selector]);

                if (searchTerm.length < 3) {
                    instance.clearChoices();
                    return;
                }

                debounceTimeouts[field.selector] = setTimeout(() => {
                    fetch(`${field.url}?search=${encodeURIComponent(searchTerm)}`, {
                        method: "GET",
                        headers: {
                            Accept: "application/json",
                        },
                    })
                        .then((response) => response.json())
                        .then((data) => {
                            const results = field.responseKey
                                ? data[field.responseKey]
                                : data;
                            instance.clearChoices();

                            if (results && results.length > 0) {
                                const newOptions = results.map((item) => ({
                                    value: item[field.valueKey],
                                    label: item[field.labelKey],
                                }));

                                instance
                                    .setChoices(newOptions, "value", "label", true)
                                    .then(() => {
                                        // Force dropdown to show all items
                                        instance.showDropdown();
                                        const dropdown = element
                                            .closest(".choices")
                                            .querySelector(".choices__list--dropdown");
                                        if (dropdown) {
                                            dropdown.style.maxHeight = "none";
                                            dropdown.style.overflowY = "visible";
                                        }
                                    });
                            } else {
                                instance.setChoices(
                                    [
                                        {
                                            value: "",
                                            label: "No results found",
                                            disabled: true,
                                        },
                                    ],
                                    "value",
                                    "label",
                                    true
                                );
                            }
                        })
                        .catch((err) => {
                            console.error(`Error fetching ${field.url}:`, err);
                        });
                }, 500);
            }
        });
    });
});

function change_package_status(id,status = null) {
    var adminurl = $("#adminurl").val();
    if(status === null){
    var status = $("#status" + id).val();
    }else status = status;

    $.post(
        "/admin/orders/change_package_status",
        { id: id, status: status },
        function (data) {
           //showAlert("Status updated", "green");
        }
    );
}

function select_all(className) {
    const checkboxes = document.querySelectorAll("." + className);
    const masterCheckbox = document.getElementById(className);
    checkboxes.forEach((checkbox) => {
        checkbox.checked = masterCheckbox.checked;
    });
}

function change_package_shipper(id) {
    // var adminurl = $("#adminurl").val();
    var shipper = $("#shipper" + id).val();
     console.log(shipper);
     $.post("/admin/orders/change_package_shipper", { id: id, shipper: shipper }, function(data) {
       //  console.log(data);
     $('#shippertd' + id).append(data);
    // $('#shippertd' + id).html(data);

     if (data) { $("#status" + id).val("18"); }
     });
}

function printCN(divID) {
    var url = $("#url").val();

    var packages_ids = $("#packagesIDS").val();

    $.post(
        url + "general_functions/mark_as_print",
        { packages_ids: packages_ids },
        function (data) { }
    );

    var divElements = document.getElementById(divID).innerHTML;
    // console.log(divElements);
    var oldPage = document.body.innerHTML;

    //alert(oldPage);
    document.body.innerHTML =
        "<html><head><title></title></head><body>" + divElements + "</body></html>";

    window.print();
    document.body.innerHTML = oldPage;
}

function tracking_bulk() {
    var adminurl = $("#adminurl").val();
    var id = 0;
    var packages = $(".select_all:checked")
        .map(function () {
            return this.value;
        })
        .get();
    var shipped_ref = [];
    if (packages != "") {
        var err = 0;
        $.each(packages, function (i) {
            id = packages[i];
            var get_shipped_ref = $("#row_chk_" + id).data("cn");

            track_package_by_id(id, get_shipped_ref, 1);
        });

        showAlert("Bulk Tracking Process Completed. ", "green");
        $("#" + "select_all").prop("checked", false);
        $("." + "select_all").prop("checked", false);
    } else {
        showAlert("No Orders Selected to Generate Consignments. ", "red");
        return false;
    }
}

function track_package_by_id(id, ref, summary, process = 0) {
    var adminurl = $("#adminurl").val();
    // console.log(adminurl);

    $("#tracking" + id).html(
        '<div class="inline-block border-b-2 rounded-full size-3.5 animate-spin border-l-none border-custom-500"></div>'
    );
    $.post(
        adminurl + "admin/orders/track_package_by_id",
        { id: id, ref: ref, summary: summary, process: process },
        function (data) {
            // console.log(data);
            //  return;
            if (data) {
                $("#tracking" + id).html(data);
                $(".tracking" + id).html(data);
            } else {
                $("#tracking" + id).html(
                    '<div class="px-1 py-0.5 text-[11px]  font-medium rounded border bg-sky-100 border-sky-200 text-sky-500 dark:bg-sky-500/20 dark:border-sky-500/20">Consignment booked.</div>'
                );
                $(".tracking" + id).html(
                    '<div class="px-1 py-0.5 text-[11px]  font-medium rounded border bg-sky-100 border-sky-200 text-sky-500 dark:bg-sky-500/20 dark:border-sky-500/20">Consignment booked.</div>'
                );
            }
        }
    );
}

function track_package_by_oshi(id, store_id) {
    var adminurl = $("#adminurl").val();
    // console.log(adminurl);

    $("#oshi_tracking" + id).html(
        '<div class="inline-block border-b-2 rounded-full size-3.5 animate-spin border-l-none border-custom-500"></div>'
    );
    $.post(
        adminurl + "admin/orders/track_package_by_oshi",
        { id: id, store_id: store_id },
        function (data) {
            // console.log(data);
            //  return;
            if (data) {
                $("#oshi_tracking" + id).html(data);
                $(".oshi_tracking" + id).html(data);
            } else {
                $("#oshi_tracking" + id).html(
                    '<div class="px-1 py-0.5 text-[11px]  font-medium rounded border bg-sky-100 border-sky-200 text-sky-500 dark:bg-sky-500/20 dark:border-sky-500/20">Consignment booked.</div>'
                );
                $(".oshi_tracking" + id).html(
                    '<div class="px-1 py-0.5 text-[11px]  font-medium rounded border bg-sky-100 border-sky-200 text-sky-500 dark:bg-sky-500/20 dark:border-sky-500/20">Consignment booked.</div>'
                );
            }
        }
    );
}

function generate_cn() {
    var adminurl = $("#adminurl").val();

    var id = 0;
    var packages = $(".select_all:checked")
        .map(function () {
            return this.value;
        })
        .get();

    if (packages != "") {
        var err = 0;
        $.each(packages, function (i) {
            id = packages[i];

            var get_cn = $("#row_chk_" + id).data("cn");
            //     console.log(get_cn);
            if (get_cn == 0) {
                err = 1;
                return false;
            }
        });

        if (err > 0) {
            showAlert(
                "Consignment Can Be Generated For Only Those Orders Which are Marked" +
                "<br>" +
                "Ready to Process",
                "red"
            );
        } else {
            window.location = adminurl + "admin/orders/cn?packages=" + packages;
        }
    } else {
        showAlert("No Orders Selected to Generate Consignments.", "red");

        return false;
    }
}

function update_on_both_status_combo(v) {
    $(".bulk_status").val(v);
    //console.log($('.bulk_status').val());
}

function update_amounts(id, pfield) {
    var nvalue = $("#update_" + pfield + id).val();
    $.post(
        "/admin/update_amounts",
        { id: id, field: pfield, nvalue: nvalue },
        function (data) {
            if (data) {
                //  console.log(data);
                showAlert(pfield + " updated", "green");
            }
        }
    );
}

function bulk_change_order_status() {
    var adminurl = $("#adminurl").val();
    var status = $("#bulk_status").val();
    
    var id = 0;
    var packages = $(".select_all:checked")
        .map(function () {
            return this.value;
        })
        .get();
    if (packages != "") {
        var err = 0;
        $.each(packages, function (i) {
            id = packages[i];
            change_package_status(id,status)
        });

        showAlert("Bulk Status Process Completed. ", "green");
        $("#" + "select_all").prop("checked", false);
        $("." + "select_all").prop("checked", false);
    } else {
        showAlert("No Orders Selected to Change Status. ", "red");
        return false;
    }
}


function postex_paddress_new(id) {
    $.post("/admin/sellers/postex_paddress_new", { id: id }, function (data) {
        // Trim the response to avoid leading/trailing whitespaces
        data = data.trim();

        $("#api_status")
            .removeClass("hidden")
            .html("Response: " + data);
        // Check if the response contains "Code:" and extract the code
        if (data.includes("Code:")) {
            // Split the data by "Code:" and get the code part
            let parts = data.split("Code:");
            let code = parts[1].trim(); // Get the code after "Code:"

            // Show only the code in #postex_result{id}
            $("#postex_result" + id).html(code);
        } else {
            // If no "Code:" in response, clear the code div and show refresh button
            $("#postex_result" + id).html("");

            // Add the refresh button with data-lucide for the Lucide refresh icon
            $("#postex_result" + id).append(`
                <button onclick="window.location.reload();" class="px-2.5 py-0.5 inline-block text-xs font-medium rounded-full border bg-red-100 border-transparent text-red-500 dark:bg-red-500/20 dark:border-transparent">
                    refresh 
                </button>
            `);
        }
    });
}

function create_trax_paddress(id) {
    $.post("/admin/sellers/createTraxPaddress", { id: id }, function (data) {
        data = data.trim();

        // Show full response in api_status
        $("#api_status")
            .removeClass("hidden")
            .html("Response: " + data);

        // If response includes 'ID:', extract and show the ID
        if (data.includes("ID:")) {
            let parts = data.split("ID:");
            let idCode = parts[1].trim();
            $("#trax_result" + id).html(idCode);
        } else {
            // Error case: show refresh icon and error message
            $("#trax_result" + id).html(`
                <button onclick="window.location.reload();" class="px-2.5 py-0.5 inline-block text-xs font-medium rounded-full border bg-red-100 border-transparent text-red-500 dark:bg-red-500/20 dark:border-transparent">
                        refresh
                </button>
            `);
        }
    });
}

function mnp_cost_center_new(id) {
    $.post("/admin/sellers/mnp_cost_center_new", { id: id }, function (data) {
        data = data.trim();

        // Show full response in api_status
        $("#api_status")
            .removeClass("hidden")
            .html("Response: " + data);

        // If response includes 'ID:', extract and show the ID
        if (data.includes("ID:")) {
            let parts = data.split("ID:");
            let idCode = parts[1].trim();
            $("#mnp_result" + id).html(idCode);
        } else {
            // Error case: show refresh icon and error message
            $("#mnp_result" + id).html(`
                <button onclick="window.location.reload();" type="button" class="px-2.5 py-0.5 inline-block text-xs font-medium rounded-full border bg-red-100 border-transparent text-red-500 dark:bg-red-500/20 dark:border-transparent">
                        refresh
                </button>
            `);
        }
    });
}

function tcs_cost_center_new(id) {
    $.post(
        "/admin/sellers/tcs_cost_center_new",
        { id: id, shipper: null },
        function (data) {
            data = data.trim();

            // Show full response in api_status
            $("#api_status")
                .removeClass("hidden")
                .html("Cost Center Code: " + data);

            // If response includes a cost center code, extract and show
            if (data.includes("Code:")) {
                let parts = data.split("Code:");
                let code = parts[1].trim();
                $("#tcs_result" + id).html(code);
            } else {
                // Error case: show refresh icon and error message
                $("#tcs_result" + id).html(`
                <button onclick="window.location.reload();" class="px-2.5 py-0.5 inline-block text-xs font-medium rounded-full border bg-red-100 border-transparent text-red-500 dark:bg-red-500/20 dark:border-transparent">
                        refresh
                </button>
            `);
            }
        }
    );
}


function tranzo_cost_center(id) {
    $.post(
        "/admin/sellers/tranzo_cost_center",
        { id: id, shipper: null },
        function (data) {
            data = data.trim();

            // Show Full Response
            $("#api_status")
                .removeClass("hidden")
                .html("Response: " + data);

            // Check if it contains "Successfully"
            if (data.includes("Successfully")) {
                // Extract Code
                let codeMatch = data.match(/Code:\s*([^\s|]+)/);
                let code = codeMatch ? codeMatch[1] : null;

                if (code) {
                    $("#tranzo_result" + id).html(code);
                    $("#api_error").addClass("hidden");
                } else {
                    $("#tranzo_result" + id).html("Code not found");
                }
            }
            // Error Case
            else if (data.includes("API Error") || data.includes("Invalid") || data.includes("Client not found")) {
                $("#api_error")
                    .removeClass("hidden")
                    .html(
                        "<b>API Error:</b> " + data +
                        `<br><button onclick="window.location.reload();" 
                            class="px-2.5 py-0.5 inline-block text-xs font-medium rounded-full border 
                                   bg-red-100 border-transparent text-red-500 dark:bg-red-500/20 dark:border-transparent">
                                Refresh
                        </button>`
                    );
                $("#tranzo_result" + id).html("Error");
            }
            // Any other response
            else {
                $("#tranzo_result" + id).html("Unexpected Response");
            }
        }
    );
}


function do_cost_center_new(pid) {
    $.post(
        "/admin/sellers/do_cost_center_new",
        { id: pid, shipper: null },
        function (data) {
            data = data.trim();

            // Show full raw response in debug area
            $("#api_status")
                .removeClass("hidden")
                .html("Response: " + data);

            // Extract ID from the response using regex
            const match = data.match(/ID:\s*(\d+)/);

            if (match && match[1]) {
                // ID found, show in span
                $("#do_result" + pid).html(match[1]);
            } else {
                // No ID found, show refresh button
                $("#do_result" + pid).html(`
                <button onclick="window.location.reload();" class="px-2.5 py-0.5 inline-block text-xs font-medium rounded-full border bg-red-100 border-transparent text-red-500 dark:bg-red-500/20 dark:border-transparent">
                    refresh
                </button>
            `);
            }
        }
    );
}

function tcso_cost_center_new(id) {
    $.post(
        "/admin/sellers/tcso_cost_center_new",
        { id: id, shipper: 8 },
        function (data) {
            data = data.trim();

            // Show full response in api_status
            $("#api_status")
                .removeClass("hidden")
                .html("Cost Center Code: " + data);

            // If response includes a cost center code, extract and show
            if (data.includes("Code:")) {
                let parts = data.split("Code:");
                let code = parts[1].trim();
                $("#tcso_result" + id).html(code);
            } else {
                // Error case: show refresh icon and error message
                $("#tcso_result" + id).html(`
                <button onclick="window.location.reload();" class="px-2.5 py-0.5 inline-block text-xs font-medium rounded-full border bg-red-100 border-transparent text-red-500 dark:bg-red-500/20 dark:border-transparent">
                        refresh
                </button>
            `);
            }
        }
    );
}

function leo_cost_center_new(id) {
    $.post(
        "/admin/sellers/leo_cost_center_new",
        {
            id: id,
        },
        function (data) {
            $("#api_status")
                .removeClass("hidden")
                .html("Cost Center Code: " + data);
            $("#leo_result" + id).html(data);
        }
    );
}

function blueex_cost_center_new(id) {
    $.post(
        "/admin/sellers/blueex_cost_center_new",
        {
            id: id,
        },
        function (data) {
            $("#api_status")
                .removeClass("hidden")
                .html("Cost Center Code: " + data);
            $("#blueex_result" + id).html(data);
        }
    );
}

function rocket_cost_center_new(id) {
    $.post(
        "/admin/sellers/rocket_cost_center_new",
        {
            id: id,
        },
        function (data) {
            $("#api_status")
                .removeClass("hidden")
                .html("Cost Center Code: " + data);
            $("#rocket_result" + id).html(data);
        }
    );
}

function new_change_cn_status(e) {
    var adminurl = $("#adminurl").val();
    var status = $("#status").val();
    var id = $("#cn_number").val();
    var shipper = $("#shipper_req_id").val();

    if (e.keyCode === 13) {
        var tpkgs = parseInt($("#totalpkgs").html());

        $.post(
            "/admin/orders/change_cn_status",
            { id: id, status: status, shipper: shipper },
            function (response) {
                // Try to parse JSON safely
                let obj;
                try {
                    obj = typeof response === "object" ? response : JSON.parse(response);
                } catch (err) {
                    console.error("Invalid JSON:", err, response);
                    showAlert("Invalid response from server", "red");
                    return;
                }

                // Handle errors from backend
                if (obj == 2) {
                    showAlert("Same Status Cannot be Changed", "red");
                    $("#cn_number").val("");
                    return;
                }
                if (obj == 5) {
                    showAlert("Only Same Client Can be Scanned at a time", "red");
                    $("#cn_number").val("");
                    return;
                } else if (obj == 3 && status == 10) {
                    showAlert(
                        "First Mark to Ready to Ship -- Order is not Marked Ready to Ship",
                        "red"
                    );
                    $("#cn_number").val("");
                    return;
                } else if (obj == 3 && status == 9) {
                    showAlert(
                        "First Mark to Shipped -- Order is not Marked Shipped",
                        "red"
                    );
                    $("#cn_number").val("");
                    return;
                }

                // Success Case
                tpkgs++;
                $("#totalpkgs").html(tpkgs);
                //console.log(obj);
                // Append row to table
                var txt =
                    "<tr>" +
                    '<td class="px-3.5 py-2.5 font-semibold border-b border-slate-200 dark:border-zink-500 text-sm">' +
                    id +
                    "</td>" +
                    '<td class="px-3.5 py-2.5 font-semibold border-b border-slate-200 dark:border-zink-500 text-sm">' +
                    obj.shipment_services +
                    "</td>" +
                    '<td class="px-3.5 py-2.5 font-semibold border-b border-slate-200 dark:border-zink-500 text-sm">' +
                    obj.clients +
                    "</td>" +
                    '<td class="px-3.5 py-2.5 font-semibold border-b border-slate-200 dark:border-zink-500 text-sm">' +
                    obj.current_status +
                    "</td>" +
                    '<td class="px-3.5 py-2.5 font-semibold border-b border-slate-200 dark:border-zink-500 text-sm">' +
                    obj.last_status +
                    "</td>" +
                    "</tr>";
                $("#status_change_tbl").append(txt);

                // Set shipper input
                $("#shipper_req_id").val(obj.shipment_services);

                // Success message
                showAlert("Status updated", "green");
                $("#cn_number").val("");
            }
        );
    }
}


function printDiv(divID) {
    var divElements = document.getElementById(divID).innerHTML;
    var oldPage = document.body.innerHTML;
    document.body.innerHTML =
        "<html><head><title></title></head><body>" + divElements + "</body>";
    window.print();
    document.body.innerHTML = oldPage;
}

function cn_report_bulk_action() {
    var adminurl = $("#adminurl").val();
    var ids = $(".rcheckbox:checkbox:checked")
        .map(function () {
            return this.value;
        })
        .get();
    ids = ids.join(",");
    var amount_received = $("#bulk_amount_received").val();

    var client_id = $("#client_i_d").val();
    // Console log all variables

    if (ids == "") {
        showAlert("Please select record to apply bulk action.", "red");
        return false;
    } else {
        $.post(
            "report/cn_report_bulk_action",
            {
                ids: ids,
                amount_received: amount_received,
                client_id: client_id,
            },
            function (data) {
                // console.log(data);
                if (data == 1) {
                    showAlert("Status Changed", "green");

                    location.reload();
                } else {
                    showAlert("Sorry! there is problem in applying bulk action.", "red");
                }
            }
        );
    }
}

$(document).on("click", "[data-delete-button]", function () {
    const table = $(this).data("table");
    const id = $(this).data("id");
    const field = $(this).data("field");
    const value = $(this).data("value");

    $("#deleteRecord")
        .off("click")
        .on("click", function () {
            performDelete(table, id, field, value);
        });
});

function performDelete(table, id, field, value) {
    const requestData = {
        table: table,
        id: id,
        field: field,
        value: value,
    };

    $.ajax({
        url: "/generalfunction/universalDelete",
        type: "POST",
        data: requestData,
        dataType: "json",
        success: function (response) {
            console.log(response);
            if (response.success) {
                showAlert(response.message, "green");
                const row = $(`tr[data-id="${id}"]`);

                if (row.length) {
                    // Store original dimensions
                    const originalHeight = row.outerHeight();
                    const originalPadding = {
                        top: parseInt(row.css("padding-top")),
                        bottom: parseInt(row.css("padding-bottom")),
                    };

                    // Prepare row for animation
                    row.css({
                        height: originalHeight + "px",
                        overflow: "hidden",
                        "will-change": "transform, opacity", // Better performance
                    });

                    // Create smooth animation timeline
                    const tl = gsap.timeline({
                        defaults: { ease: "power2.inOut" },
                        onComplete: () => {
                            row.remove();
                            // Animate subsequent rows up after removal
                            gsap.to(row.nextAll(), {
                                y: 0,
                                duration: 0.3,
                                ease: "back.out(1)",
                            });
                        },
                    });

                    // Animation sequence
                    tl.to(row, {
                        backgroundColor: "#f1f5f9",
                        duration: 0.3,
                        ease: "power2.out",
                    })
                        .to(
                            row,
                            {
                                keyframes: [
                                    { x: 8, duration: 0.08 },
                                    { x: -16, duration: 0.12 },
                                    { x: 0, duration: 0.1 },
                                ],
                                opacity: 0.6,
                            },
                            ">"
                        )
                        .to(
                            row,
                            {
                                height: 0,
                                paddingTop: 0,
                                paddingBottom: 0,
                                marginTop: 0,
                                marginBottom: 0,
                                opacity: 0,
                                duration: 0.35,
                            },
                            ">-=0.1"
                        )
                        .to(
                            row.nextAll(),
                            {
                                duration: 0.4,
                                ease: "back.out(0.8)",
                                stagger: 0.02,
                            },
                            "<0.2"
                        );
                }
            } else {
                showAlert(response.message, "red");
            }
        },
        error: function (xhr) {
            console.error("Error:", xhr);
            showAlert("An error occurred while deleting the record.", "red");
        },
    });
}

function payments_bulk() {
    var adminurl = $("#adminurl").val();
    var ids = $(".rcheckbox:checkbox:checked")
        .map(function () {
            return this.value;
        })
        .get();
    // console.log(ids);
    if (ids != "") {
        var err = 0;
        $.each(ids, function (i) {
            id = ids[i];
            var cn = $("#row_chk_" + id).data("cn");
            //console.log(cn);
            get_courier_charges(cn);
        });

        showAlert("Bulk Payments Sync Process Completed. ", "green");
        $("#" + "select_all").prop("checked", false);
        $("." + "select_all").prop("checked", false);
    } else {
        showAlert("No Orders Selected to Fetch Payments. ", "red");
        return false;
    }
}

function get_courier_charges(id) {
    // Tailwind spinner
    $("#get_charges" + id).html(
        '<div class="inline-block border-2 rounded-full size-4 animate-spin border-l-transparent border-[#df0a0b]"></div>'
    );

    $.post("/admin/reports/get_courier_charges", { id: id }, function (data) {
        if (data) {
            // console.log(data);
            $("#new_charges" + id).html(
                '<div class="rounded-md border border-green-200 bg-green-50 text-green-700 text-sm p-2">' +
                data +
                "</div>"
            );
            $("#get_charges" + id).addClass("hidden");
        } else {
            $("#new_charges" + id).html(
                '<div class="rounded-md border border-red-200 bg-red-50 text-red-700 text-sm p-2">error in sync.</div>'
            );
            $("#get_charges" + id).addClass("hidden");
        }

        if (window.lucide) {
            lucide.createIcons(); // Lucide icons render
        }
    });
}

function taxes_bulk() {
    var adminurl = $("#adminurl").val();
    var ids = $(".rcheckbox:checkbox:checked")
        .map(function () {
            return this.value;
        })
        .get();
    // console.log(ids);
    if (ids != "") {
        var err = 0;
        $.each(ids, function (i) {
            id = ids[i];
            var cn = $("#row_chk_" + id).data("cn");
            add_taxes(cn);
        });

        showAlert("Bulk Payments Sync Process Completed. ", "green");
        window.location.href;
    } else {
        showAlert("No Orders Selected to Fetch Payments. ", "red");
        return false;
    }
}

function add_taxes(id, salert = true) {
    $.post("/admin/reports/add_taxes", { id: id }, function (data) {
        let response = typeof data === "string" ? JSON.parse(data) : data;

        if (response.success) {
            if (salert) showAlert(response.message, "green");
        } else {
            showAlert(response.message, "red");
        }

        $("#get_charges" + id).addClass("hidden");

        if (window.lucide) {
            lucide.createIcons(); // Lucide icons render
        }
    }).fail(function () {
        showAlert("Server error occurred", "red");
        $("#get_charges" + id).addClass("hidden");
    });
}

function bulk_generate_invoice() {
    var id = 0;
    var packages = $(".select_all:checked")
        .map(function () {
            return this.value;
        })
        .get();
    if (packages != "") {
        var err = 0;
        $.each(packages, function (i) {
            id = packages[i];
            auto_invoice_received(id);
        });

        showAlert("Bulk Paid Yes Process Completed. ", "green");
        $("#" + "select_all").prop("checked", false);
        $("." + "select_all").prop("checked", false);
    } else {
        showAlert("No Orders Selected to Generate Invoice. ", "red");
        return false;
    }
}

function auto_invoice_received(cid) {
    var adminurl = $("#adminurl").val();
    var ids = $("#" + cid + "_ids").val();
    var total_orders = $("#" + cid + "_shipping_total").val();
    var company = $("#" + cid + "_company").val();
    var total_amount = $("#" + cid + "_deliveredamount").val();
    var shipping = $("#" + cid + "_shippingcharges").val();
    var wht = $("#" + cid + "_wht").val();
    var sst = $("#" + cid + "_sst").val();
    var adjustments = $("#" + cid + "_adjustments").val();
    var payable = $("#" + cid + "_deliveredpayable").val();
    var client_id = cid;
    //console.log(adminurl+"\n"+ids+"\n"+total_orders+"\n"+company+"\n"+total_amount+"\n"+shipping+"\n"+courier_shipping+"\n"+gross_profit+"\n"+payable+"\n"+agency_payable+"\n"+net_profit+"\n"+client_id);
    if (ids == "") {
        showAlert("Cannot Process Payment.", "error");
        return false;
    } else {
        $("#" + cid + "_button").html(
            '<div class="text-center"><i class="fa fa-spinner fa-pulse"></i> Processing ..</div>'
        );
        $.post(
            adminurl + "/admin/generate/report/auto_invoice_received",
            {
                ids: ids,
                total_orders: total_orders,
                company: company,
                total_amount: parseFloat(total_amount.replace(/,/g, "")),
                shipping: parseFloat(shipping.replace(/,/g, "")),
                wht: parseFloat(wht.replace(/,/g, "")),
                sst: parseFloat(sst.replace(/,/g, "")),
                adjustments: parseFloat(adjustments.replace(/,/g, "")),
                payable: parseFloat(payable.replace(/,/g, "")),
                client_id: client_id,
            },
            function (data) {
                // console.log(data);
                if (data == 0) {
                    $("#" + cid + "_button").hide();
                    $("#" + cid + "_invoice_alert").html(
                        '<div class=" max-w-32  text-wrap px-1 py-0.5 text-[11px] inline-block font-medium rounded border bg-red-100 border-red-200 text-red-500 dark:bg-red-500/20 dark:border-red-500/20">Invoice Not Processed Due to Error / Invoice Already Exists:.</div>'
                    );
                } else if (data) {
                    $("#" + cid + "_invoice_alert").html(
                        '<div class=" max-w-32  text-wrap px-1 py-0.5 text-[11px] inline-block font-medium rounded border bg-green-100 border-green-200 text-green-500 dark:bg-green-500/20 dark:border-green-500/20">' +
                        data +
                        "</div>"
                    );
                    $("#" + cid + "_button").hide();
                }
            }
        );
    }
}

function bulk_generate_invoice_all() {
    var id = 0;
    var packages = $(".select_all:checked")
        .map(function () {
            return this.value;
        })
        .get();
    if (packages != "") {
        var err = 0;
        $.each(packages, function (i) {
            id = packages[i];
            auto_invoice_received_all(id);
        });

        showAlert("Bulk Paid Yes Process Completed. ", "green");
        $("#" + "select_all").prop("checked", false);
        $("." + "select_all").prop("checked", false);
    } else {
        showAlert("No Orders Selected to Generate Invoice. ", "red");
        return false;
    }
}

function auto_invoice_received_all(cid) {
    var adminurl = $("#adminurl").val();
    var ids = $("#" + cid + "_ids").val();
    var aids = $("#" + cid + "_aids").val();
    var total_orders = $("#" + cid + "_shipping_total").val();
    var arrival_orders = $("#" + cid + "_ashipping_total").val();
    var company = $("#" + cid + "_company").val();
    var total_amount = $("#" + cid + "_deliveredamount").val();
    var shipping = $("#" + cid + "_shippingcharges").val();
    var charged_adv_shipping = $("#" + cid + "_charged_adv_shipping").val();
    var net_shipping = $("#" + cid + "_netshipping").val();
    var wht = $("#" + cid + "_wht").val();
    var sst = $("#" + cid + "_sst").val();
    var gst = $("#" + cid + "_gst").val();
    var adv_shipping = $("#" + cid + "_adv_shipping").val();
    var adjustments = $("#" + cid + "_adjustments").val();
    var payable = $("#" + cid + "_deliveredpayable").val();
    var client_id = cid;

    //console.log(adminurl+"\n"+ids+"\n"+total_orders+"\n"+company+"\n"+total_amount+"\n"+shipping+"\n"+courier_shipping+"\n"+gross_profit+"\n"+payable+"\n"+agency_payable+"\n"+net_profit+"\n"+client_id);
    if ((!ids || ids.trim() === "") && (!aids || aids.trim() === "")) {
        showAlert("Cannot Process Payment." + aids, "red");
        return false;
    } else {
        $("#" + cid + "_button").html(
            '<div class="text-center"><i class="fa fa-spinner fa-pulse"></i> Processing ..</div>'
        );
        $.post(
            adminurl + "admin/generate/invoices/auto_invoice_received_all",
            {
                ids: ids,
                aids: aids,
                total_orders: total_orders,
                arrival_orders: arrival_orders,
                company: company,
                total_amount: parseFloat(total_amount.replace(/,/g, "")),
                shipping: parseFloat(shipping.replace(/,/g, "")),
                charged_adv_shipping: parseFloat(
                    charged_adv_shipping.replace(/,/g, "")
                ),
                net_shipping: parseFloat(net_shipping.replace(/,/g, "")),
                wht: parseFloat(wht.replace(/,/g, "")),
                sst: parseFloat(sst.replace(/,/g, "")),
                gst: parseFloat(gst.replace(/,/g, "")),
                adv_shipping: parseFloat(adv_shipping.replace(/,/g, "")),
                adjustments: parseFloat(adjustments.replace(/,/g, "")),
                payable: parseFloat(payable.replace(/,/g, "")),
                client_id: client_id,
            },
            function (data) {
                // console.log(data);
                if (data == 0) {
                    $("#" + cid + "_button").hide();
                    $("#" + cid + "_invoice_alert").html(
                        '<div class="px-1 py-0.5 text-[11px] inline-block font-medium rounded border bg-red-100 border-red-200 text-red-500 dark:bg-red-500/20 dark:border-red-500/20">Invoice Not Processed Due to Error / Invoice Already Exists:.</div>'
                    );
                } else if (data) {
                    $("#" + cid + "_invoice_alert").html(
                        '<div class="px-1 py-0.5 text-[11px] inline-block font-medium rounded border bg-green-100 border-green-200 text-green-500 dark:bg-green-500/20 dark:border-green-500/20">' +
                        data +
                        "</div>"
                    );
                    $("#" + cid + "_button").hide();
                    /*$("#" + cid + "_row_id").css({ position: "relative" }).animate({
                          opacity: 0,
                          transform: "scale(0.9)", // Slight shrink effect
                          marginLeft: "150px" // Move it to the right smoothly
                      }, 2000, "swing", function() {
                          $(this).slideUp(200, function() {
                              $(this).remove();
                          });
                      });*/
                }
            }
        );
    }
}

window.generate_load_sheet = function () {
    let packages = $(".select_all:checked")
        .map(function () {
            return this.value;
        })
        .get();

    if (packages.length === 0) {
        showAlert("No orders selected to generate Load Sheet.", "red");
        return;
    }

    let riderId = $('select[name="rider"]').val();

    $.post(
        "/admin/orders/generate-load-sheet",
        {
            rider: riderId,
            ids: packages,
        },
        function (res) {
            if (res.status === "success" && res.redirect) {
                window.location.href = res.redirect;
            } else {
                showAlert(res.message || "Failed to generate Load Sheet.", "red");
            }
        },
        "json"
    ).fail(function () {
        showAlert("Something went wrong. Please try again.", "red");
    });
};


window.generate_return_sheet_by_id = function () {
    let packages = $(".select_all:checked")
        .map(function () {
            return this.value;
        })
        .get();

    if (packages.length === 0) {
        showAlert("No orders selected to Return Sheet.", "red");
        return;
    }

    let riderId = $('select[name="rider"]').val();

    $.post(
        "/admin/orders/generate-return-sheet",
        {
            rider: riderId,
            ids: packages,
        },
        function (res) {
            if (res.status === "success" && res.redirect) {
                window.location.href = res.redirect;
            } else {
                showAlert(res.message || "Failed to generate Return Sheet.", "red");
            }
        },
        "json"
    ).fail(function () {
        showAlert("Something went wrong. Please try again.", "red");
    });
};


window.generate_delivery_sheet_by_id = function () {
    let packages = $(".select_all:checked")
        .map(function () {
            return this.value;
        })
        .get();

    if (packages.length === 0) {
        showAlert("No orders selected to Delivery Sheet.", "red");
        return;
    }

    let riderId = $('select[name="rider"]').val();

    $.post(
        "/admin/orders/generate-delivery-sheet",
        {
            rider: riderId,
            ids: packages,
        },
        function (res) {
            if (res.status === "success" && res.redirect) {
                window.location.href = res.redirect;
            } else {
                showAlert(res.message || "Failed to generate Delivery Sheet.", "red");
            }
        },
        "json"
    ).fail(function () {
        showAlert("Something went wrong. Please try again.", "red");
    });
};
