<div class="modal-content">

    <div class="modal-header">
    <h5 class="modal-title">
        {{ $value->title }}
        @if($value->subtitle)
            <br><small class="text-muted">{{$value->subtitle}}</small>
        @endif

    </h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>
</div>
<div class="modal-body">
    {!! Form::open(['url' => $value->url, 'class' => '', 'id'=>'customer-mail-form']) !!}
    {{ Form::hidden('booking_id', $value->id) }}
    {{ Form::hidden('action', '') }}
    @if(isset($value->save_customer_mail_id))
        {{ Form::hidden('save_customer_mail_id', $value->save_customer_mail_id) }}
    @endif

    @if($value->show === 'single' || $value->show === 'reply')
        <div class="row">
            @if(isset($value->booking))
            <div class="col-sm-4">
                <strong>Buchung: </strong><br>
                @if($value->booking->travel_country_id)
                    {{ " | ".$value->booking->travel_country->name }}
                @endif
                @if($value->booking->travelagenda_id)
                    {{ " | ".$value->booking->travel_agenda->name }}
                @endif
                ({{ $value->booking->id }})
            </div>
            <div class="col-sm-4">
                @if($value->booking->customer)
                    <strong>Kunde: </strong><br>{{ $value->booking->customer->salutation->name }} {{ $value->booking->customer->title }} {{  $value->booking->customer->firstname }}  {{  $value->booking->customer->name }}
                @endif
                @if($value->booking->lead)
                    ({{$value->booking->lead->id}})
                @endif
            </div>
            @endif
            <div class="col-sm-4">
                @if(isset($value->customer_mail))
                    <strong>Antwort auf: </strong><br>{{  $value->customer_mail->id }} || {{ $value->customer_mail->subject }}
                @endif
            </div>
            <div class="col-sm-12">
                <hr>
            </div>
        </div>
    @endif
    @if(isset($value->customers))
        @if($value->show === 'single')
            <div class="form-row">
                <div class="form-group col-sm-12 mb-1">
                    <label for="to" class="form-label">E-Mail senden an:*</label>
                    @foreach($value->customers as $key=>$val)
                        <label class="custom-control custom-checkbox mt-2" style="margin-right: 20px;">
                            {!! Form::checkbox('send_mail_to['.$key.']', 1, $key, ['class'=>'custom-control-input']) !!}
                            <span class="custom-control-label">
                                <div class="row">
                                    <div class="col-sm-6">
                                      {{ Form::text('send_mail_to_mail['.$key.']', $val['email'],  array('placeholder'=>'Erste E-Mail: Pflichtpfeld', 'id'=>'send_mail_to_mail_'.$key, 'class'=>'form-control', 'style'=>'margin-top: -8px;', 'required')) }}
                                    </div>
                                    <div class="col-sm-6">
                                       <button type="button" class="btn btn-sm btn-outline-primary mt-1 mb-2" data-toggle="collapse" data-target="#collapseModalNewMailRe" aria-expanded="false" aria-controls="collapseModalNewMailRe"><i class="fa fa-plus-circle"></i> Weitere Empfänger</button>
                                    </div>
                                </div>
                            </span>
                        </label>
                    @endforeach
                </div>
            </div>
            <div class="collapse form-row" id="collapseModalNewMailRe">
                <div class="form-group col-sm-4">
                    <label class="form-label" for="recipient">TO: (weitere Empfänger)</label>
                    {{ Form::textarea('recipient', $value->recipient, ['class' => 'form-control', 'rows'=>4]) }}
                </div>
                <div class="form-group col-sm-4">
                    <label class="form-label" for="cc">CC: (Kopie Empfänger)</label>
                    {{ Form::textarea('cc', $value->cc, ['class' => 'form-control', 'rows'=>4]) }}
                </div>
                <div class="form-group col-sm-4">
                    <label class="form-label" for="bcc">BCC: (Blindkopie Empfänger)</label>
                    {{ Form::textarea('bcc', $value->bcc, ['class' => 'form-control', 'rows'=>4]) }}
                </div>
            </div>
        @endif

        @if($value->show === 'multi')
            <div class="form-row">
                <div class="form-group col-sm-12 mb-1">
                    <label for="to" class="form-label">E-Mail senden an:</label>
                    @foreach($value->customers as $key=>$val)
                        <label class="custom-control custom-checkbox mt-2" style="margin-right: 20px;">
                            {!! Form::checkbox('send_mail_to['.$key.']', 1, $key, ['class'=>'custom-control-input']) !!}
                            <span class="custom-control-label">{{ $val['email']  }} | {{ $val['name']  }}</span>
                        </label>
                    @endforeach
                </div>
            </div>
        @endif
    @endif

    @if($value->show === 'reply' && isset($value->booking))
        <div class="form-row">
            <div class="form-group col">
                <label for="mail_from" class="form-label">E-Mail von:</label>
                {{ Form::text('mail_from', $value->booking->customer ? $value->booking->customer->email : '',  array('placeholder'=>'E-Mail Adresse von', 'id'=>'mail_from', 'class'=>'form-control', 'required')) }}
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col">
                <label for="sent_at" class="form-label">Gesendet am:</label>
                {{ Form::text('sent_at', \Carbon::now()->format('d.m.Y H:i'),  array('placeholder'=>__(\Carbon::now()->format('d.m.Y - H:i')), 'class'=>'form-control  b-material-datetime-picker', 'id'=>'sent_at')) }}
            </div>
        </div>
    @endif


    <div class="form-row">
        {{ Form::hidden('lead_title_id', $value->lead_title_id, array('id'=>'lead_title_id')) }}
        <div class="form-group col">
            <label for="subject" class="form-label">Betreff</label>
            {{ Form::text('subject', $value->subject,  array('placeholder'=>$value->s_placeholder, 'id'=>'subject', 'class'=>'form-control', 'required')) }}
        </div>
    </div>

    <div class="form-group mb-1">
        <label class="form-label" for="message">Nachricht</label>
        @if($value->show === 'single' || $value->show === 'multi')
            @if(Auth::user()->isPermission('sua-st-em'))
                <div class="float-right small">Vorlage unter: <a href="{{route('admin_settings_emails')}}">Einstellungen -> E-Mails / Vorlagen</a></div>
            @endif
        @endif
        <div id="message-editor-toolbar">
            <span class="ql-formats">
                          <button class="ql-bold"></button>
                          <button class="ql-italic"></button>
                          <button class="ql-underline"></button>
                          <button class="ql-strike"></button>
                        </span>
            <span class="ql-formats">
                          <button class="ql-header" value="1"></button>
                          <button class="ql-header" value="2"></button>
                          <button class="ql-blockquote"></button>
                          <button class="ql-code-block"></button>
                        </span>
            <span class="ql-formats">
                          <button class="ql-list" value="ordered"></button>
                          <button class="ql-list" value="bullet"></button>
                          <button class="ql-indent" value="-1"></button>
                          <button class="ql-indent" value="+1"></button>
                        </span>
            <span class="ql-formats">
                          <select class="ql-align"></select>
                        </span>
            <span class="ql-formats">
                          <button class="ql-clean"></button>
                        </span>
            <span class="ql-formats">
                <select class="ql-placeholder">
                    {!! \App\Services\Placeholder::getBookingOptions() !!}
                </select>
            </span>
        </div>
        <div id="message-editor" style="height: 400px">{!! $value->message !!}</div>
        {{ Form::textarea('message', $value->message,  array('placeholder'=>$value->m_placeholder, 'id'=>'message-editor-fallback', 'class'=>'form-control d-none', 'rows'=>15)) }}
    </div>
    @if($value->show === 'single' || $value->show === 'multi')
    <div class="row">
        <div class="col-12">
            <button type="button" class="btn btn-sm btn-outline-next mt-1 mb-3 float-left" data-toggle="collapse" data-target="#collapseModalEmailTemplate" aria-expanded="false" aria-controls="collapseModalEmailTemplate"><i class="ion ion-ios-mail"></i> E-Mail Vorlage laden</button>
        </div>
        <div class="collapse col-12" id="collapseModalEmailTemplate">
            <hr class="mt-0">

            <select class="custom-select" name="filter_email_templates_directory" id="filter_email_templates_directory" style="">
                <option value="">Alle Verzeichniss</option>
                @foreach($value->filter_email_templates_directories as $id=>$name)
                    <option value="{{$id}}" >{{$name}}</option>
                @endforeach
            </select>

            <div class="table-responsive" id="email_templates_table">
                <table id="datatables-email-templates" class="table table-striped">
                    <thead>
                    <tr>
                        <th>#</th>
                        <th>{{__('Vorlage Bezeichnung')}}</th>
                        <th>{{__('Verzeichniss')}}</th>
                        <th>&nbsp;</th>
                    </tr>
                    </thead>
                    <tbody class="">
                    </tbody>
                </table>
            </div>
            <hr class="mt-1">
        </div>
    </div>
    @endif
    @if($value->show === 'single' || $value->show === 'reply')
        <div class="form-row">
            <div class="col-sm-6">
                <label for="send_mail_dir" class="form-label">Ablegen unter:</label>
                <select class="custom-select" name="dir" id="send_mail_dir">
                    @foreach(\App\Services\Booking::getCustomerMailDirs() as $customer_mail_dir)
                        <option value="{{$customer_mail_dir->pos}}" @if($value->customer_mail_dir == $customer_mail_dir->pos) selected @endif>{{$customer_mail_dir->name}}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-sm-6">
                <label for="subdir" class="form-label">&nbsp;</label>
                {{-- TODO load subdirs by pos id --}}
                @if(isset($value->booking) && $value->booking->travel_country)
                    @foreach(\App\Services\Booking::getCustomerMailDirs() as $customer_mail_dir)
                        @if($customer_mail_dir->pos > 0)
                        <select class="custom-select send_mail_subdir" name="subdir" id="send_mail_subdir_{{$customer_mail_dir->pos}}">
                            <option value="0">keinen Unterordner</option>
                        @foreach($value->booking->travel_country->getMailDirs($customer_mail_dir->pos) as $mail_dir_id)
                            @php ($mail_dir_name = \App\Services\Booking::getCustomerMailName($customer_mail_dir, $mail_dir_id))
                                <option value="{{$mail_dir_id}}" @if($value->customer_mail_subdir == $mail_dir_id) selected @endif>{{$mail_dir_name}}</option>
                        @endforeach
                        </select>
                        @endif
                    @endforeach
                @endif
            </div>
        </div>
    @endif
    @if(isset($value->customer_mail))
        {{ Form::hidden('customer_mail_id', $value->customer_mail->id) }}
    @endif
    <hr>
    {!! Form::close() !!}

    <div class="row">
        <div class="col-12">
            @if($value->show === 'single' && isset($value->booking))
                <button type="button" class="btn btn-sm btn-outline-primary mt-1 mb-2 float-right" data-toggle="collapse" data-target="#collapseModalBookingFiles" aria-expanded="false" aria-controls="collapseModalBookingFiles"><i class="fa fa-plus-circle"></i> Dateien aus Buchung</button>
            @endif
            <h5>Datei Anhänge</h5>
        </div>
        @if($value->show === 'single' && isset($value->booking))
            <div class="collapse col-12" id="collapseModalBookingFiles">
                @include('customer.mail.modal-new-booking-files', ['booking'=>$value->booking])
            </div>
        @endif
        <div class="col-12">
            <div class="alert alert-danger alert-dismissable" style="display:none;"></div>
        </div>
        <div class="col-6" id="preview-mail-attachment">
            @if(isset($value->customer_files))
                @foreach($value->customer_files as $customer_file)
                    <div class="message-attachment ui-bordered p-2 mr-3 mb-3">
                        <div class="message-attachment-file display-4"><i class="mail-att-icon {{$customer_file->getIconExt()}}"></i></div>
                        <div class="media-body ml-3">
                            <strong class="message-attachment-filename">{{$customer_file->original_name}}</strong>
                            <div class="text-muted small mail-att-size">{{$customer_file->formatBytes()}}</div>
                            <div>
                                <a href="{{$customer_file->getURL()}}" target="_blank" class="mail-att-show">Vorschau</a> &nbsp;
                                <a href="javascript:void(0)" data-url="{{route('customer_mail_ajax')}}" data-id="{{$customer_file->id}}" data-action="delete_mail_attachment" class="mail-att-delete">löschen</a>
                            </div>
                        </div>
                    </div>
                @endforeach
            @endif
        </div>
        <div class="col-6">
            {!! Form::open([ 'url' => route('customer_mail_upload_attachment', ['tmp']), 'method' => 'post', 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'uploadAttachmentFile' ]) !!}
            <div class="fallback">
                <input name="file" type="file" multiple>
            </div>
            {!! Form::close() !!}
        </div>
    </div>

    @if(isset($value->customer_mail))
        <hr>
        @include('customer.mail.modal-show-mail-inner', ['customer_mail' => $value->customer_mail])
    @endif
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-default float-left" data-dismiss="modal">schließen</button>
    @if($value->show === 'single' || $value->show === 'multi')
        @if($value->draft)
            <button type="submit" class="btn btn-next submit-button-form" value="draft"><i class="ion ion-ios-save"></i> Entwurf speichern</button>
        @endif
    <button type="submit" class="btn btn-primary submit-button-form" value="send"><i class="ion ion-ios-mail-open"></i> E-Mail senden</button>
    @endif
    @if($value->show === 'reply')
        <button type="submit" class="btn btn-primary submit-button-form" value="save"><i class="ion ion-ios-mail-open"></i> Antwort speichern</button>
    @endif
