@extends('layouts.app')
@section('title', 'Task')
@section('pages')
    <style type="text/css">
        .dataTables_filter {
            margin-bottom: 6px;
        }

        .text-left {
            text-align: left !important;
        }
    </style>
    <link rel="stylesheet/less" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
    <link href="{{ asset('admin/plugins/datepicker/css/datepicker.css') }}" rel="stylesheet" />
    <!--breadcrumb-->
    <div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
        <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> Task | {{ formatedDate($data->date) }}</div>
        <div class="ps-3">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0 p-0">
                    <li class="breadcrumb-item active" aria-current="page"> {{ $data->getProject->title ?? '' }}</li>
                </ol>
            </nav>
        </div>
        <div class="ms-auto">
            {{-- @if (auth()->user()->can('product-edit')) --}}
            {{-- <div class="btn-group">
            <a href="{{route('projects.edit',$data->id)}}" class="btn btn-warning" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Edit">
                <i class="bi bi-pencil-square text-white"></i>
            </a>
        </div> --}}
            {{-- @endif --}}
            <div class="btn-group">
                <a href="javascript:history.back()" class="btn btn-outline-secondary me-1"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
            </div>
        </div>
    </div>
    <!--end breadcrumb-->

    <div class="row auto">
        <div class="col-xl-12 mx-auto">
            <div class="shadow-none radius-5 min-height">
                <div class="row">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">{{ ucfirst($data->title) }} | {{ formatedDate($data->date) }} | Task Points: {{ $data->task_point ?? '' }}</h5>
                                </div>
                                <hr class="mb-2">
                                <div>
                                    <p>{{ $data->details }}</p>
                                </div>
                                <div class="row">
                                    <div class="col-md-2">
                                        <label class="form-label"><b>Work Status</b></label>
                                        <select class="form-control taskStatusDropdown" data-task-id="{{ $data->id }}">
                                            <option value="">-- Select --</option>
                                            @foreach ($taskStatus as $option)
                                                <option value="{{ $option->id }}" {{ $data->task_status_id == $option->id ? 'selected' : '' }}>
                                                    {{ ucfirst($option->name) }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label"><b>Priority</b></label>
                                         <select class="form-control taskPriorityDropdown" data-task-id="{{ $data->id }}">
                                            <option value="">-- Select --</option>
                                            @foreach ($taskPriority as $option)
                                                <option value="{{ $option->id }}" {{ $data->task_priority_id == $option->id ? 'selected' : '' }}>
                                                    {{ ucfirst($option->name) }}
                                                </option>
                                            @endforeach
                                         </select>
                                    </div>
                                    {{-- <div class="col-md-2">
                                        <label class="form-label"><b>Project</b></label>
                                        <select class="projectDropdown form-control" data-task-id="{{ $data->id }}">
                                            <option value="">--Select Project --</option>
                                            @foreach($project as $list)
                                            <option value="{{ $list->id }}" {!! matchSelected($data->project_id, $list->id) !!}>{{ $list->title }}</option>
                                            @endforeach
                                        </select>
                                    </div> --}}
                                    <div class="col-md-2">
                                        <label class="form-label"><b>Group</b></label>
                                        <select class="taskGroupDropdown form-control" data-task-id="{{ $data->id }}">
                                            <option value="">--Select Group --</option>
                                            @foreach($task_groups as $list)
                                            <option value="{{ $list->id }}" {!! matchSelected($data->task_group_id, $list->id) !!}>{{ $list->name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label"><b>Type</b></label>
                                            <select class="taskTypeDropdown form-control" data-task-id="{{ $data->id }}">
                                                <option value="">--Select Type --</option>
                                                @foreach($taskType as $list)
                                                <option value="{{ $list->id }}" {!! matchSelected($data->task_type_id, $list->id) !!}>{{ $list->title }}</option>
                                                @endforeach
                                            </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
        <div class="col-xl-12 mx-auto">
            <div class="shadow-none radius-5 min-height">
                <div class="row">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body g-3">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">Task Comments</h5>
                                </div>
                                <hr class="mb-2">
                                <div class="row mb-4">
                                    <div class="col-md-6">
                                        <label class="form-label">Comment <span class="text-danger"><b>*</b></span></label>
                                        <input class="form-control comment-textbox" placeholder="Comment"/>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Tag User</label>
                                        <input type="text" name="" id="customer_id" class=" customer-select form-control" placeholder="Search User">
                                        <input type="hidden" name="customer_id">
                                    </div>
                                    <div class="col-md-3">
                                        <button class="btn btn-primary store-comment mt-3">Save Comment</button>
                                    </div>
                                </div>
                                <div id="fetch_comments"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @if(auth()->user()->can('task-attachment-list'))
        <div class="col-xl-12 mx-auto">
            <h2 class="accordion-header" id="panelsStayOpen-headingTwo">
              <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-doc" aria-expanded="false" aria-controls="panelsStayOpen-doc">
                Documents and Attachments
              </button>
            </h2>
            <div class="shadow-none radius-5 min-height">
                <div class="card">
                    <div style="" id="panelsStayOpen-doc" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingTwo">
                      <div class="accordion-body">
                        <div id="fetch_taskAttachments">
                        </div>
                      </div>
                    </div>
                </div>
            </div>
        </div>
        @endif

        @if (auth()->user()->can('responsible-team-list'))
        <div class="col-xl-12 mx-auto">
            <h2 class="accordion-header" id="panelsStayOpen-headingTwo">
              <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-team" aria-expanded="false" aria-controls="panelsStayOpen-team">
                Responsible Team
              </button>
            </h2>
            <div class="shadow-none radius-5 min-height">
                <div class="card">
                    <div style="" id="panelsStayOpen-team" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingTwo">
                      <div class="accordion-body">
                        <div id="fetch_task_entry">
                        </div>
                      </div>
                    </div>
                </div>
            </div>
        </div>
        @endif
        {{-- @if (auth()->user()->can('product-prices-list')) --}}
        <div class="col-xl-12 mx-auto">
            <h2 class="accordion-header" id="panelsStayOpen-headingTwo">
              <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-track" aria-expanded="false" aria-controls="panelsStayOpen-track">
                Task Tracking
              </button>
            </h2>
            <div class="shadow-none radius-5 min-height">
                <div class="card">
                    <div style="" id="panelsStayOpen-track" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingTwo">
                      <div class="accordion-body">
                        <div id="fetch_task_tracking">
                        </div>
                      </div>
                    </div>
                </div>
            </div>
        </div>
        {{-- @endif --}}
    </div>

    <!--end row-->
@endsection
@section('js')
    <script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js') }}"></script>
 <script>
    $(document).ready(function() {
        $('.customer-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="customer_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('task-search-users') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="customer_id"]').val('');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();

                $(this).val(ui.item.name);
                $('[name="customer_id"]').val(ui.item.id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            return $("<li>")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };

        $('.taskStatusDropdown').on('change', function () {
            var selectedStatusId = $(this).val();
            var taskId = $(this).data('task-id');

            // Check if the selected value is empty
            if (selectedStatusId === "") {
                toastr.warning('Please select a status.', 'Warning!');
                return;
            }

            $.ajax({
                url: "{{ url('store-task-status') }}/" + taskId,
                method: 'POST',
                data: {
                    task_status_id: selectedStatusId,
                    _token: '{{ csrf_token() }}',
                },
                success: function(response) {
                    if (response.success === true) {
                        toastr.success(response.message, 'Success.');

                        // hide modal
                        $('#commonModal').modal('hide');
                        fetch_project_attachments();
                    } else {
                        toastr.error(response.message, 'Error!');
                    }
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                console.log('AJAX request failed:', textStatus, errorThrown);
                toastr.error('An error occurred during the request.', 'Error!');

                // hide modal
                $('#commonModal').modal('hide');
                $('#commonModal').find('.modal-body').html('');
            });
        });


        $('.taskPriorityDropdown').on('change', function () {
            var selectedPriorityId = $(this).val();
            var taskId = $(this).data('task-id');

            $.ajax({
                url: "{{ url('store-task-priority') }}/" + taskId, // Fix this line
                method: 'POST',
                data: {
                    status_id: selectedPriorityId,
                    _token: '{{ csrf_token() }}',
                },
                success: function(response) {
                         if (response.success === true) {
                             toastr.success(response.message, 'Success.');

                             // hide modal
                             $('#commonModal').modal('hide');
                             fetch_project_attachments();
                         } else {
                             toastr.error(response.message, 'Error!');
                         }
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                 console.log('AJAX request failed:', textStatus, errorThrown);
                 toastr.error('An error occurred during the request.', 'Error!');

                 // hide modal
                 $('#commonModal').modal('hide');
                 $('#commonModal').find('.modal-body').html('');
            });
        });
        $('.projectDropdown').on('change', function () {
            var selectedPriorityId = $(this).val();
            var taskId = $(this).data('task-id');

            $.ajax({
                url: "{{ url('store-task-project') }}/" + taskId, // Fix this line
                method: 'POST',
                data: {
                    status_id: selectedPriorityId,
                    _token: '{{ csrf_token() }}',
                },
                success: function(response) {
                         if (response.success === true) {
                             toastr.success(response.message, 'Success.');

                             // hide modal
                             $('#commonModal').modal('hide');
                             fetch_project_attachments();
                         } else {
                             toastr.error(response.message, 'Error!');
                         }
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                 console.log('AJAX request failed:', textStatus, errorThrown);
                 toastr.error('An error occurred during the request.', 'Error!');

                 // hide modal
                 $('#commonModal').modal('hide');
                 $('#commonModal').find('.modal-body').html('');
            });
        });

        $('.taskGroupDropdown').on('change', function () {
            var selectedPriorityId = $(this).val();
            var taskId = $(this).data('task-id');

            $.ajax({
                url: "{{ url('store-task-group') }}/" + taskId, // Fix this line
                method: 'POST',
                data: {
                    status_id: selectedPriorityId,
                    _token: '{{ csrf_token() }}',
                },
                success: function(response) {
                         if (response.success === true) {
                             toastr.success(response.message, 'Success.');

                             // hide modal
                             $('#commonModal').modal('hide');
                             fetch_project_attachments();
                         } else {
                             toastr.error(response.message, 'Error!');
                         }
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                 console.log('AJAX request failed:', textStatus, errorThrown);
                 toastr.error('An error occurred during the request.', 'Error!');

                 // hide modal
                 $('#commonModal').modal('hide');
                 $('#commonModal').find('.modal-body').html('');
            });
        });

        $('.taskTypeDropdown').on('change', function () {
            var selectedPriorityId = $(this).val();
            var taskId = $(this).data('task-id');

            $.ajax({
                url: "{{ url('store-task-type') }}/" + taskId, // Fix this line
                method: 'POST',
                data: {
                    status_id: selectedPriorityId,
                    _token: '{{ csrf_token() }}',
                },
                success: function(response) {
                         if (response.success === true) {
                             toastr.success(response.message, 'Success.');

                             // hide modal
                             $('#commonModal').modal('hide');
                             fetch_project_attachments();
                         } else {
                             toastr.error(response.message, 'Error!');
                         }
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                 console.log('AJAX request failed:', textStatus, errorThrown);
                 toastr.error('An error occurred during the request.', 'Error!');

                 // hide modal
                 $('#commonModal').modal('hide');
                 $('#commonModal').find('.modal-body').html('');
            });
        });

     });

        $(document).on('change','.team-approval', function () {
            var selectedStatusId = $(this).val();
            var teamId = $(this).data('id');

            // Check if the selected value is empty
            if (selectedStatusId === "") {
                toastr.warning('Please select a status.', 'Warning!');
                return;
            }

            if (selectedStatusId == 1) {
                $.ajax({
                    url: "{{ route('task-entry.team-approval') }}",
                    method: 'POST',
                    data: {
                        task_status_id: selectedStatusId,
                        team_id: teamId,
                        _token: '{{ csrf_token() }}',
                    },
                    success: function(response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            fetch_task_entry();
                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');

                });
            } else {
                Swal.fire({
                    title: "Reject Reason",
                    text: "Write reason of rejecting:",
                    input: 'text',
                    showCancelButton: true        
                }).then((result) => {
                    if (result.value) {
                        $.ajax({
                            url: "{{ route('task-entry.team-approval') }}",
                            method: 'POST',
                            data: {
                                task_status_id: selectedStatusId,
                                team_id: teamId,
                                reason: result.value,
                                _token: '{{ csrf_token() }}',
                            },
                            success: function(response) {
                                if (response.success === true) {
                                    toastr.success(response.message, 'Success.');
                                    fetch_task_entry();
                                } else {
                                    toastr.error(response.message, 'Error!');
                                }
                            }
                        })
                        .fail(function(jqXHR, textStatus, errorThrown) {
                            console.log('AJAX request failed:', textStatus, errorThrown);
                            toastr.error('An error occurred during the request.', 'Error!');

                        });
                    }
                });
            }
        });
 </script>

    <script type="text/javascript">
        $(document).on('click', '.store-comment', function(event) {
            var comment     = $('.comment-textbox').val();
            var tagged_user = $('[name="customer_id"]').val();

            if (comment.trim() != '') {
                $.ajax({
                    url: "{!! route('task-comments.store') !!}",
                    data: {
                        id : '{!! $id !!}',
                        comment : comment,
                        tagged_user : tagged_user
                    },
                    // processData: false,
                    // contentType: false,
                    type: 'POST',
                    success: function(response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            $('.comment-textbox').val('');
                            $('[name="customer_id"]').val('');
                            $('#customer_id').val('');
                            fetch_comments();
                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');

                    // hide modal
                    $('#commonModal').modal('hide');
                    $('#commonModal').find('.modal-body').html('');
                });
            } else {
                toastr.error("Comment Field is required!", 'Warning!');
            }
        });
        $(document).on('click', '.update-comment', function(event) {
            var comment     = $('.comment-textbox').val();
            var tagged_user = $('[name="customer_id"]').val();

            if (comment.trim() != '') {
                var id = $(this).data('id');
                var url = `{!! route('task-comments.update', ':id') !!}`.replace(':id', id);

                $.ajax({
                    url: url,
                    data: {
                        comment     : comment,
                        tagged_user : tagged_user
                    },
                    // processData: false,
                    // contentType: false,
                    type: 'PUT',
                    success: function(response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            $('.comment-textbox').val('');
                            $('[name="customer_id"]').val('');
                            $('#customer_id').val('');
                            $('.update-comment').remove();
                            $('.store-comment').show();
                            $('.cancel-comment').remove();
                            fetch_comments();
                        } else {
                            toastr.error(response.message, 'Error!');
                        }
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');

                    // hide modal
                    $('#commonModal').modal('hide');
                    $('#commonModal').find('.modal-body').html('');
                });
            } else {
                toastr.error("Comment Field is required!", 'Warning!');
            }
        });

        $(document).on('click', '.edit_comments', function(){
            $('#commonModalLabel').text('Edit Comment');
            $('.save_button_span').text('Update Comment');
            var id = $(this).data('id');
            var url = `{!! route('task-comments.edit', ':id') !!}`.replace(':id', id);

            $.ajax({
              url:url,
              success:function(data){
                if (data.status == 'success') {
                    $('.comment-textbox').val(data.data.comment);
                    $('[name="customer_id"]').val(data.data.user_id);
                    $('#customer_id').val(data.data.tagged_user);
                    $('.store-comment').parent().append('<button class="btn btn-primary update-comment mt-3" data-id=" ' + data.data.id + '">Update Comment</button><button class="btn btn-danger cancel-comment mt-3">Cancel</button>');
                    $('.store-comment').hide();
                } else {
                toastr.error(data.message, 'Error!');
                }
              }
            })
        });

        $(document).on('click', '.cancel-comment', function(){
            $('.comment-textbox').val('');
            $('[name="customer_id"]').val('');
            $('#customer_id').val('');
            $('.update-comment').remove();
            $('.cancel-comment').remove();
            $('.store-comment').show();
        });

        /*********delete data**********/
        $("body").on("click", '.deleteCommentData', function(event) {
            var dataString = {
                "_token": $('meta[name="csrf-token"]').attr('content'),
                "id": $(this).data('id')
            };
            var UrlValue = $(this).data('url');
            var btn = $(this);

            Swal.fire({
                title: 'Are you sure you want to delete this?',
                icon: 'warning',
                showDenyButton: true,
                showCancelButton: false,
                confirmButtonText: 'Yes',
                denyButtonText: 'No',
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.isConfirmed) {
                    $.ajax({
                        url: UrlValue,
                        method: 'post',
                        data: dataString,
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(response) {
                            if (response.success) {
                                $(this).Toastshow('success', response.message);

                                fetch_comments();
                            } else {
                                var ErroMsg = $(this).printErrorMsg(response.message);
                                $(this).Toastshow('error', ErroMsg);
                            }
                        },
                        error: function(data) {
                            console.log("error ", data);
                        }
                    });
                }
            });
        });

        $(document).on('click', '.save_button', function(event) {
            event.preventDefault();
            if ($('#commonModal').find('form').hasClass('task_attachments')) {
                $('.error_error_upload').hide();
                var error = 0;

                if ($("#uploaded_file").get(0).files.length === 0) {
                    $(".error_uploaded_file").css("display", "block");
                    setTimeout(function () {
                        $('.error_uploaded_file').hide();
                        }, 3000);
                    e.preventDefault(); // Prevent form submission
                } else {
                    $(".error_uploaded_file").css("display", "none");
                }

                if (error == 0) {
                    $('[name="task_id"]').val('{{$data->id}}');
                    let formdata = new FormData($('#commonModal').find('form')[0]);

                    $.ajax({
                            url: $('#commonModal').find('form').attr('action'),
                            data: formdata,
                            processData: false,
                            contentType: false,
                            type: 'POST',
                            success: function(response) {
                                if (response.success === true) {
                                    toastr.success(response.message, 'Success.');

                                    // hide modal
                                    $('#commonModal').modal('hide');
                                    fetch_taskAttachments();
                                } else {
                                    toastr.error(response.message, 'Error!');
                                }
                            }
                        })
                        .fail(function(jqXHR, textStatus, errorThrown) {
                            console.log('AJAX request failed:', textStatus, errorThrown);
                            toastr.error('An error occurred during the request.', 'Error!');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        });
                }
            }
            event.preventDefault();

            if ($('#commonModal').find('form').hasClass('task_entry')) {
                $('.error_assigned_to_id').hide();
                var error = 0;

                if ($('select[name="assigned_to_id"]').val() == null || $('select[name="assigned_to_id"]').val() ==
                    '') {
                    $('.error_assigned_to_id').show();
                    error = 1;
                    setTimeout(function () {
                        $('.error_assigned_to_id').hide();
                        }, 3000);
                }

                if (error == 0) {
                    $('[name="task_id"]').val('{{$data->id}}');
                    let formdata = new FormData($('#commonModal').find('form')[0]);

                    $.ajax({
                            url: $('#commonModal').find('form').attr('action'),
                            data: formdata,
                            processData: false,
                            contentType: false,
                            type: 'POST',
                            success: function(response) {
                                if (response.success === true) {
                                    toastr.success(response.message, 'Success.');

                                    // hide modal
                                    $('#commonModal').modal('hide');
                                    fetch_task_entry();
                                } else {
                                    toastr.error(response.message, 'Error!');
                                }
                            }
                        })
                        .fail(function(jqXHR, textStatus, errorThrown) {
                            console.log('AJAX request failed:', textStatus, errorThrown);
                            toastr.error('An error occurred during the request.', 'Error!');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        });
                }
            }
            event.preventDefault();

            if ($('#commonModal').find('form').hasClass('task_tracking')) {
                $('.error_responsible_teams_id').hide();
                var error = 0;

                if ($('select[name="responsible_teams_id"]').val() == null || $('select[name="responsible_teams_id"]').val() ==
                    '') {
                    $('.error_responsible_teams_id').show();
                    error = 1;
                }

                if (error == 0) {
                    $('[name="task_id"]').val('{{$data->id}}');
                    let formdata = new FormData($('#commonModal').find('form')[0]);

                    $.ajax({
                            url: $('#commonModal').find('form').attr('action'),
                            data: formdata,
                            processData: false,
                            contentType: false,
                            type: 'POST',
                            success: function(response) {
                                if (response.success === true) {
                                    toastr.success(response.message, 'Success.');

                                    // hide modal
                                    $('#commonModal').modal('hide');
                                    fetch_task_tracking();
                                } else {
                                    toastr.error(response.message, 'Error!');
                                }
                            }
                        })
                        .fail(function(jqXHR, textStatus, errorThrown) {
                            console.log('AJAX request failed:', textStatus, errorThrown);
                            toastr.error('An error occurred during the request.', 'Error!');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        });
                }
            }
            if ($('#commonModal').find('form').hasClass('update-comment')) {
                var error = 0;

                if ($('#edit_comment').val() == null || $('#edit_comment').val() == '') {
                    toastr.error("Comment Field is required!", 'Warning!');
                    error = 1;
                }

                if (error == 0) {
                    let formdata = new FormData($('#commonModal').find('form')[0]);

                    $.ajax({
                            url: $('#commonModal').find('form').attr('action'),
                            data: formdata,
                            processData: false,
                            contentType: false,
                            type: 'POST',
                            success: function(response) {
                                if (response.success === true) {
                                    toastr.success(response.message, 'Success.');

                                    $('#edit_comment').val('');
                                    $('[name="customer_id"]').val('');
                                    fetch_comments();
                                } else {
                                    toastr.error(response.message, 'Error!');
                                }
                            }
                        })
                        .fail(function(jqXHR, textStatus, errorThrown) {
                            console.log('AJAX request failed:', textStatus, errorThrown);
                            toastr.error('An error occurred during the request.', 'Error!');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        });
                }
            }

            error = 1;
        })

        function clickBTN() {
            $('#createLicenses').trigger('click');
        }
        $(document).ready(function() {
            fetch_taskAttachments();
            fetch_task_entry();
            fetch_comments();
            fetch_task_tracking();
        });
        /*** Fetching task Tracking ***/
        function fetch_task_tracking() {
            $.ajax({
                url: "{!! route('task.tracking', $data->id) !!}",
                success: function(data) {
                    $('#fetch_task_tracking').html('');
                    $('#fetch_task_tracking').html(data);
                    $.switcher('#fetch_task_tracking .changeStatusCustom');
                }
            })
        }
        /*** Fetching task attachments ***/
        function fetch_taskAttachments() {
            $.ajax({
                url: "{!! route('task.attachments', $data->id) !!}",
                success: function(data) {
                    $('#fetch_taskAttachments').html('');
                    $('#fetch_taskAttachments').html(data);
                    $.switcher('#fetch_taskAttachments .changeStatusCustom');
                }
            })
        }

        /*** Fetching task entry ***/
        function fetch_task_entry() {
            $.ajax({
                url: "{!! route('task.entry', $data->id) !!}",
                success: function(data) {
                    $('#fetch_task_entry').html('');
                    $('#fetch_task_entry').html(data);
                    $.switcher('#fetch_task_entry .changeStatusCustom');
                }
            })
        }

        /*** Fetching task entry ***/
        function fetch_comments() {
            $.ajax({
                url: "{!! route('task.comments', $data->id) !!}",
                success: function(data) {
                    $('#fetch_comments').html('');
                    $('#fetch_comments').html(data);
                }
            })
        }


         /*********create Documents and Attachments**********/
         $(document).on('click', '#createtaskAttachment', function() {
            $('#commonModalLabel').text('Add New Documents and Attachments');
            $('.save_button_span').text('Store Documents and Attachments');

            $.ajax({
                url: "{!! route('task-attachments.create') !!}",
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);

                }
            })
        })

         /*********create Comment**********/
         $(document).on('click', '#createTaskComment', function() {
            $('#commonModalLabel').text('Add New Comment');
            $('.save_button_span').text('Store Comment');

            $.ajax({
                url: "{!! route('task-comments.create') !!}",
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);

                }
            })
        })
        /*********Update Documents and Attachments**********/
        $(document).on('click', '#taskAttachmentsEdit', function() {
            var id = $(this).data('id');
            var url = `{!! route('task-attachments.edit', ':id') !!}`.replace(':id', id);
            $('#commonModalLabel').text('Edit Documents and Attachments');
            $('.save_button_span').text('Update Documents and Attachments');

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            })
        })

         /*********create Task Entry**********/
        $(document).on('click', '#createtaskEntry', function() {
            $('#commonModalLabel').text('Add New Responsible Team');
            $('.save_button_span').text('Store Responsible Team');

            $.ajax({
                url: "{!! route('task-entry.create') !!}",
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);

                    var currentDate = new Date();
                    var formattedDate = currentDate.getDate() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getFullYear();
                    $('#assigned_date').val(formattedDate);

                    // Initialize datepickers
                    $('#assigned_date').datepicker();

                    $( function() {
                        $('#expected_completion_date').datepicker();
                    });

                    $( function() {
                        $('#actual_completion_date').datepicker();
                    });

                }
            })
        })

        /*********Update Task entry**********/
        $(document).on('click', '#taskEntryEdit', function() {
            var id = $(this).data('id');
            var url = `{!! route('task-entry.edit', ':id') !!}`.replace(':id', id);
            $('#commonModalLabel').text('Edit Responsible Team');
            $('.save_button_span').text('Update Responsible Team');

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);

                    $( function() {
                        $('#assigned_date').datepicker();
                    });
                    $( function() {
                        $('#expected_completion_date').datepicker();
                    });
                    $( function() {
                        $('#actual_completion_date').datepicker();
                    });

                }
            })
        })

         /*********create Task tracking**********/
         $(document).on('click', '#createTaskTracking', function() {
            $('#commonModalLabel').text('Add New Task Tracking');
            $('.save_button_span').text('Store Task Tracking');

            $.ajax({
                url: "{!! route('task-tracking.create') !!}",
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);

                }
            })
        })
        /*********Update Task Tracking**********/
        $(document).on('click', '#editTaskTracking', function() {
            var id = $(this).data('id');
            var url = `{!! route('task-tracking.edit', ':id') !!}`.replace(':id', id);
            $('#commonModalLabel').text('Edit Task Tracking');
            $('.save_button_span').text('Update Task Tracking');

            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);

                }
            })
        })



        /*********change status**********/
        $("body").on("click", '.changeStatusCustom', function(event) {
            dataString = {
                "id": $(this).data('id'),
                "status": $(this).data('status')
            };
            var UrlValue = $(this).data('url');
            var status = $(this).data('status');
            var changeStatus = $(this);
            var btn = $(this);

            Swal.fire({
                title: 'Are you sure you want to change status?',
                icon: 'warning',
                showDenyButton: true,
                showCancelButton: false,
                confirmButtonText: 'Yes',
                denyButtonText: 'No',
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: UrlValue,
                        method: 'post',
                        data: dataString,
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(response) {
                            if (response.success) {
                                var ErroMsg = $(this).printErrorMsg(response.message);
                                $(this).Toastshow('success', ErroMsg);
                            } else {
                                var ErroMsg = $(this).printErrorMsg(response.message);
                                if (ErroMsg === '') {
                                    ErroMsg = "Something went wrong!";
                                }
                                $(this).Toastshow('error', ErroMsg);
                            }
                            fetch_status();
                            fetch_prices();
                        },
                        error: function(data) {
                            console.log("error ", data);
                            fetch_status();
                            fetch_prices();
                        }
                    });
                } else if (result.isDenied) {
                    fetch_status();
                    fetch_prices();
                }
                //return false;
            });
            //return false;
        });

        /*********delete data**********/
        $("body").on("click", '.deleteAccountData', function(event) {
            dataString = {
                "id": $(this).data('id')
            };
            var UrlValue = $(this).data('url');
            var btn = $(this);
            //alert(dataValue);
            console.log($('meta[name="csrf-token"]').attr('content'));
            console.log(dataString);

            Swal.fire({
                title: 'Are you sure you want to delete this?',
                icon: 'warning',
                showDenyButton: true,
                showCancelButton: false,
                confirmButtonText: 'Yes',
                denyButtonText: 'No',
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.isConfirmed) {
                    $.ajax({
                        url: UrlValue,
                        method: 'post',
                        data: {
                            "_token": $('meta[name="csrf-token"]').attr('content'),
                            "id": $(this).data('id'),
                            "account": "{!! $data->id !!}"
                        },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        beforeSend: function(xhr) {
                            // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                        },
                        success: function(response) {
                            console.log(response.data);
                            if (response.success) {
                                var ErroMsg = $(this).printErrorMsg(response.message);

                                $(this).Toastshow('success', ErroMsg);

                                if (btn.hasClass('attachments')) {
                                    fetch_taskAttachments();
                                } else if (btn.hasClass('task_entry')) {
                                    fetch_task_entry();
                                } else if (btn.hasClass('task_tracking')) {
                                    fetch_task_tracking();
                                }
                                console.log('s');
                            } else {
                                var ErroMsg = $(this).printErrorMsg(response.message);
                                $(this).Toastshow('error', ErroMsg);
                            }
                        },
                        error: function(data) {
                            console.log("error ", data);
                        }
                    });
                }
            });
        });
    </script>
@endsection

