@extends('frontend.layouts.app')

@section('title', app_name() . ' | ' . __('navs.frontend.dashboard') )
@push('after-styles')
    <style>
        {{--        Fixing big images--}}
        .contents img {
            max-width: 100% !important;
            height: auto;
        }
    </style>
@endpush
{{--Scripts for this page--}}
@push('after-scripts')
    <script src="{{ asset('js/tinymce/tinymce.min.js') }}"></script>
    <script src="{{ asset('js/tinymce/jquery.tinymce.min.js') }}"></script>
    {{--    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>--}}
{{--    <script src="https://unpkg.com/@popperjs/core@2"></script>--}}
{{--    <script src="https://unpkg.com/tippy.js@6"></script>--}}
    <script type="text/javascript">
        var currenteditingid = -1;
        var currentdeletingid = -1;

        $(document).ready(function () {
//select2
            $('select').select2({
                placeholder: "Select...",
                allowClear: true
            });

            $('div.modal').on('show.bs.modal', function (event) {
                let modal = $(this);
                modal.addClass('d-block'); // Boostrap class for display-block
            });
            $('div.modal').on('hide.bs.modal', function (event) {
                let modal = $(this);
                modal.removeClass('d-block');
            });

            //tinymce
            tinymce.init({
                selector: '.richtext',
                menubar: false,
                relative_urls: false,
                remove_script_host: true,
                document_base_url: "{{url('/')}}",
                valid_elements: 'img[class=myclass|!src|border:0|alt|title|width|height|style],' +
                    'a[href|target=_blank],' +
                    'strong/b,div[align],strong/b,em/i,strike,u,' +
                    'p[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|title],' +
                    'ol[class|compact<compact|dir<ltr?rtl|id|lang|start|style|title|type],' +
                    'ul[class|compact<compact|dir<ltr?rtl|id|lang|start|style|title|type],-li',

                plugins: [
                    "link image emoticons"
                ],
                mobile: {
                    theme: 'mobile',
                    plugins: ["link image emoticons"],
                    toolbar: ['bold', 'italic', 'link', 'image', 'emoticons']
                },
                contextmenu: 'link, image',
                toolbar: 'bold italic | link image emoticons |',
                file_picker_types: 'image',
                paste_data_images: true,
                images_upload_handler: function (blobInfo, success, failure) {
                    let data = new FormData();
                    data.append('uploaded_file', blobInfo.blob(), blobInfo.filename());
                    console.log('Uploading data')
                    axios.post('{{route('frontend.forum.storemedia')}}', data)
                        .then(function (res) {
                            console.log('Uploading success!')
                            //  console.log(res.data)
                            success(res.data.location);
                        })
                        .catch(function (err) {
                            failure('HTTP Error: ' + err.message);
                        });
                },
                // setup: function (editor) {
                //     editor.on('change', function () {
                //         tinymce.triggerSave();
                //
                //     });
                // }
            });


            $('a[data-toggle=modal], button[data-toggle=modal]').click(function () {
                currenteditingid = $(this).data('id');
                switch ($(this).data('target')) {
                    case '#editthreaddialog':
                        break;

                    case '#addreplydialog':
                        break;

                    case '#editreplydialog':
                        if ($(this).data('id') > -1) {
                            getReplyDetails($(this).data('id'));
                        }
                        break;
                    case '#deletereplydialog':
                        currentid = $(this).data('id');
                        break;
                    default:
                        currenteditingid = -1;
                        currentdeletingid = -1;
                        break;
                }
            });

            $('#editthreaddialog').submit(function (event) {
                // cancels the form submission
                console.log('editthreaddialog submitted');
                event.preventDefault();
                //$(this).modal('hide');
                // var form = $(this).find("form");//.serializeArray();

                // Editor contains a value
                var form = $(this).find("form").get()[0];
                // waitingDialog.show();
                submitEditThreadForm(form);


            });


            $('#addreplydialog').submit(function (event) {
                // cancels the form submission
                console.log('addreplydialog submitted');
                event.preventDefault();
                //$(this).modal('hide');
                //var vars = $(this).find("form").serializeArray();
                var form = $(this).find("form").get()[0];
                // waitingDialog.show();
                submitNewReplyForm(form);
            });

            $('#editreplydialog').submit(function (event) {
                // cancels the form submission
                console.log('editreplydialog submitted');
                event.preventDefault();
                //$(this).modal('hide');
                // var vars = $(this).find("form").serializeArray();
                var form = $(this).find("form").get()[0];
                console.log(form);
                // waitingDialog.show();
                submitUpdateReplyForm(currenteditingid, form);
            });

            $("#deletereplydialog").submit(function (event) {
                $(this).modal('hide');
                // cancels the form submission
                event.preventDefault();

                deleteReply(currentid);
            });

            $("#deletethreaddialog").submit(function (event) {
                $(this).modal('hide');
                // cancels the form submission
                event.preventDefault();

                deleteThread();
            });
        });

        function submitEditThreadForm(form) {
            // console.log(form)
            var data = new FormData(form);
            axios.post('{{route('frontend.threads.update', $thread->id)}}',
                data
            ).then(function (response) {
                console.log(response);
                if (response.data.status == 0) {
                    location.reload();
                } else {
                    alert('something went wrong with the update');
                }
            })
                .catch(function (error) {
                    console.log(error);
                    alert('something went wrong with the update');
                })
                .finally(function () {
                    // always executed
                    wait(false)
                });

        }

        function getReplyDetails(id) {
            console.log('getReplyDetails:' + id);


            $.ajax({
                url: '{!! URL::to('forum/forumreply')!!}/' + id,
                type: 'GET',
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function (data) {
                    //  console.log(data);
                    //$("#editcontactdialog").find("form").values(data);
                    populate($("#editreplydialog"), data);
                    // changevalidation('edituserform');
                    //waitingDialog.hide();

                }
            });
        }


        function submitNewReplyForm(form) {
            var data = new FormData(form);

            axios.post('{{route('frontend.forumreply.store')}}',
                data
            ).then(function (response) {
                console.log(response);
                if (response.data.status == 0) {
                    location.reload();
                } else {
                    alert('something went wrong with the update');
                }
            })
                .catch(function (error) {
                    console.log(error);
                    alert('something went wrong with the update');
                })
                .finally(function () {
                    // always executed
                    wait(false)
                });

        }

        function submitUpdateReplyForm(id, form) {
            var data = new FormData(form);
            // data.method =
            axios.post('{!! URL::to('forum/forumreply/')!!}/' + id,
                data
            ).then(function (response) {
                console.log(response);
                if (response.data.status == 0) {
                    location.reload();
                } else {
                    alert('something went wrong with the update');
                }
            })
                .catch(function (error) {
                    console.log(error);
                    alert('something went wrong with the update');
                })
                .finally(function () {
                    // always executed
                    wait(false)
                });

        }

        function deleteReply(id) {
            axios.post('{!! URL::to('forum/forumreply/')!!}/' + id,
                {
                    _method: "DELETE"
                }
            ).then(function (response) {
                console.log(response);
                if (response.data.status == 0) {
                    location.reload();
                } else {
                    alert('something went wrong with the update');
                }
            })
                .catch(function (error) {
                    console.log(error);
                    alert('something went wrong with the update');
                })
                .finally(function () {
                    // always executed
                    wait(false)
                });

        }

        function deleteThread() {
            axios.post('{!! $thread->path()!!}',
                {
                    _method: "DELETE"
                }
            ).then(function (response) {
                console.log(response);
                if (response.data.status == 0) {
                    location.assign('{{route('frontend.channels.index')}}');
                } else {
                    alert('something went wrong with the update');
                }
            })
                .catch(function (error) {
                    console.log(error);
                    alert('something went wrong with the update');
                })
                .finally(function () {
                    // always executed
                    wait(false)
                });

        }

        // populates a form with data returned from Laravel
        function populate(frm, data) {

            $.each(data, function (key, value) {
                var $ctrl = $('[name=' + key + ']', frm);
                if ($ctrl.is("select")) {
                    $ctrl.select2('val', value);
                } else if ($ctrl.is("textarea")) {
                    if ($ctrl.hasClass('richtext')) {
                        tinyMCE.activeEditor.setContent(value);
                    } else {
                        $ctrl.val((value === null) ? '' : value);
                    }
                } else {

                    switch ($ctrl.attr("type")) {
                        case "text" :
                        case "hidden":
                            $ctrl.val(value);
                            $ctrl.trigger('change');
                            break;

                        case "radio" :
                        case "checkbox":
                            $ctrl.each(function () {
                                if ($(this).attr('value') == value) {
                                    $(this).attr("checked", value);
                                }
                            });
                            break;

                        default:
                            $ctrl.val(value);
                    }

                }
            });
        }

        function wait(on) {
            console.log(on)
            if (on) {
                $('.load-spinner').modal('show');
            } else {
                setTimeout(function () {
                    $('.load-spinner').modal('hide');
                }, 500)

            }
        }
    </script>
