/**
 * Reusable Delete Confirmation Modal
 * Usage: Add data-delete-url attribute to any delete button
 * Example: <button class="btn btn-danger" data-delete-url="/admin/add-stocks/1">Delete</button>
 */

$(document).ready(function () {
    // Handle delete button clicks
    $(document).on("click", "[data-delete-url]", function (e) {
        e.preventDefault();

        const deleteUrl = $(this).data("delete-url");
        const customMessage = $(this).data("delete-message");

        // Set the delete URL in the hidden form
        $("#deleteForm").attr("action", deleteUrl);

        // Set custom message if provided
        if (customMessage) {
            $("#deleteModalMessage").text(customMessage);
        } else {
            $("#deleteModalMessage").text(
                "This action cannot be undone and will permanently remove the record."
            );
        }

        // Show the modal
        $("#deleteConfirmationModal").modal("show");
    });

    // Handle confirm delete button click
    $("#confirmDeleteBtn").on("click", function () {
        const form = $("#deleteForm");
        const action = form.attr("action");

        // Show loading state
        $(this)
            .prop("disabled", true)
            .html('<i class="fa fa-spinner fa-spin"></i> Deleting...');

        // Submit the form via AJAX
        // Submit the form via AJAX
        $.ajax({
            url: action,
            type: "POST",
            data: form.serialize(),
            success: function (response) {
                $("#deleteConfirmationModal").modal("hide");

                // If backend returns success = false → show error and stop
                if (response.success === false) {
                    if (typeof toastr !== "undefined") {
                        toastr.error(response.message);
                    } else {
                        alert(response.message);
                    }

                    // Reset button
                    $("#confirmDeleteBtn")
                        .prop("disabled", false)
                        .html('<i class="fa fa-trash"></i> Delete');

                    return; // Do NOT reload page
                }

                // Success message
                let message =
                    response.message ?? "Record deleted successfully!";

                if (typeof toastr !== "undefined") {
                    toastr.success(message);
                } else {
                    alert(message);
                }

                // Reload page after short delay
                setTimeout(() => {
                    location.reload();
                }, 800);
            },
            error: function (xhr, status, error) {
                $("#confirmDeleteBtn")
                    .prop("disabled", false)
                    .html('<i class="fa fa-trash"></i> Delete');

                let errorMessage =
                    "An error occurred while deleting the record.";

                if (xhr.responseJSON?.message) {
                    errorMessage = xhr.responseJSON.message;
                }

                if (typeof toastr !== "undefined") {
                    toastr.error(errorMessage);
                } else {
                    alert(errorMessage);
                }
            },
        });
    });

    // Reset modal state when hidden
    $("#deleteConfirmationModal").on("hidden.bs.modal", function () {
        $("#confirmDeleteBtn")
            .prop("disabled", false)
            .html('<i class="fa fa-trash"></i> Delete');
        $("#deleteForm").attr("action", "");
    });
});

/**
 * Helper function to show delete confirmation for specific records
 * @param {string} deleteUrl - The URL to delete the record
 * @param {string} customMessage - Optional custom message to display
 */
function showDeleteConfirmation(deleteUrl, customMessage = null) {
    $("#deleteForm").attr("action", deleteUrl);

    if (customMessage) {
        $("#deleteModalMessage").text(customMessage);
    } else {
        $("#deleteModalMessage").text(
            "This action cannot be undone and will permanently remove the record."
        );
    }

    $("#deleteConfirmationModal").modal("show");
}
