@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</div>
        <div class="ps-3">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0 p-0">
                    <li class="breadcrumb-item active" aria-current="page"> Task Details</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">
                    @if (isset($product->description) && $product->description != '')
                        <div class="col-md-12">
                            <div class="card">
                                <div class="card-body g-3 row">
                                    <div class="table-responsive">
                                        <h5 class="mb-0">Item Name: <b>{{ $product->name }}</b></h5>
                                        <hr class="mb-2">
                                        <p>{{ $product->description }}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endif
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body g-3">
                                <div class="table-responsive">
                                    <div class="d-flex justify-content-between">
                                        <h5 class="mb-0">Task Details of  {{ $data->getProject->title ?? 'Null' }}</h5>
                                    </div>
                                    <hr class="mb-2">
                                    <table class="table table-bordered align-middle">
                                        <tr>
                                            <td class="text-left">Title </td>
                                            <td>{{ ucfirst($data->title) }} {{ formatedDate($data->date) }}</td>
                                        </tr>
                                        <tr>
                                            <td class="text-left">Details</td>
                                            <td>{{ $data->details }}</td>
                                        </tr>


                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
        @if(auth()->user()->can('task-attachment-list'))
        <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" id="fetch_taskAttachments">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @endif
        @if (auth()->user()->can('responsible-team-list'))
        <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" 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">
            <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" 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 type="text/javascript">
        $(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('');
                        });
                }
            }

            error = 1;
        })

        function clickBTN() {
            $('#createLicenses').trigger('click');
        }
        $(document).ready(function() {
            fetch_taskAttachments();
            fetch_task_entry();
            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');
                }
            })
        }


         /*********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);

                }
            })
        })
        /*********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