@endpush

@section('content')


    {{-- Forum threads display--}}
    @if(isset($lab))
        {!! Breadcrumbs::render('frontend.lab.forum.thread', $lab, $thread) !!}
    @else
        {!! Breadcrumbs::render('frontend.threads.show', $thread) !!}
      @endif
    <div class="container">
        <div class="row"
             style="margin-left:20px; background-color: whitesmoke; border: 1px solid #2aa8cc; border-radius: 0px 10px 10px 10px; margin-right: 5px; min-height: 500px">
            <div class="col">
                <div class="d-flex flex-row pb-1" style="border-bottom: 2px solid grey; ">
                    <div class=" p-0 m-0 w-100">
                        <div class="g_et_al_header2" style="overflow-wrap: break-word; overflow-y: hidden">
                            Thread: {{$thread->title}}</div>
                        <div class="g_et_al_paragraph2"
                             style="overflow-wrap: break-word; overflow-y: hidden">{{$thread->user->name}}</div>
                        @foreach($thread->tags as $tag)
                            #{{$tag->text}}
                        @endforeach
                    </div>

                    <div class=" ml-auto pt-1">
                        <div class="btn-group btn-group-sm" role="group" aria-label="Controls">
                            <span data-toggle="modal" data-target="#editthreaddialog"><button type="button"
                                                                                              class="btn btn-sm btn-primary"
                                                                                              data-toggle="tooltip"
                                                                                              title="Edit"
                                ><i
                                        class="fas fa-edit"></i></button>
                            </span>
                            <span data-toggle="modal" data-target="#deletethreaddialog"><button type="button"
                                                                                                class="btn btn-sm btn-danger"
                                                                                                data-toggle="tooltip"
                                                                                                title="Delete"><i
                                        class="fas fa-trash-alt"></i></button>
                            </span>
                        </div>

                    </div>
                </div>
                <div class="row w-100">
                    <div class="col contents" style="overflow-y: hidden">
                        {!! $thread->body!!}
                    </div>

                </div>

                <a name="replies"></a>
                {{--                Replies--}}
                @foreach($thread->replies as $reply)
                    <div class="row w-100" style="border-top: 1px solid grey; ">

                        {{--                        <div class="d-flex flex-row pb-1">--}}
                        {{--                                Name and date--}}
                        <div class="col g_et_al_paragraph2"
                             style="padding-top: 0 !important; overflow-wrap: break-word; overflow-y: hidden">{{$reply->user->name??''}}
                            <div
                                class="g_et_al_timecell">{{$reply->created_at->diffForHumans()}}</div>
                        </div>
                    </div>

                    {{--                        </div>--}}
                    <div class="row">
                        <div class="col contents" style="overflow-y: hidden">
                            {!! $reply->body!!}
                        </div>
                    </div>


                    <div class="d-flex flex-row">
                        <div class="d-flex p-2 g_et_al_listtext" style="padding-top: 0 !important;">
                            <a href="#" data-toggle="modal" data-id="{{$reply->id}}"
                               data-target="#editreplydialog">
                                <i class="far fa-edit"></i>
                            </a>&nbsp;
                            <a href="#" data-toggle="modal" data-id="{{$reply->id}}"
                               data-target="#deletereplydialog">
                                <i class="far fa-trash-alt" style="color: orangered"></i>
                            </a>
                        </div>
                    </div>


                @endforeach

                {{--                <div class="row">--}}
                {{--                    <table class="table table-hover">--}}
                {{--                        @foreach($thread->replies as $reply)--}}
                {{--                            <tr id="reply_{{$reply->id}}">--}}
                {{--                                <td>--}}
                {{--                                    <div class="d-flex">--}}

                {{--                                        <div class="p-2 g_et_al_paragraph2"--}}
                {{--                                             style="padding-top: 0 !important; ; overflow-y: hidden">{{$reply->user->name}} <span--}}
                {{--                                                class="g_et_al_timecell">{{$reply->created_at->diffForHumans()}}</span>--}}
                {{--                                        </div>--}}
                {{--                                    </div>--}}
                {{--                                    <div class="d-flex">--}}
                {{--                                        <div class="p-2 g_et_al_listtitle"--}}
                {{--                                             style="padding-top: 0 !important;">{{$reply->title}}</div>--}}
                {{--                                    </div>--}}
                {{--                                    <div class="d-flex p-2 contents" style="padding-top: 0 !important; overflow-y: hidden"--}}
                {{--                                         id="reply_body_{{$reply->id}}">--}}
                {{--                                        {!! $reply->body !!}--}}
                {{--                                    </div>--}}
                {{--                                    <div class="d-flex p-2 g_et_al_listtext" style="padding-top: 0 !important;">--}}
                {{--                                        <a href="#" data-toggle="modal" data-id="{{$reply->id}}"--}}
                {{--                                           data-target="#editreplydialog">--}}
                {{--                                            <i class="far fa-edit"></i>--}}
                {{--                                        </a>&nbsp;--}}
                {{--                                        <a href="#" data-toggle="modal" data-id="{{$reply->id}}"--}}
                {{--                                           data-target="#deletereplydialog">--}}
                {{--                                            <i class="far fa-trash-alt" style="color: orangered"></i>--}}
                {{--                                        </a>--}}
                {{--                                    </div>--}}
                {{--                                </td>--}}
                {{--                            </tr>--}}
                {{--                        @endforeach--}}
                {{--                    </table>--}}
                {{--                </div>--}}

                <div class="row pt-0">
                    <div class="col-md-8 col-md-offset-2">
                        <button class="btn btn-info" data-toggle="modal"
                                data-target="#addreplydialog">Reply
                        </button>
                    </div>
                </div>
            </div>
        </div>

    </div>


