<script>
    $(function() {
        'use strict';

        const csrfToken = $('meta[name="csrf-token"]').attr('content');
        // Caching the route URL to avoid recalculating it
        const updateStatusRoute = `{{ route('admin.order.task.status-update') }}`;

        // Initialize sortable columns for drag-and-drop
        $(".sortable-column").sortable({
            connectWith: ".sortable-column",
            placeholder: "ui-state-highlight",
            start: function(event, ui) {
                ui.placeholder.height(ui.item.height());
            },
            receive: function(event, ui) {
                let taskId = ui.item.find('input[type="hidden"]').attr('name').match(/\d+/)[0]; // Extract task ID
                let newStatus = $(this).attr('id'); // Get the column ID to determine the new status

                // Map column IDs to status (adjust this to your real statuses)
                let statusMap = {
                    'todo-column': 'pending',
                    'in-progress-column': 'in_progress',
                    'done-column': 'completed'
                };

                let updatedStatus = statusMap[newStatus];

                // Send AJAX request to update task's status
                updateTaskStatus(taskId, updatedStatus);
            },
        }).disableSelection();

        // Function to handle the status update via AJAX
        function updateTaskStatus(taskId, newStatus) {
            $.ajax({
                url: updateStatusRoute,
                method: 'POST',
                data: {
                    task_id: taskId,
                    status: newStatus,
                    _token: csrfToken // Use cached CSRF token
                },
                success: function(response) {
                    if (response.success) {
                        notifyEvs('success', response.message);
                    } else {
                        notifyEvs('error', response.message);
                    }
                },
                error: function(xhr) {
                    notifyEvs('error', 'An error occurred while updating task status:', xhr.responseText);
                }
            });
        }

        // Generalized function to show modals and load data via AJAX
        function showModal(modalId, dataContainerId, url) {
            const loadingHtml = `
            <div class="d-flex justify-content-center">
                <div class="spinner-border" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
            </div>
        `;

            $(`#${modalId}`).modal('show');
            $(`#${dataContainerId}`).html(loadingHtml);

            // AJAX request to load the modal content
            $.get(url, function(data) {
                $(`#${dataContainerId}`).html(data);
            });
        }

        // Event listener for showing modals
        $(document).on('click', '.show-modal', function () {
            const url = $(this).data('show-url');
            showModal('show-task-modal', 'show-task-data', url);
        });


        // Initialize the edit form modal
        editFormByModal('edit-task-modal', 'edit-task-data');
    });


</script>
