<?php $__env->startSection('content'); ?>
    <form action="<?php echo e(route('admin.knowledge.save', $knowledge->id ?? '')); ?>" class="editorForm" id="knowledgeForm" method="post">
        <?php echo csrf_field(); ?>
        <input type="hidden" name="status">
        <div class="knowledge-create">
            <div class="knowledge-create-body">
                <div class="knowledge-create-header">
                    <div class="flex-align gap-3">
                        <div class="knowledge-create-sidebar-toggle d-lg-none">
                            <i class="fa-solid fa-bars"></i>
                        </div>
                        <a class="title" href="<?php echo e(route('admin.knowledge.list')); ?>">
                            <i class="fa-solid fa-arrow-left"></i>
                            <?php echo app('translator')->get('Knowledge List'); ?>
                        </a>
                    </div>

                    <div class="flex-align gap-2">
                        <button class="btn btn-outline--base btn--sm me-1 aiModalBtn" type="button">
                            <i class="fa-solid fa-wand-magic-sparkles me-1"></i><?php echo app('translator')->get('AI Assist'); ?>
                        </button>
                        <button class="btn btn--base btn--sm me-1 publishBtn" type="button"><?php echo app('translator')->get('Publish'); ?></button>
                        <a href="<?php echo e(route('admin.knowledge.list')); ?>" class="btn btn-outline--secondary btn--sm cancelBtn" type="button"><?php echo app('translator')->get('Cancel'); ?></a>
                    </div>
                </div>
                <div class="knowledge-create-body-top">
                    <input type="text" class="article-input-control" name="title" value="<?php echo e(old('title', $knowledge->title ?? '')); ?>" autofocus placeholder="<?php echo app('translator')->get('Article Title'); ?>" required>
                    <input type="text" class="article-input-control style--sm" name="subtitle" value="<?php echo e(old('subtitle', $knowledge->subtitle ?? '')); ?>" placeholder="<?php echo app('translator')->get('Sub Title (Optional)'); ?>">
                </div>
                <div class="knowledge-create-body-editor">
                    <div class="editor-wrapper">
                        <div id="editor-two">
                            <?php
                                echo $knowledge->description ?? '';
                            ?>
                        </div>
                    </div>

                    <div class="knowledge-create-block p-0 mt-3 d-lg-none">
                        <div class="knowledge-create-block-body p-0 border-0">
                            <div class="row">
                                <div class="col-sm-6 form-group">
                                    <label class="form--label style-two"><?php echo app('translator')->get('Category'); ?></label>
                                    <select class="select2" id="categoryMobile">
                                        <option value=""><?php echo app('translator')->get('Select One'); ?></option>
                                        <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($category->id); ?>" <?php if($category->id == ($knowledge->knowledge_category_id ?? '')): echo 'selected'; endif; ?> data-subcategories="<?php echo e($category->subcategories); ?>"><?php echo e(__($category->name)); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <div class="col-sm-6 form-group">
                                    <label class="form--label style-two"><?php echo app('translator')->get('Subcategory'); ?></label>
                                    <select class="select2" id="subcategoryMobile">
                                        <option value=""><?php echo app('translator')->get('Select One'); ?></option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <input type="hidden" name="description">
                <button class="submitBtn d-none"></button>
            </div>
            <div class="knowledge-create-sidebar">
                <div class="flex-between knowledge-create-sidebar-header">
                    <p class="title"><?php echo app('translator')->get('Manage Settings'); ?></p>
                    <div class="knowledge-create-sidebar-close d-lg-none fs-20">
                        <i class="las la-times"></i>
                    </div>
                </div>

                <div class="knowledge-create-block">
                    <p class="knowledge-create-block-title"><?php echo app('translator')->get('Article Created by'); ?></p>
                    <?php
                        $admin = auth('admin')->user();
                    ?>
                    <div class="knowledge-create-block-body">
                        <div class="knowledge-create-auth">
                            <div class="thumb">
                                <img src="<?php echo e(getImage(getFilePath('adminProfile') . '/' . $admin->image, getFileSize('adminProfile'), true)); ?>" alt="">
                            </div>
                            <div class="info">
                                <p class="name"><?php echo e($admin->name); ?></p>
                                <p class="email"><?php echo e($admin->email); ?></p>
                            </div>
                        </div>
                        <div class="knowledge-create-date">
                            <span class="label"><?php echo app('translator')->get('Created at'); ?></span>
                            <span class="value">
                                <?php echo $__env->make('admin.partials.svg.calendar', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                                <?php echo e(showDateTime(now(), 'd M Y h:i A')); ?>

                            </span>
                        </div>
                    </div>
                </div>

                <div class="knowledge-create-block d-none d-lg-block">
                    <p class="knowledge-create-block-title"><?php echo app('translator')->get('Other Information'); ?></p>

                    <div class="knowledge-create-block-body">
                        <div class="form-group">
                            <label class="form--label style-two"><?php echo app('translator')->get('Category'); ?></label>
                            <select class="select2" name="category" required>
                                <option value=""><?php echo app('translator')->get('Select One'); ?></option>
                                <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($category->id); ?>" <?php if($category->id == ($knowledge->knowledge_category_id ?? '')): echo 'selected'; endif; ?> data-subcategories="<?php echo e($category->subcategories); ?>"><?php echo e(__($category->name)); ?></option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label class="form--label style-two"><?php echo app('translator')->get('Subcategory'); ?></label>
                            <select class="select2" name="subcategory" required>
                                <option value=""><?php echo app('translator')->get('Select One'); ?></option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <div class="modal custom--modal fade" id="aiAssistModal" tabindex="-1" role="dialog" aria-labelledby="aiAssistModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="aiAssistModalLabel"><?php echo app('translator')->get('AI Assistant'); ?></h5>
                    <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                        <i class="las la-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <form class="ai-assist-form" method="POST" action="<?php echo e(route('admin.knowledge.ai.generate')); ?>">
                        <?php echo csrf_field(); ?>
                        <div class="form-group mb-3">
                            <label class="form--label style-two mb-2"><?php echo app('translator')->get('Generate for fields'); ?></label>
                            <div class="ai-field-grid">
                                <label class="ai-field-option">
                                    <input type="checkbox" name="fields[]" value="title" class="exceptInput">
                                    <span class="label"><?php echo app('translator')->get('Title'); ?></span>
                                </label>
                                <label class="ai-field-option">
                                    <input type="checkbox" name="fields[]" value="subtitle" class="exceptInput">
                                    <span class="label"><?php echo app('translator')->get('Subtitle'); ?></span>
                                </label>
                                <label class="ai-field-option">
                                    <input type="checkbox" name="fields[]" value="description" class="exceptInput">
                                    <span class="label"><?php echo app('translator')->get('Description'); ?></span>
                                </label>
                            </div>
                            <small class="text-muted d-block mt-2"><?php echo app('translator')->get('Select one or more fields. AI will generate only for selected fields.'); ?></small>
                        </div>
                        <div class="form-group mb-3">
                            <label class="form--label style-two mb-2"><?php echo app('translator')->get('Write your instruction'); ?></label>
                            <textarea class="form--control md-style ai-prompt-textarea" name="prompt" rows="6" placeholder="<?php echo app('translator')->get('Describe what you want to write...'); ?>" required></textarea>
                        </div>
                        <button type="submit" class="btn btn--base btn--md w-100 ai-submit-btn">
                            <i class="fa-solid fa-paper-plane me-1"></i> <?php echo app('translator')->get('Submit Prompt'); ?>
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
<?php $__env->stopSection(); ?>


<?php $__env->startPush('script'); ?>
    <script>
        (function($) {
            "use strict";

            $('.publishBtn').on('click', function() {
                $('.submitBtn').click();
            });

            $('.aiModalBtn').on('click', function() {
                if (window.bootstrap) {
                    const aiModal = bootstrap.Modal.getOrCreateInstance(document.getElementById('aiAssistModal'));
                    aiModal.show();
                }
            });

            $('[name=category], #categoryMobile').on('change', function() {
                let subcategories = $(this).find(':selected').data('subcategories');
                let subcategory = $('[name="subcategory"], #subcategoryMobile');
                subcategory.empty().append(`<option value=""><?php echo app('translator')->get('Select One'); ?></option>`);
                if (Array.isArray(subcategories)) {
                    subcategories.forEach(function(sub) {
                        subcategory.append('<option value="' + sub.id + '">' + sub.name + '</option>');
                    });
                }
            }).change();

            $('[name=subcategory]').val(`<?php echo e($knowledge->knowledge_subcategory_id ?? ''); ?>`);
            $('#subcategoryMobile').val(`<?php echo e($knowledge->knowledge_subcategory_id ?? ''); ?>`);

            $('#categoryMobile').on('change', function() {
                let val = $(this).val();
                $('[name="category"]').val(val);
            });

            $('#subcategoryMobile').on('change', function() {
                let val = $(this).val();
                $('[name="subcategory"]').val(val);
            });

            function extractJsonObject(rawText) {
                if (!rawText) return null;

                try {
                    return JSON.parse(rawText);
                } catch (e) {
                    const match = rawText.match(/\{[\s\S]*\}/);
                    if (!match) return null;
                    try {
                        return JSON.parse(match[0]);
                    } catch (error) {
                        return null;
                    }
                }
            }

            function setDescriptionInEditor(text) {
                if (!window.knowledgeEditorTwo) return;
                window.knowledgeEditorTwo.setContents([]);
                window.knowledgeEditorTwo.clipboard.dangerouslyPasteHTML(text || '');
                window.knowledgeEditorTwo.setSelection(window.knowledgeEditorTwo.getLength(), 0);
            }

            $('.ai-assist-form').on('submit', function(e) {
                e.preventDefault();

                let form = $(this);
                let submitBtn = form.find('.ai-submit-btn');
                let originalBtnHtml = submitBtn.html();
                let selectedFields = form.find('input[name="fields[]"]:checked').map(function() {
                    return this.value;
                }).get();

                if (!selectedFields.length) {
                    notify('error', '<?php echo app('translator')->get("Please select at least one field"); ?>');
                    return;
                }

                let userPrompt = (form.find('[name="prompt"]').val() || '').trim();
                let requestData = form.serializeArray().filter(function(item) {
                    return item.name !== 'prompt';
                });

                requestData.push({
                    name: 'prompt',
                    value: userPrompt
                });

                submitBtn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin me-1"></i> <?php echo app('translator')->get("Generating..."); ?>');

                $.ajax({
                    type: 'POST',
                    url: form.attr('action'),
                    data: $.param(requestData),
                    success: function(response) {
                        if (response.status !== 'success') {
                            notify('error', response.message || '<?php echo app('translator')->get("Failed to generate content"); ?>');
                            return;
                        }

                        const generatedText = response && response.data && response.data.response ? response.data.response : '';
                        const parsed = extractJsonObject(generatedText);

                        if (parsed) {
                            if (selectedFields.includes('title')) {
                                $('[name="title"]').val(parsed.title || '');
                            }

                            if (selectedFields.includes('subtitle')) {
                                $('[name="subtitle"]').val(parsed.subtitle || '');
                            }

                            if (selectedFields.includes('description')) {
                                setDescriptionInEditor(parsed.description || '');
                            }
                        } else if (selectedFields.length === 1) {
                            if (selectedFields[0] === 'title') {
                                $('[name="title"]').val(generatedText);
                            } else if (selectedFields[0] === 'subtitle') {
                                $('[name="subtitle"]').val(generatedText);
                            } else if (selectedFields[0] === 'description') {
                                setDescriptionInEditor(generatedText);
                            }
                        } else {
                            if (selectedFields.includes('title')) {
                                $('[name="title"]').val(generatedText);
                            }

                            if (selectedFields.includes('subtitle')) {
                                $('[name="subtitle"]').val(generatedText);
                            }

                            if (selectedFields.includes('description')) {
                                setDescriptionInEditor(generatedText);
                            }
                        }

                        notify('success', response.message || '<?php echo app('translator')->get("Generated successfully"); ?>');

                        if (window.bootstrap) {
                            const aiModal = bootstrap.Modal.getOrCreateInstance(document.getElementById('aiAssistModal'));
                            aiModal.hide();
                        }

                        form[0].reset();
                    },
                    error: function(xhr) {
                        let message = '<?php echo app('translator')->get("Something went wrong"); ?>';
                        if (xhr.responseJSON && xhr.responseJSON.errors && xhr.responseJSON.errors.prompt && xhr.responseJSON.errors.prompt.length) {
                            message = xhr.responseJSON.errors.prompt[0];
                        } else if (xhr.responseJSON && xhr.responseJSON.message) {
                            message = xhr.responseJSON.message;
                        }

                        notify('error', message);
                    },
                    complete: function() {
                        submitBtn.prop('disabled', false).html(originalBtnHtml);
                    }
                });
            });

        })(jQuery);
    </script>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('style'); ?>
    <style>
        #aiAssistModal .modal-content {
            border: 0;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 22px 55px rgba(19, 37, 70, .18);
        }

        #aiAssistModal .modal-header {
            border-bottom: 1px solid #e9edf4;
            background: linear-gradient(135deg, #f7fbff 0%, #ecf5ff 100%);
            padding: 18px 20px;
        }

        #aiAssistModal .modal-title {
            font-weight: 700;
            color: #1f2a37;
        }

        #aiAssistModal .modal-body {
            padding: 20px;
            background-color: #fff;
        }

        .ai-prompt-textarea {
            min-height: 150px;
            border-radius: 12px;
            border: 1px solid #dce5f1;
            transition: all .2s ease;
            resize: vertical;
        }

        .ai-prompt-textarea:focus {
            border-color: #5b8def;
            box-shadow: 0 0 0 3px rgba(91, 141, 239, .18);
        }

        .ai-submit-btn {
            border-radius: 12px;
            font-weight: 600;
            letter-spacing: .2px;
            min-height: 44px;
        }

        .ai-field-grid {
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            gap: 10px;
        }

        .ai-field-option {
            display: flex;
            align-items: center;
            gap: 8px;
            border: 1px solid #dce5f1;
            border-radius: 10px;
            padding: 10px 12px;
            cursor: pointer;
            background: #f8fbff;
            transition: all .2s ease;
        }

        .ai-field-option:hover {
            border-color: #5b8def;
            background: #f0f6ff;
        }

        .ai-field-option input {
            width: 16px;
            height: 16px;
            accent-color: #5b8def;
        }

        .ai-field-option .label {
            font-weight: 600;
            color: #1f2a37;
            line-height: 1.2;
        }

        @media (max-width: 575px) {
            .ai-field-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('admin.layouts.master', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\projects\custom_viserdesk\Files\core\resources\views/admin/knowledge/form.blade.php ENDPATH**/ ?>