
Runner.pages.PageSettings.addPageEvent( 
	"Food_Pack_Priority", 
	"dashboard", 
	"afterPageReady", 
	function(pageObj, proxy, pageid, inlineRow, inlineObject, row ) {
		function initFoodpackSortable() {

    if (typeof $.fn.sortable !== "function") {
        console.log("jQuery UI sortable not loaded yet.");
        return;
    }

    $("#foodpack-sortable").sortable({
        handle: ".drag-handle",
        placeholder: "foodpack-placeholder",
        update: function () {
            $("#foodpack-sortable .foodpack-row").each(function (index) {
                $(this).find(".priority-badge").text(index + 1);
            });
        }
    });

    $("#foodpack-sortable").disableSelection();

    $("#save-ranking").off("click").on("click", function () {

        var orderedIds = [];

        $("#foodpack-sortable .foodpack-row").each(function () {
            orderedIds.push($(this).data("id"));
        });

        $.ajax({
            url: "save_foodpack_ranking.php",
            type: "POST",
            dataType: "json",
            data: {
                ordered_ids: orderedIds.join(",")
            },
            success: function (res) {
                if (res.success) {
                    $("#ranking-message").html("<span class='rank-success'>Ranking saved successfully.</span>");
                } else {
                    $("#ranking-message").html("<span class='rank-error'>" + res.message + "</span>");
                }
            },
            error: function () {
                $("#ranking-message").html("<span class='rank-error'>Server error while saving ranking.</span>");
            }
        });
    });
}

if (typeof $.fn.sortable === "function") {
    initFoodpackSortable();
} else {
    $.getScript("https://code.jquery.com/ui/1.13.2/jquery-ui.min.js")
        .done(function () {
            initFoodpackSortable();
        })
        .fail(function () {
            alert("Unable to load jQuery UI. Drag and drop will not work.");
        });
}
});







