@extends('layouts.adminmaster')

@section('styles')
    <!-- INTERNAl Summernote css -->
    <link rel="stylesheet" href="{{asset('build/assets/plugins/summernote/summernote.css')}}">
@endsection

@section('styles')

    <!-- INTERNAL multiselecte css-->
    <link href="{{asset('build/assets/plugins/multipleselect/multiple-select.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />
    <link href="{{asset('build/assets/plugins/multi/multi.min.css')}}?v=<?php echo time(); ?>" rel="stylesheet" />

@endsection

@section('content')

    <!--Page header-->
    <div class="page-header d-xl-flex d-block">
        <div class="page-leftheader">
            <h4 class="page-title"><span class="font-weight-normal text-muted ms-2">{{ lang('Edit Campaign Template', 'menu') }}</span></h4>
        </div>
    </div>
    <!--End Page header-->

    <div class="col-xl-12 col-lg-12 col-md-12">
        <div class="card ">
            <form id="templateEditForm" enctype="multipart/form-data">
                <div class="card-header border-0 d-md-max-block">
                    <h4 class="card-title">{{ lang('Edit Campaign Template') }}</h4>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-xl-6">
                            <div class="form-group">
                                <label class="form-label">{{lang('Title')}} <span class="text-red">*</span> <small><i>({{ lang('Max 255 characters only') }})</i></small></label>
                                <input type="text" id="title" name="title" value="{{ $template->title }}"  placeholder="{{ lang('Enter title') }}" class="form-control" maxlength="255">
                                <span class="text-danger" id="titleError"></span>
                                @error('title')
                                    <span class="invalid-feedback d-block" role="alert">
                                        <strong>{{ lang($message) }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                        <div class="col-xl-6">
                            <div class="form-group">
                                <label class="form-label">{{lang('Email Subject')}} <span class="text-red">*</span> <small><i>({{ lang('Max 255 characters only') }})</i></small></label>
                                <input type="text" id="subject" name="subject" value="{{ $template->subject }}" placeholder="{{ lang('Enter subject for email') }}" class="form-control" maxlength="255">
                                <span class="text-danger" id="emailSubjectError"></span>
                                @error('subject')
                                    <span class="invalid-feedback d-block" role="alert">
                                        <strong>{{ lang($message) }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                        <div class="col-xl-12">
                            <div class="form-group">
                                <label class="form-label">{{lang('Email Body')}} <span class="text-red">*</span></label>
                                <textarea rows="25" id="messageTextarea" class="summernote form-control" name="message">
                                    {{ $template->message }}
                                </textarea>
                                <span class="text-danger" id="EmailMessageError"></span>
                                @error('message')
                                    <span class="invalid-feedback d-block" role="alert">
                                        <strong>{{ lang($message) }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <div class="form-group float-end">
                        <button class="btn btn-secondary" type="submit">{{ lang('Update') }}</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

@endsection

@section('scripts')

    <!-- INTERNAL Summernote js  -->
    <script src="{{asset('build/assets/plugins/summernote/summernote.js')}}"></script>

    <script>
        $(function() {
            "use strict";

            $('.summernote').summernote();
            (function($) {

                // Variables
                var SITEURL = '{{ url('') }}';

                // Csrf Field
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });

            })(jQuery);

            let id = @json($template->id);

            document.querySelector('#templateEditForm').onsubmit = async (e) => {
                e.preventDefault();

                e.target.querySelector('.btn.btn-secondary').innerHTML = '{{ lang('Sending ... ') }} <i class="fa fa-spinner fa-spin"></i>';
                e.target.querySelector('.btn.btn-secondary').classList.add('disabled');
                e.target.querySelector('.btn.btn-secondary').disabled = true;

                let title = document.querySelector('#title');
                let subject = document.querySelector('#subject');
                let message = document.querySelector('#messageTextarea');

                let titleError = document.querySelector('#titleError');
                let subjectError = document.querySelector('#emailSubjectError');
                let messageError = document.querySelector('#EmailMessageError');

                // Clear previous error messages
                titleError.innerHTML = '';
                subjectError.innerHTML = '';
                messageError.innerHTML = '';

                let formData = {
                    id: id,
                    title: title.value.trim(),
                    subject: subject.value.trim(),
                    message: message.value.trim(),
                };
                // Validation
                let isValid = true;

                if (formData.message == '') {
                    messageError.innerHTML = '{{ lang('Email body field is required') }}';
                    isValid = false;
                }

                if (formData.subject == '') {
                    subjectError.innerHTML = '{{ lang('Subject field is required') }}';
                    isValid = false;
                }

                if (formData.title == '') {
                    titleError.innerHTML = '{{ lang('Title field is required') }}';
                    isValid = false;
                }
                // If the form is valid, submit it (you can add your form submission logic here)
                if (isValid) {

                    const response = await fetch(SITEURL+'/admin/emailCampaigns/templates/update', {
                        method: "POST",
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                            'X-Requested-With' : 'XMLHttpRequest',
                            'Accept':'application/json, text/javascript, */*; q=0.01',
                        },
                        body: JSON.stringify(formData),
                    });
                    const data = await response.json();
                    if (data?.success) {
                        toastr.success(data.success);
                        e.target.querySelector('.btn.btn-secondary').innerHTML = '{{ lang('Update') }}';
                        e.target.querySelector('.btn.btn-secondary').classList.remove('disabled');
                        e.target.querySelector('.btn.btn-secondary').disabled = false;
                        localStorage.setItem('success', data.success);
                        location.href = SITEURL + '/admin/emailCampaigns/templates'
                    }
                    if (data?.errors) {
                        if (data?.errors?.title) {
                            e.target.querySelector('.btn.btn-secondary').innerHTML = '{{ lang('Update') }}';
                            e.target.querySelector('.btn.btn-secondary').classList.remove('disabled');
                            e.target.querySelector('.btn.btn-secondary').disabled = false;
                            titleError.innerHTML = '{{ lang('The title has already been taken.') }}';
                        }
                        if (data?.errors?.subject) {
                            e.target.querySelector('.btn.btn-secondary').innerHTML = '{{ lang('Update') }}';
                            e.target.querySelector('.btn.btn-secondary').classList.remove('disabled');
                            e.target.querySelector('.btn.btn-secondary').disabled = false;
                            subjectError.innerHTML = '{{ lang('The subject must not be greater than 255 characters.') }}';
                        }
                    }
                } else {
                    e.target.querySelector('.btn.btn-secondary').innerHTML = '{{ lang('Update') }}';
                    e.target.querySelector('.btn.btn-secondary').classList.remove('disabled');
                    e.target.querySelector('.btn.btn-secondary').disabled = false;
                }

            }

            const textarea = document.getElementById("messageTextarea");
            const outputArea = document.getElementById("outputArea");
            let debounceTimer;

            textarea.addEventListener("input", function () {
                clearTimeout(debounceTimer);
                debounceTimer = setTimeout(function () {
                    // Update the output area with the current textarea value
                    outputArea.innerHTML = textarea.value;
                }, 3000); // 5000 milliseconds = 5 seconds
            });
        });
    </script>
@endsection
