jQuery(document).ready(function ($) {
    jQuery(document).on('click', '.open-edit-modal', function () {
        var taskId = jQuery(this).data('task-id');

        jQuery('#edit_task_message').html('');
        jQuery('#edit_task_form')[0].reset();
        jQuery('#edit_task_id').val(taskId);


        jQuery.ajax({
            url: manager_path.manager_ajaxurl,
            type: 'POST',
            data: {
                action: 'voidempo_get_task_details_callback',
                task_id: taskId,
                security: manager_path.manager_ajax_nonce,


            },
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    var task = response.data;

                    jQuery('#task_title').val(task.title);
                    jQuery('#task_description').val(task.description);
                    jQuery('#task_status').val(task.status);
                    jQuery('#estimated_hours').val(task.estimated_hours);
                    jQuery('#estimated_minutes').val(task.estimated_minutes);

                    jQuery('#voidempo_taskc_assign_mem').empty();

                    jQuery('#task_manager').html(task.managers_dropdown);

                    var $memberSelect = jQuery('#voidempo_taskc_assign_mem');

                    if ($memberSelect.hasClass('select2-hidden-accessible')) {
                        $memberSelect.select2('destroy');
                    }

                    $memberSelect.empty().append(task.members_dropdown);

                    $memberSelect.select2({
                        placeholder: '-- Assign Members --',
                        closeOnSelect: false,
                        width: '100%',
                        dropdownParent: $('#editTaskModal')
                    });

                    $memberSelect.val(task.members).trigger('change');

                    jQuery('#editTaskModal').modal('show');
                }
            },

            error: function () {
                jQuery('#edit_task_message').html('<div class="alert alert-danger">Something went wrong!</div>');
            }
        });
    });


    jQuery(document).on('click', '.voidempo_update_eod_but', function (e) {

        e.preventDefault();

        var eod_id = $(this).data('eod_id');

        jQuery('#updateEODModal').modal('show');

        jQuery.ajax({
            type: 'POST',
            url: manager_path.manager_ajaxurl,
            data: {
                action: 'voidempo_get_eod_data',
                eod_id: eod_id,
                security: manager_path.manager_ajax_nonce,

            },
            success: function (response) {
                if (response.success) {
                    jQuery('#eod_id').val(response.data.id);
                    jQuery('#project').val(response.data.project_title);
                    jQuery('#task').val(response.data.task_title);
                    jQuery('#task_status').val(response.data.task_status);
                    jQuery('#hours').val(response.data.hours);
                } else {
                    alert('Failed to fetch EOD data.');
                }
            }
        });
    });

    jQuery(document).on('click', '#updateEODBtn', function () {
        var eod_id = jQuery('#eod_id').val();
        var task_status = jQuery('#task_status').val();
        var hours = jQuery('#hours').val();

        jQuery.ajax({
            type: 'POST',
            url: manager_path.manager_ajaxurl,
            data: {
                action: 'voidempo_update_eod_data',
                eod_id: eod_id,
                task_status: task_status,
                hours: hours,
                security: manager_path.manager_ajax_nonce,
            },
            success: function (response) {
                if (response.success) {
                    jQuery('#updateEODModal').modal('hide');
                    alert('EOD updated successfully');
                   if ($.fn.DataTable.isDataTable('#voidempo_eod_list_view ')) {
                        jQuery('#voidempo_eod_list_view ').DataTable().ajax.reload(null, false); 
                    }                  
                } else {
                    alert('Error updating EOD');
                }
            }
        });
    });
    jQuery(document).on('click', '#saveTaskChanges', function (e) {
        e.preventDefault();

        const taskId = jQuery('#edit_task_id').val();
        const managerId = jQuery('#task_manager').val();
        const memberIds = jQuery('#voidempo_taskc_assign_mem').val();
        const title = jQuery('#task_title').val();
        const description = jQuery('#task_description').val();
        const status = jQuery('#task_status').val();
        const estimatedHours = jQuery('#estimated_hours').val();
        const estimatedMinutes = jQuery('#estimated_minutes').val();

        jQuery.ajax({
            url: manager_path.manager_ajaxurl,
            type: 'POST',
            data: {
                action: 'voidempo_update_task_details',
                task_id: taskId,
                manager_id: managerId,
                member_ids: memberIds.join(','),
                title: title,
                description: description,
                status: status,
                estimated_time: `${estimatedHours}:${estimatedMinutes}`,
                security: manager_path.manager_ajax_nonce,
            },
            success: function (response) {
                if (response.success) {
                    alert('Task updated successfully!');
                    jQuery('#editTaskModal').modal('hide');
                     if ($.fn.DataTable.isDataTable('#voidempo_task_view_table')) {
                        jQuery('#voidempo_task_view_table').DataTable().ajax.reload(null, false); 
                    }
                 
                } else {
                    alert('Update failed: ' + response.data);
                }
            }
        });
    });


   jQuery(document).on('click', '.voidempo_task_delete', function () {
        var task_id = jQuery(this).data('task_id');
        var task_user_id = jQuery(this).data('task_user_id');

        Swal.fire({
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            icon: 'warning',
            input: 'text', // 👈 input box for delete reason
            inputPlaceholder: 'Enter delete reason',
            inputValidator: (value) => {
                if (!value) {
                    return 'You need to write something!';
                }
            },
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                var delete_reason = result.value;

                var post_data = {
                    'delete_reason': delete_reason,
                    'task_id': task_id,
                    'action': 'voidempo_usertask_delete',
                    'security': manager_path.manager_ajax_nonce,
                };

                jQuery.ajax({
                    url: manager_path.manager_ajaxurl,
                    type: 'POST',
                    data: post_data,
                    dataType: 'html',
                    success: function (response) {
                        var obj = jQuery.parseJSON(response);
                        if (obj.msg === 'deleted') {
                            Swal.fire({
                                icon: 'success',
                                title: 'Done',
                                text: 'Task for the user is deleted'
                            });
                            jQuery('.voidempo_tr_' + obj.task_id).remove();
                                if ($.fn.DataTable.isDataTable('#voidempo_task_view_table')) {
                                    jQuery('#voidempo_task_view_table').DataTable().ajax.reload(null, false); 
                                }
                        }
                    }
                });
            }
        });
    });


});
