<script src="https://cdn.jsdelivr.net/npm/tinymce@6.8.3/tinymce.min.js" referrerpolicy="origin"></script>
<script>
(function () {
    var uploadUrl = @json(route('admin.announcements.media.upload'));
    var csrfToken = @json(csrf_token());

    tinymce.init({
        selector: '#announcement-content',
        directionality: 'rtl',
        language: 'fa',
        height: 500,
        menubar: 'edit insert view format table',
        plugins: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table help wordcount autoresize codesample emoticons',
        toolbar: 'undo redo | blocks fontsize | bold italic underline strikethrough | forecolor backcolor | alignright aligncenter alignleft alignjustify | bullist numlist outdent indent | link image media table codesample | removeformat code fullscreen',
        toolbar_mode: 'sliding',
        autoresize_bottom_margin: 30,
        branding: false,
        promotion: false,
        relative_urls: false,
        remove_script_host: false,
        convert_urls: false,
        image_caption: true,
        image_advtab: true,
        automatic_uploads: true,
        file_picker_types: 'image',
        images_upload_url: uploadUrl,
        images_upload_credentials: true,
        images_upload_handler: function (blobInfo, progress) {
            return new Promise(function (resolve, reject) {
                var fd = new FormData();
                fd.append('file', blobInfo.blob(), blobInfo.filename());
                fd.append('_token', csrfToken);

                var xhr = new XMLHttpRequest();
                xhr.open('POST', uploadUrl, true);
                xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

                xhr.upload.onprogress = function (e) {
                    progress(e.loaded / e.total * 100);
                };

                xhr.onload = function () {
                    if (xhr.status < 200 || xhr.status >= 300) {
                        reject('خطا در آپلود: ' + xhr.status);
                        return;
                    }
                    var resp;
                    try { resp = JSON.parse(xhr.responseText); } catch (e) { reject('پاسخ نامعتبر سرور'); return; }
                    if (!resp || !resp.location) { reject('پاسخ نامعتبر سرور'); return; }
                    resolve(resp.location);
                };

                xhr.onerror = function () { reject('خطای شبکه در آپلود تصویر'); };

                xhr.send(fd);
            });
        },
        content_style: 'body { font-family: Tahoma, Arial, sans-serif; font-size: 15px; line-height: 1.9; direction: rtl; }',
    });
})();
</script>