@endsection
@section('dialogs')

    <div id="editthreaddialog" class="modal fade" role="dialog">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Edit thread</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    {{html()->modelForm($thread)->class('form-horizontal')->open()}}

                    @include('frontend.forum.thread.form.edit_thread', ['submitButtonText'=>'Edit thread'])

                    {{ html()->closeModelForm() }}
                </div>
            </div>
        </div>
    </div>

    <div id="addreplydialog" class="modal fade" role="dialog">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="additemtitle">Add reply</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    {!! Form::open( ['class'=>'form-horizontal', 'id'=>'addreplyform'])!!}

                    @include('frontend.forum.thread.form.replyform', ['submitButtonText'=>'Add reply', 'bodyid'=>'add_body'])

                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>

    <div id="editreplydialog" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Edit reply</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    {!! Form::open( ['class'=>'form-horizontal', 'id'=>'editreplyform'])!!}
                    <input type="hidden" name="_method" value="PATCH">
                    @include('frontend.forum.thread.form.replyform', ['submitButtonText'=>'Update reply',  'bodyid'=>'reply_body'])

                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>

    <div id="deletereplydialog" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Really delete?</h4>
                </div>
                <div class="modal-body">
                    {!! Form::open()!!}
                    @include('frontend.form_common.deletedialog')
                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>

    <div id="deletethreaddialog" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Really delete thread and replies?</h4>
                </div>
                <div class="modal-body">
                    {!! Form::open()!!}
                    @include('frontend.form_common.deletedialog')
                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade load-spinner" data-backdrop="static" data-keyboard="false" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <i class="fas fa-circle-notch fa-spin fa-3x mx-auto"></i>
            </div>
        </div>
    </div>
@endsection
