{{-- EXTENDS TEMPLATE --}}
@extends('layouts.app')

{{-- TITLE --}}
@section('title', ($Laporan == TRUE)? __('lang.edit_data', ['data' => __('lang.laporan')]) : __('lang.add_data', ['data' => __('lang.laporan')]))

{{-- ADDITIONAL STYLE --}}
@push('addons-style')
<link rel="stylesheet" href="{{ url('/') }}/assets/vendor/DataTables/datatables.css" />
<link rel="stylesheet" href="{{ url('/') }}/assets/vendor/select2/css/select2.css" />
<link rel="stylesheet" href="{{ url('/') }}/assets/vendor/select2-bootstrap-theme/select2-bootstrap.min.css" />
<link rel="stylesheet" href="{{ url('/') }}/assets/vendor/dropzone/dropzone.css" />
@endpush

{{-- ADDITIONAL SCRIPT --}}
@push('addons-script')
<script src="{{ url('/') }}/assets/vendor/select2/js/select2.js"></script>
<script src="{{ url('/') }}/assets/vendor/DataTables/datatables.js"></script>
<script src="{{ url('/') }}/assets/vendor/parsley/parsley.min.js"></script>
<script src="{{ asset('js/tinymce/js/tinymce.min.js') }}"></script>
<script src="{{ url('/') }}/assets/vendor/dropzone/dropzone.js"></script>
@endpush

{{-- CUSTOM STYLESHEET --}}
@push('custom-style')
<style>
    .dropzone {
        border: 2px dashed #168eea !important;
    }
    .dropzone i {
        font-size: 50px;
        color: #168eea !important;
    }
</style>
@endpush

{{-- CUSTOM SCRIPT --}}
@push('custom-script')
<script>
    Dropzone.autoDiscover = false;
    $(() => {
        var editor_config = {
            path_absolute : "/",
            height: 500,
            selector: 'textarea#content',
            relative_urls: false,
            plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table directionality",
            "emoticons template paste textpattern"
            ],
            toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media",
            file_picker_callback : function(callback, value, meta) {
                var x = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
                var y = window.innerHeight|| document.documentElement.clientHeight|| document.getElementsByTagName('body')[0].clientHeight;

                var cmsURL = editor_config.path_absolute + 'laravel-filemanager?editor=' + meta.fieldname;
                if (meta.filetype == 'image') {
                    cmsURL = cmsURL + "&type=Images";
                } else {
                    cmsURL = cmsURL + "&type=Files";
                }

                tinyMCE.activeEditor.windowManager.openUrl({
                    url : cmsURL,
                    title : 'Filemanager',
                    width : x * 0.8,
                    height : y * 0.8,
                    resizable : "yes",
                    close_previous : "no",
                    onMessage: (api, message) => {
                        callback(message.content);
                    }
                });
            },
            setup: function (editor) {
                editor.on('change', function () {
                    tinymce.triggerSave();
                });
            }
        };

        tinymce.init(editor_config);

        const uploadURL = $("#uploadURL").val();
        let dropzone = new Dropzone(".dropzone", {
            autoProcessQueue: false,
            parallelUploads: 100,
            maxFiles: 100,
            maxFilesize: {{ config('ppid.max_file_upload') }},
            url: uploadURL,
            method: "post",
            acceptedFiles: "image/*,application/pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx",
            paramName: "userfile",
            addRemoveLinks: true,
            processing: function() {
                $(".btn-save")
                    .prop("disabled", true)
                    .html(`<i class='spinner-border spinner-border-sm'></i> ${lang.uploading_state}`);
            },
            init: function() {
                this.on("addedfile", function(file) {
                    let thumbnail = getThumbnailFromExtension(file.name);
                    $('.dz-image img').css({"width":"100%", "height":"120px"});
                    this.emit("thumbnail", file, thumbnail);

                    if (this.files.length) {
                        let i, len;
                        for (i = 0, len = this.files.length; i < len - 1; i++)
                        {
                            if (this.files[i].name === file.name && this.files[i].size === file.size && this.files[i].lastModified.toString() === file.lastModified.toString()) {
                                this.removeFile(file);
                                sweetAlert("error", 'Berkas sudah ada', lang.failed);
                            }
                        }
                    }
                });
                this.on('sending', function(file, xhr, data) {
                    let _token = $('#token').val();

                    data.append("_token", _token);
                });
                this.on('queuecomplete', function(file) {
                    let acceptedFiles = this.getAcceptedFiles().length;
                    let filesInQueue = this.getQueuedFiles().length;

                    if (filesInQueue > 0) {
                        this.processQueue();
                    } else {
                        if(acceptedFiles > 0) {
                            $("#formLaporan").trigger('submit');
                        }
                    }
                });
                this.on('thumbnail', function(file) {
                    //console.log(file);
                });
                this.on('error', function(file,response) {
                    sweetAlert("error", response, lang.failed);
                    this.removeFile(file);
                });
            },

            dictInvalidFileType: lang.file_x_type,
            dictCancelUpload: lang.cancel,
            dictRemoveFile: lang.delete,
            dictFileTooBig: lang.file_too_big,
        });

        $('#category_report').select2();

        $(".btn-save").on('click', function(e) {

            $("#formLaporan").parsley().validate();

            if ($("#formLaporan").parsley().isValid()) {
                if (dropzone.getQueuedFiles().length > 0) {
                    dropzone.processQueue();
                } else {
                    sweetAlert("error", 'Tidak ada berkas yang diunggah', lang.failed);
                }
            }
        });
    });
