@extends('layouts.admin')

@section('title')
    @if ($article->exists)
        Editare
    @else
        Creare
    @endif
    @if ($article->isRecipe())
        reteta
    @endif
@endsection

@section('content')
    <script src="{{asset('assets/admin/plugins/timepicker/jquery-ui-timepicker-addon.js')}}"></script>
    <link href="{{ asset('assets/admin/plugins/timepicker/jquery-ui-timepicker-addon.css') }}" rel="stylesheet">
    <div class="tabs-container">
        <ul class="nav nav-tabs">
            <li class="active"><a data-toggle="tab" href="#tab-1" aria-expanded="true">De bază</a></li>
            @if ($article->exists)
                <li class=""><a data-toggle="tab" href="#tab-5" aria-expanded="false">Poze</a></li>

                {{--                <li class="">--}}
                {{--                    <a data-toggle="tab" href="#files" aria-expanded="false">--}}
                {{--                        Documente--}}
                {{--                        @if ($article->documents->count())--}}
                {{--                            <span class="text-primary h5">{{$article->documents->count()}}</span>--}}
                {{--                        @endif--}}
                {{--                    </a>--}}
                {{--                </li>--}}
                <li class=""><a
                            href="{{route('site.articles.showById', $article)}}"
                            target="_blank">Preview articol</a></li>
            @endif
        </ul>
        <div class="tab-content">
            <div id="tab-1" class="tab-pane active">
                <div class="panel-body">
                    <form
                            id="form-article"
                            action="{{route($article->exists ? 'admin.articles.update' : 'admin.articles.store', $article)}}"
                            method="POST" class="form-horizontal">
                        <input type="hidden" name="_redirect" value="{{url()->previous()}}" class="form-control">
                        {{ method_field($article->exists ? 'PUT' : 'POST' ) }}
                        {{ csrf_field() }}
                        @if (!$article->exists)
                            <p class="text-center h3 text-primary" style="padding-bottom: 24px">
                                Alegeti un titlu pentru {{$article->isRecipe() ? 'reteta' : 'articol'}} si continuati.
                            </p>
                        @endif

                        <div class="row">
                            <div
                                    class="{{!$article->exists || ($article->category->can_create_articles) ? 'col-md-8 col-lg-8' : 'col-12'}}">


                                <div class="form-group row">
                                    <label class="col-sm-2 control-label">Titlu
                                    </label>
                                    <div class="col-sm-10">
                                        <input type="text" name="title"
                                               value="{{ ((old('title')) ?: $article->title) }}"
                                               class="form-control" autofocus="autofocus" required>
                                    </div>
                                </div>


                                @if ((!$article->exists || $article->category->can_create_articles))
                                    <div class="form-group row">
                                        <label class="col-sm-2 control-label">Categorie</label>
                                        <div class="col-sm-10">
                                            <select name="category_id" class="form-control" required>
                                                <option value="">ALEGETI...</option>
                                                @foreach ($categories as $category)
                                                    @if ($category->can_have_children && $category->subcats->count())
                                                        <optgroup label="{{$category->name}}">

                                                            @foreach ($category->subcats as $subcategory)
                                                                <option value="{{$subcategory->id}}"
                                                                        {{ ($subcategory->id == $article->category_id || (!$article->exists && request('category_id') == $subcategory->id)) ? 'selected=selected' : '' }} >
                                                                    {{$subcategory->name}}
                                                                </option>
                                                            @endforeach
                                                        </optgroup>

                                                    @else
                                                        <option value="{{$category->id}}"
                                                                {{ ($category->id == $article->category_id  || (!$article->exists && request('category_id') == $category->id)) ? 'selected=selected' : '' }} >
                                                            {{$category->name}}
                                                        </option>
                                                    @endif

                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                @endif




                                {{--                                @if ($article->exists)--}}
                                {{--                                    <div class="form-group row">--}}
                                {{--                                        <label class="col-sm-2 control-label">Meta description--}}
                                {{--                                        </label>--}}
                                {{--                                        <div class="col-sm-10">--}}
                                {{--                                            <textarea name="meta_description"--}}
                                {{--                                                      class="form-control">{{ ((old('meta_description')) ?: $article->meta_description) }}</textarea>--}}
                                {{--                                        </div>--}}
                                {{--                                    </div>--}}
                                {{--                                @endif--}}
                            </div>


                            @if ($article->exists || ($article->exists && $article->category->can_create_articles))
                                <div class="col-md-4 col-lg-4">
                                    <div class="ibox mb-0">
                                        <div class="ibox-content gray-bg mb-0">
                                            @if ($article->exists)
                                                <div class="form-group">
                                                    <label
                                                            class="col-sm-3 control-label {{$article->status === 'active' ? 'text-primary' : 'text-danger'}}">Status</label>
                                                    <div class="col-sm-9">
                                                        <select name="status" class="form-control">
                                                            @foreach ($article->getPossibleEnumValues('status') as $value)
                                                                <option value="{{$value}}"
                                                                        {{ $article->status == $value ? 'selected=selected' : '' }}>
                                                                    {{$value}}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </div>
                                                </div>
                                            @endif

                                            @if ($article->exists)

                                                @if ($article->isBlog())
                                                    <div class="form-group">
                                                        <label class="col-sm-3 control-label">Data Publicare</label>
                                                        <div class="col-sm-9">
                                                            <input type="text" name="published_at"
                                                                   value="{{ (old('published_at')) ?: $article->published_at}}"
                                                                   class="form-control datetime" autocomplete="off">
                                                            <p class="text-muted">
                                                                Se lasa gol pentru setare automata a datei cand
                                                                articolul se
                                                                trece
                                                                pe
                                                                activ.
                                                            </p>
                                                        </div>
                                                    </div>
                                                @endif

                                                {{--                                                @if (array_search($article->category->parent_id, config('categories_mapping')) === 'articles')--}}
                                                {{--                                                    <div class="form-group mb-0">--}}
                                                {{--                                                        <label class="checkbox-inline col-sm-9 col-sm-offset-3">--}}
                                                {{--                                                            <input type="hidden" name="is_featured" value="0"/>--}}
                                                {{--                                                            <input type="checkbox" name="is_featured" value="1"--}}
                                                {{--                                                                   class="i-checks"--}}
                                                {{--                                                                   @if ($article->is_featured)--}}
                                                {{--                                                                   checked="checked"--}}
                                                {{--                                                                @endif--}}
                                                {{--                                                            /> Recomandate / apare pe home--}}
                                                {{--                                                        </label>--}}
                                                {{--                                                    </div>--}}
                                                {{--                                                @endif--}}
                                            @endif

                                        </div>
                                    </div>
                                </div>
                            @endif
                        </div>


                        @if ($article->exists)

                            @if ($article->isRecipe())
                                <div class="row bg-muted p-h-sm m-t-sm m-b-lg">
                                    <div class="col-xs-offset-2 col-xs-12 ">
                                        <p class="text-uppercase small font-bold text-success">
                                            Info generale
                                        </p>
                                    </div>


                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="col-sm-4 control-label">Porții</label>
                                            <div class="col-sm-6">
                                                <input type="text" name="params[servings]"
                                                       value="{{old('params.servings', $article->params->servings ?? '')}}"
                                                       class="form-control">
                                                <input type="hidden" name="params[yield]"
                                                       value="{{old('params.yield', $article->params->yield ?? '')}}"
                                                       class="form-control">
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label class="col-sm-4 control-label">
                                                Timp preparare (minute)
                                            </label>
                                            <div class="col-sm-6">
                                                <input type="number" name="params[time_preparing]"
                                                       value="{{old('params.time_preparing', $article->params->time_preparing ?? '')}}"
                                                       class="form-control">
                                            </div>
                                        </div>


                                        <div class="form-group">
                                            <label class="col-sm-4 control-label">
                                                Timp gatire (minute)
                                            </label>
                                            <div class="col-sm-6">
                                                <input type="number" name="params[time_cooking]"
                                                       value="{{old('params.time_cooking', $article->params->time_cooking ?? '')}}"
                                                       class="form-control">
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label class="col-sm-4 control-label">
                                                Gata în (minute)
                                            </label>
                                            <div class="col-sm-6">
                                                <input type="number" name="params[time_ready]"
                                                       value="{{old('params.time_ready', $article->params->time_ready ?? '')}}"
                                                       class="form-control">
                                            </div>
                                        </div>

                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label class="col-sm-4 control-label">
                                                Bucătărie
                                            </label>
                                            <div class="col-sm-6">
                                                <select
                                                        name="params[cuisine]"
                                                        class="form-control select2tag-simple">
                                                    @php
                                                        $current_cuisine = Str::slug($article->params->cuisine ?? null);
                                                    @endphp
                                                    @foreach ($cuisines as $cuisine)
                                                        <option value="{{$cuisine->name}}"
                                                                @if($current_cuisine == $cuisine->slug)
                                                                    selected="selected"
                                                                @endif
                                                        >{{$cuisine->name}}</option>
                                                    @endforeach
                                                </select>


                                                {{--                                                <input--}}
                                                {{--                                                        id="cuisine"--}}
                                                {{--                                                        list="cuisines"--}}
                                                {{--                                                        type="text" name="params[cuisine]"--}}
                                                {{--                                                        value="{{old('params.cuisine', $article->params->cuisine ?? '')}}"--}}
                                                {{--                                                        class="form-control">--}}
                                                {{--                                                <datalist id="cuisines">--}}
                                                {{--                                                    <option value="Românească">--}}
                                                {{--                                                    <option value="Franceză">--}}
                                                {{--                                                    <option value="Italiană">--}}
                                                {{--                                                </datalist>--}}
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-sm-4 control-label">
                                                Masă a zilei
                                            </label>
                                            <div class="col-sm-6">
                                                <input type="text" name="params[course]"
                                                       value="{{old('params.course', $article->params->course ?? '')}}"
                                                       class="form-control">
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-sm-4 control-label">
                                                Grad dificultate
                                            </label>
                                            <div class="col-sm-6">
                                                <input
                                                        id="skill"
                                                        list="skills"
                                                        type="text" name="params[skill]"
                                                        value="{{old('params.skill', $article->params->skill ?? '')}}"
                                                        class="form-control">
                                                <datalist id="skills">
                                                    <option value="Ușor">
                                                    <option value="Mediu">
                                                    <option value="Greu">
                                                </datalist>
                                            </div>
                                        </div>


                                    </div>

                                </div>
                            @endif


                            <div class="form-group row">
                                <label class="col-sm-12 text-left mb-2 control-label-or-not">
                                    @if ($article->isRecipe())
                                        Descriere
                                    @else
                                        Text
                                    @endif
                                </label>

                                <div class="col-sm-12">
                                            <textarea name="body" class="form-control rich"
                                                      rows="8">{{ (old('body')) ?: $article->body }}</textarea>
                                </div>
                            </div>

                            @if ($article->isRecipe())
                                <div class=" p-sm m-t-sm m-b-lg mobile-negative-margins"
                                     style="background: #f9f9f9">
                                    <div class="text-center ">
                                        <p class="text-uppercase fa-2x font-bold text-success">
                                            Ingrediente reteta
                                        </p>
                                    </div>

                                    <div class="ingredients-xhr row"
                                         data-url="{{route('admin.articles.ingredients.category', $article)}}"
                                         data-method="post"
                                         data-form="#form-article"
                                         data-callback="setCurrentState"
                                    >
                                        @include('admin.article.recipe.ingredients', ['ingredient_categories' =>  $article->ingredients])
                                    </div>
                                </div>

                                <div class=" p-sm m-t-sm m-b-lg mobile-negative-margins"
                                     style="background: #ecf2f3">
                                    <div class="text-center ">
                                        <p class="text-uppercase fa-2x font-bold text-success">
                                            Pasi reteta
                                        </p>
                                    </div>
                                    <div class="">
                                        <div class="alert alert-warning">
                                            Pentru a putea alege poze la pasi, inainte trebuiesc urcate in
                                            tab-ul Poze.
                                        </div>
                                    </div>


                                    <div class="steps-xhr row"
                                         data-url="{{route('admin.articles.steps.category', $article)}}"
                                         data-method="post"
                                         data-form="#form-article"
                                         data-callback="setCurrentState"
                                    >
                                        @include('admin.article.recipe.steps', ['step_categories' =>  $article->steps])
                                    </div>
                                </div>



                                <div class="bg-muted p-xs  border-top-bottom border-left-right"
                                     style="border-radius: 6px">
                                    <label class="text-left mb-2 control-label-or-not">
                                        Etichete / tags
                                    </label>

                                    <select
                                            name="tags[]"
                                            class="form-control form-control-lg select2tag" multiple="multiple">
                                        @if ($article->tags->count())
                                            @foreach ($article->tags as $tag)
                                                <option selected="selected">{{$tag->name}}</option>
                                            @endforeach
                                        @endif
                                    </select>
                                    <p class="small m-t-xs">
                                        Etichetele ce se introduc prin copy/paste trebuie sa fie separate prin
                                        virgula.
                                    </p>
                                </div>

                            @endif
                        @endif

                        <div class="hr-line-dashed"></div>
                        <div class="form-group">
                            <div class="col-sm-12 col-sm-offset-2-or-not {{!$article->exists ? 'text-center' : '' }}">
                                <p class="text-muted">
                                    Scris de {{$article->user ? $article->user->getName() : $me->getName()}}
                                </p>
                                <button class="btn btn-primary btn-lg" type="submit">
                                    @if ($article->exists)
                                        Salveaza
                                    @else
                                        Salveaza si Continua
                                    @endif
                                </button>
                            </div>
                        </div>
                        @if ($article->exists && !$article->isRecipe() || true)
                            @include('admin.parts.photo.input_info')
                        @endif

                        @if ($article->shouldBeAutosaved())
                            <div class="alert alert-success">
                                <p class="text-uppercase font-bold small">Auto save activ</p>
                                <p>
                                    Acest articol se salveaza automat la fiecare 1 minut (daca s-au realizat
                                    modificari).
                                </p>
                                <p>
                                    Conditiile necesare pentru autosave:
                                </p>
                                <ul class="list-group-item">
                                    <li>
                                        Articolul nu este activ
                                    </li>
                                    <li>
                                        Articolul a fost creat in ultimele 21 de zile
                                    </li>
                                </ul>
                            </div>

                        @endif
                    </form>
                </div>
            </div>
            <div id="tab-5" class="tab-pane">
                <div class="panel-body">
                    @include('admin.parts.photo.index')
                </div>
            </div>

            {{--            @if ($article->exists)--}}
            {{--                <div id="files" class="tab-pane">--}}
            {{--                    <div class="panel-body">--}}
            {{--                        <div class="dynamic-block">--}}
            {{--                            @include('admin.article.document.index')--}}
            {{--                        </div>--}}
            {{--                    </div>--}}
            {{--                </div>--}}
            {{--            @endif--}}
        </div>
    </div>
    @include('admin.parts.rich_editor', ['can_browse_photos' => true])

    <style>
        .select2-search--inline:first-child {
            width: 100%;
        }

        .select2-container li.select2-search--inline input {
            width: 100% !important;
            height: 100%;
            margin-top: 0px;
        }
    </style>
    <script>
        $(document).bind('touchmove', function (e) {
            e.preventDefault();
        }, false);


        $('.datetime').datetimepicker({
            dateFormat: "yy-mm-dd",
            timeFormat: "hh:mm:ss",
        });


        // $('textarea').summernote({
        //     height: 200,
        // });

        @if (request('tab') === 'files')
        $('.nav-tabs a[href="#files"]').tab('show');
        @endif


        $('.select2tag').select2({
            tags: true,
            minimumResultsForSearch: -1,
            tokenSeparators: [',', '.'],
            // tokenizer: function(input, selection, callback) {
            //     if (input.indexOf(',') < 0 && input.indexOf(' ') < 0)
            //         return;
            //
            //     var parts = input.split(/,| /);
            //     for (var i = 0; i < parts.length; i++) {
            //         var part = parts[i];
            //         part = part.trim();
            //
            //         callback({id:part,text:part});
            //     }
            // }
        });

        $('.select2tag-simple').select2({
            tags: true,
        });


        $('body').on('paste', '.select2-search__field', function (event) {
            var delemiter = ',';
            var clipboardData = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData;
            var newTags = clipboardData.getData('text/plain');
            if (!newTags.endsWith(delemiter)) {
                newTags += delemiter;
            }
            event.preventDefault();
            event.target.value = newTags;

            $('.select2tag').data('select2').dataAdapter.$search.val(newTags).trigger("input");
            return false;
        });
    </script>

    @if ($article->shouldBeAutosaved())
        <script>
            var prevState = $('#form-article').serialize();
            var autoSaveInterval;
            var timeout;
            var currentState;

            var setCurrentState = function () {
                console.log('saved state');
                prevState = $('#form-article').serialize();
            }

            var saveData = function () {
                currentState = $('#form-article').serialize();

                // if nothing changed do nothing.
                if (currentState == prevState) {
                    return;
                }

                // if there in active XHR do nothing (we may have inconsistencies)
                if ($.active > 0) {
                    return;
                }

                prevState = currentState;

                $.ajax({
                    url: '{{route('admin.articles.update', $article)}}',
                    method: 'PUT',
                    data: currentState,
                });
            };

            var autoSave = function () {
                timeout && clearTimeout(timeout);

                if (autoSaveInterval) {
                    return;
                }

                // init auto save
                autoSaveInterval = window.setInterval(saveData, 60000); // 60000
            }

            $(window).ready(autoSave);
            $(window).focus(autoSave);
            window.onbeforeunload = function () {
                var currentState = $('#form-article').serialize();

                if (currentState != prevState) {
                    return 'Sigur parasiti pagina? Sunt informatii nesalvate.';
                }

            };

            $(window).blur(function () {
                timeout = window.setTimeout(function () {
                    clearInterval(autoSaveInterval);
                    autoSaveInterval = 0;
                    // we save date only if tab switched, otherwise blur will trigger when onbeforeunload is triggered.
                    if (document.visibilityState !== 'visible') {
                        saveData();
                    }
                }, 2000);
            });

            $('#form-article').submit(function () {
                window.onbeforeunload = null;
            });
        </script>
    @endif

@endsection