</div>
    <div class="message-attachment ui-bordered p-2 mr-3 mb-3 d-none" id="mail-attachment-template">
        <div class="message-attachment-file display-4"><i class="mail-att-icon"></i></div>
        <div class="media-body ml-3">
            <strong class="message-attachment-filename"> </strong>
            <div class="text-muted small mail-att-size"> </div>
            <div>
                <a href="javascript:void(0)" target="_blank" class="mail-att-show">Vorschau</a> &nbsp;
                <a href="javascript:void(0)" class="mail-att-remove">entfernen</a>
            </div>
        </div>
    </div>
</div>


<script type="text/javascript">

    function callback_ajax_add_attachment(response) {
        if(response.error === false){
            add_mail_attachment_preview(response);
        }
    }

    function add_mail_attachment_preview(response){
        console.log(response);
        var template = $('#mail-attachment-template').clone()
            .removeAttr('id').removeClass('d-none')
            .attr('data-id', response.file_id);
        template.find('.mail-att-icon').addClass(response.file_icon);
        template.find('.message-attachment-filename').text(response.original_name);
        template.find('.mail-att-size').text(response.file_format_bytes);

        ///'storage/file/{id}/{disk}
        template.find('.mail-att-show').attr('href', response.file_url);
        template.find('.mail-att-remove').on('click', function () {
            $(this).parents('.message-attachment').remove();
        });
        $('#preview-mail-attachment').append(template);
    }

    function change_mail_subdir_select(){
        var $dir_id = $('#send_mail_dir').val();
        $('.send_mail_subdir').each(function () {
            var send_mail_subdir = 'send_mail_subdir_' + $dir_id;
            if($(this).attr('id') === send_mail_subdir){
                $(this).prop('disabled', false);
                $(this).show();
            }else{
                $(this).prop('disabled', true);
                $(this).val(0);
                $(this).hide();
            }
        })
    }

    $(document).ready(function() {
        change_mail_subdir_select();
        $('#send_mail_dir').on('change', function () {
            change_mail_subdir_select();
        });
        if (!window.Quill) {
            $('#message-editor,#message-editor-toolbar').remove();
            $('#message-editor-fallback').removeClass('d-none');
        } else {
            Quill.register('modules/placeholder', PlaceholderModule.default(Quill))
            //$('#message-editor-fallback').remove();
            var quill = new Quill('#message-editor', {
                debug: 'error',
                modules: {
                    toolbar: '#message-editor-toolbar',
                    placeholder: {
                        placeholders: [
                            {!! \App\Services\Placeholder::getBookingQuill() !!}
                        ]
                    }
                },
                placeholder: '{{$value->m_placeholder}}',
                theme: 'snow'
            });
        }

        $('.b-material-datetime-picker').bootstrapMaterialDatePicker({
            weekStart: 1,
            format : 'DD.MM.YYYY HH:mm',
            shortTime: false,
            nowButton : true,
            clearButton: true,
            lang: 'de',
            //currentDate: ''
        });

        $(".submit-button-form").click(function(event) {
            @if(isset($value->customers))
            if($(this).val() === 'send' && !confirm('E-Mail wirklich senden?')){
                event.preventDefault();
                return;
            }
            @endif
            $('#customer-mail-form input[name=action]').val($(this).val());
            $("#message-editor-fallback").val($('#message-editor .ql-editor').html());
            var message_attachment = $('#preview-mail-attachment').find('.message-attachment');
            $.each( message_attachment, function( index, value ){
                $('#customer-mail-form').append('<input type="hidden" name="message_attachment_id[]" value="'+$(value).data('id')+'">');
            });
            $( "#customer-mail-form" ).submit();
        });

        $("#preview-mail-attachment .mail-att-delete").click(function(event) {
            _self = $(this);
            if(!confirm('Angang wirklick löschen?')){
                event.preventDefault();
                return;
            }
            ajax_object_action(event, $(this), function (data) {
                console.log(data);
                if(data.status === 'success'){
                    _self.parents('.message-attachment').remove();
                }
            });


        });


        var emailTempplateTable = $('#datatables-email-templates').DataTable({
            "processing": true,
            "serverSide": true,
            "searching": true,
            "autoWidth": false,
            ajax: {
                url: '{!! route( 'email_template_data_table' ) !!}',
                data: function(d) {
                    d.filter_email_templates_directory = $('select[name=filter_email_templates_directory]').val();
                }
            },
            "columns": [
                { data: 'id', width: '8%', searchable: true },
                { data: 'name', name: 'name', width: '', searchable: true },
                { data: 'email_template_dir.name', name: 'email_template_dir.name', width: '25%', orderable: false, searchable: false },
                { data: 'action',  width: '8%', orderable: false, searchable: false},
            ],
            "bLengthChange": false,
            "iDisplayLength": 10,
            "orderSequence": ["desc", "asc"],
            "order": [[ 0, "desc" ]],
            "language": {
                "url": "/js/German.json"
            },
            "drawCallback": function( settings ) {
               $('#datatables-email-templates [rel="tooltip"]').tooltip({trigger: "hover"});
                 $('#datatables-email-templates .email-template-action').on('click', function (event) {
                    ajax_object_action(event, $(this), callback_email_template_data_table);
                });
            }
        });
        $('#filter_email_templates_directory').on('change', function(){
            emailTempplateTable.draw();
        });

        function callback_email_template_data_table(data) {
            if(data.status === 'success'){
                $('input#subject').val(data.response.subject + $('input#lead_title_id').val());
                $("input#message-editor-fallback").val(data.html);
                $('#message-editor .ql-editor').html(data.html)
                $('#collapseModalEmailTemplate').collapse('hide');
            }
        }

        Dropzone.autoDiscover = false;
        $("#uploadAttachmentFile").dropzone({
            uploadMultiple: false,
            parallelUploads: 1,
            maxFilesize: 32,
            addRemoveLinks: true,
            dictDefaultMessage: '<i class="ion ion-ios-cloud-upload "></i>Hier klicken, oder Datei hier reinziehen (Drag&Drop)',
            dictFallbackMessage: 'Ihr Browser unterstützt Drag&Drop Dateiuploads nicht',
            dictFallbackText: 'Benutzen Sie das Formular um Ihre Dateien hochzuladen',
            dictFileTooBig: "Die Datei ist zu groß. Die maximale Dateigröße beträgt 32 MB",
            dictInvalidFileType: 'Eine Datei dieses Typs kann nicht hochgeladen werden',
            dictResponseError: "Der Server hat ihre Anfrage mit Status error abgelehnt",
            dictCancelUpload: 'Hochladen abbrechen',
            dictCancelUploadConfirmation: null,
            dictRemoveFile: 'Datei entfernen',
            dictMaxFilesExceeded: 'Sie können keine weiteren Dateien mehr hochladen',
            acceptedFiles: "image/jpeg,image/pjpeg,image/png,image/gif,application/pdf,text/plain",
            // The setting up of the dropzone
            init:function() {
                this.on("removedfile", function(file) {
                    var _ele = $('.alert-danger');
                    _ele.fadeOut();

                });
                this.on("addedfile", function (file) {
                    var _ele = $('.alert-danger');
                    _ele.fadeOut();
                });
            },
            error: function(file, response) {
                var message
                if($.type(response) === "string")
                    message = response; //dropzone sends it's own error messages in string
                else
                    message = response.message;
                var _ele = $('.alert-danger');
                _ele.fadeIn();
                console.log(message);
                _ele.text(message);
            },
            success: function(file,response) {
              //  console.log(file);
              //  console.log(response);
                if(response.error === false){
                    add_mail_attachment_preview(response);
                    this.removeFile(file);
                }
            }
        });

    });
</script>