</script>
@endpush

{{-- CONTENT --}}
@section('content')
<section role="main" class="content-body">
    <x-page-layout :breadcrumbs="$bc"></x-page-layout>
    <div class="row">
        <div class="col-md-12">
            <x-forms.form method="POST" action="{{ $method }}" id="formLaporan" onsubmit="btnLoading('{!! __('messages.saving_state') !!}')" autocomplete="off" enctype="multipart/form-data" data-parsley-validate="">
            <section class="card card-featured card-featured-primary mb-4">
                <header class="card-header">
                    <h4 class="card-title m-0 me-2">
                        @if ($Laporan == TRUE)
                            @lang('lang.edit_data', ['data' => __('lang.laporan')])
                        @else
                            @lang('lang.add_data', ['data' => __('lang.laporan')])
                        @endif
                    </h4>
                </header>
                <div class="card-body">
                    @csrf
                    <x-forms.form-help :mode="$updateMode" />
                    <div class="mb-3">
                        <x-forms.label for="category_report" :value="__('lang.category_data', ['data' => __('lang.laporan')])" /><span class="asterisk">*</span>
                        <x-forms.select class="form-control" name="category_report" id="category_report" required>
                            @if ($LaporanCategory)
                                <option value="" selected>{{ __('messages.select_data', ['data' => __('lang.category_data', ['data' => __('lang.laporan')])]) }}</option>
                                @foreach ($LaporanCategory as $item)
                                    <option value="{{ $item->id }}"
                                        @if ($Laporan == TRUE)
                                            {{ $item->id == $Laporan->reports_categori_id ? 'selected' : '' }}
                                        @endif
                                        >{{ $item->name }}</option>
                                @endforeach
                            @endif
                        </x-forms.select>
                    </div>
                    <div class="mb-3">
                        <x-forms.label for="title" :value="__('lang.title')" /><span class="asterisk">*</span>
                        <input id="title" type="text" class="form-control" name="title" value="{{ ($Laporan == TRUE)? $Laporan->tittle:old('title') }}" placeholder="@lang('lang.place_data', ['data' => __('lang.title')])" required/>
                    </div>
                    <div class="mb-3">
                        <x-forms.label for="content" :value="__('lang.content')" /><span class="asterisk">*</span>
                        <x-forms.tinymce-editor name="content" id="content" required>@if ($Laporan == TRUE) {{$Laporan->content}} @endif</x-forms.tinymce-editor>
                    </div>
                    <div class="mb-3">
                        <x-forms.label for="youtube" :value="__('lang.youtube')" />
                        <input id="youtube" type="text" class="form-control" name="youtube" value="{{ ($Laporan == TRUE)? $Laporan->youtube:old('youtube') }}" placeholder="@lang('lang.place_data', ['data' => __('lang.youtube')])"/>
                    </div>
                    @if ($Laporan == TRUE)
                    <div class="mb-3">
                        <x-forms.label for="slug" :value="__('lang.slug')" />
                        <input id="slug" type="text" class="form-control" name="slug" value="{{ ($Laporan == TRUE)? $Laporan->slug:old('slug') }}" placeholder="@lang('lang.place_data', ['data' => __('lang.slug')])"/>
                    </div>
                    @endif
                    <div class="mb-3">
                        <x-forms.label for="status" :value="__('lang.status')" /><span class="asterisk">*</span>
                        <select class="form-control" name="status" id="status" required>
                            <option value="" selected>{{ __('messages.select_data', ['data' => __('lang.status'),]) }}</option>
                            <option value="publish" @if ($Laporan == TRUE) {{ 'publish' == $Laporan->status ? 'selected' : '' }} @endif>{{ __('lang.publish')}}</option>
                            <option value="draft" @if ($Laporan == TRUE) {{ 'draft' == $Laporan->status ? 'selected' : '' }} @endif>{{ __('lang.draft')}}</option>
                        </select>
                    </div>
                    <x-forms.button-href class="btn btn-info" href="{{ route('laporan.index') }}" icon="bx bx-chevron-left">{{ __('lang.back') }}</x-forms.button-href>
                    <x-forms.button-submit class="btn btn-primary btn-save"><i class="bx bx-save me-1"></i> {{ __('lang.save') }}</x-forms.button-submit>
                </div>
            </section>
            <section class="card">
                <header class="card-header">
                    <div class="card-actions">
                        <a href="#" class="card-action card-action-toggle" data-card-toggle=""></a>
                        <a href="#" class="card-action card-action-dismiss" data-card-dismiss=""></a>
                    </div>

                    <h2 class="card-title">File Upload Drag Drop</h2>
                </header>
                <div class="card-body" style="display: block;">
                    <p class="card-title-desc">@lang('messages.drag_and_drop_file')</p>
                    <input type="hidden" id="uploadURL" value="{{ route('laporan.storeFile') }}">
                    <input type="hidden" id="token" value="{{ csrf_token() }}">
                    <div class="dropzone mb-5">
                        <div class="fallback">
                            <input name="userfile" type="file" multiple="multiple" accept="image/*" required="required">
                        </div>
                        <div class="dz-message needsclick">
                            <div class="mb-3">
                                <i class="fa fa-cloud-upload"></i>
                            </div>
                            <h6>@lang('lang.drag_and_drop_file')</h6>
                        </div>
                    </div>
                </div>
            </section>
            </x-forms.form>
        </div>
    </div>
</section>
@endsection
