<?= view('common/top_header_backdesk.php') ?>

<body>
<div class="container-scroller">
    <?= view('common/top_navbar') ?>
    <div class="container-fluid page-body-wrapper">
        <?= view('common/side_navbar') ?>
        <div class="main-panel">
            <div class="content-wrapper">
                <div class="card">
                    <?php if (!empty($services)): ?>
                        <!-- EDIT FORM -->
                        <form id="service_edit_form" method="post" class="card-body">
                            <h4 class="card-title">Edit Home Service <hr></h4>
                            <input type="hidden" name="id" value="<?= esc($services['id']) ?>">

                            <div class="form-group">
                                <label class="font-weight-bold">Content</label>
                                <textarea name="content" id="editor" class="form-control" rows="10"><?= esc($services['content']) ?></textarea>
                            </div>

                            <button type="submit" class="btn btn-primary btn-sm mt-3">
                                <i class="mdi mdi-content-save"></i> Update
                            </button>
                        </form>
                    <?php else: ?>
                        <!-- ADD NEW FORM -->
                        <form id="service_add_form" method="post" class="card-body">
                            <h4 class="card-title">Add Home Service <hr></h4>

                            <div class="form-group">
                                <label class="font-weight-bold">Content</label>
                                <textarea name="content" id="editor" class="form-control" rows="10"></textarea>
                            </div>

                            <button type="submit" class="btn btn-success btn-sm mt-3">
                                <i class="mdi mdi-plus"></i> Add Service
                            </button>
                        </form>
                    <?php endif; ?>
                </div>

                <footer class="footer mt-3">
                    <div class="d-sm-flex justify-content-center justify-content-sm-between">
                        <span class="text-muted">© <?= date('Y') ?> <?= COMPANY_FULL_NAME ?>. All rights reserved.</span>
                        <span class="float-sm-right">With gratitude from <i class="mdi mdi-heart text-danger"></i>
                            <a href="<?= CREDIT_LINK ?>" target="_blank"><?= CREDIT_TITLE ?></a></span>
                    </div>
                </footer>
            </div>
        </div>
    </div>
</div>

<?= view('common/footer_backdesk.php') ?>

<!-- CKEditor 5 CDN -->
<!-- <script src="https://cdn.ckeditor.com/ckeditor5/39.0.1/classic/ckeditor.js"></script>

<script>
    let editor;

    ClassicEditor
        .create(document.querySelector('#editor'), {
            // Add the SourceEditing button to your toolbar
            toolbar: [
                'heading', '|',
                'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote',
                'sourceEditing' // This enables the source view toggle button
            ],

            // Allow all HTML tags, attributes, classes, and styles (optional)
            htmlSupport: {
                allow: [
                    {
                        name: /.*/,
                        attributes: true,
                        classes: true,
                        styles: true
                    }
                ]
            },

            // Optional: show previews for embedded HTML
            htmlEmbed: {
                showPreviews: true
            }
        })
        .then(newEditor => {
            editor = newEditor;

            $(document).ready(function () {
                const csrfTokenName = '<?= csrf_token() ?>';
                const csrfTokenValue = '<?= csrf_hash() ?>';
                const jwtToken = localStorage.getItem('jwt_token');

                <?php if (!empty($services)): ?>
                $('#service_edit_form').on('submit', function (e) {
                    e.preventDefault();

                    const formData = new FormData();
                    formData.append('id', '<?= esc($services['id']) ?>');
                    formData.append('content', editor.getData());
                    formData.append(csrfTokenName, csrfTokenValue);

                    $.ajax({
                        url: '<?= base_url('api/home/home-services/update') ?>',
                        method: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        headers: {
                            'Authorization': 'Bearer ' + jwtToken
                        },
                        success: function (response) {
                            if (response.status) {
                                toast('success', response.message);
                                window.location.href = '<?= base_url('backdesk/home-services/index') ?>';
                            } else {
                                toast('danger', response.message || 'Something went wrong!');
                            }
                        },
                        error: function (xhr) {
                            toast('danger', 'API error: ' + xhr.responseText);
                        }
                    });
                });
                <?php else: ?>
                $('#service_add_form').on('submit', function (e) {
                    e.preventDefault();

                    const formData = new FormData();
                    formData.append('content', editor.getData());
                    formData.append(csrfTokenName, csrfTokenValue);

                    $.ajax({
                        url: '<?= base_url('api/home/home-services/create') ?>',
                        method: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        headers: {
                            'Authorization': 'Bearer ' + jwtToken
                        },
                        success: function (response) {
                            if (response.status) {
                                toast('success', response.message);
                                window.location.href = '<?= base_url('backdesk/home-services/index') ?>';
                            } else {
                                toast('danger', response.message || 'Something went wrong!');
                            }
                        },
                        error: function (xhr) {
                            toast('danger', 'API error: ' + xhr.responseText);
                        }
                    });
                });
                <?php endif; ?>
            });
        })
        .catch(error => {
            console.error('CKEditor init error:', error);
        });
</script> -->


<script>
    <?php if (!empty($services)): ?>
    $(document).ready(function () {
        const csrfTokenName = '<?= csrf_token() ?>';
        const csrfTokenValue = '<?= csrf_hash() ?>';
        const jwtToken = localStorage.getItem('jwt_token');

        // Initialize Trumbowyg editor on textarea#editor (make sure your textarea has id="editor")
        $('#editor').trumbowyg({
            btns: [['viewHTML'], ['formatting'], 'bold', 'italic', 'underline'],
            autogrow: true,
            resetCss: true,
            semantic: false
        });

        $('#service_edit_form').on('submit', function (e) {
            e.preventDefault();

            // Get HTML content from Trumbowyg
            const content = $('#editor').trumbowyg('html');
            // Put content back into textarea before submitting
            $('#editor').val(content);

            const formData = new FormData(this);
            formData.append(csrfTokenName, csrfTokenValue);

            $.ajax({
                url: '<?= base_url('api/home/home-services/update') ?>',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'Authorization': 'Bearer ' + jwtToken
                },
                success: function (response) {
                    if (response.status) {
                        toast('success', response.message);
                        window.location.href = '<?= base_url('backdesk/home-services/index') ?>';
                    } else {
                        toast('danger', response.message || 'Something went wrong!');
                    }
                },
                error: function (xhr) {
                    toast('danger', 'API error: ' + xhr.responseText);
                }
            });
        });
    });
    <?php else: ?>
        $(document).ready(function () {
            const csrfTokenName = '<?= csrf_token() ?>';
            const csrfTokenValue = '<?= csrf_hash() ?>';
            const jwtToken = localStorage.getItem('jwt_token');

            // Initialize Trumbowyg editor on textarea#editor
            $('#editor').trumbowyg({
                btns: [['viewHTML'], ['formatting'], 'bold', 'italic', 'underline'],
                autogrow: true,
                resetCss: true,
                semantic: false
            });

            $('#service_add_form').on('submit', function (e) {
                e.preventDefault();

                // Get HTML content from Trumbowyg
                const content = $('#editor').trumbowyg('html');
                // Put content back into textarea before submitting
                $('#editor').val(content);

                const formData = new FormData(this);
                formData.append(csrfTokenName, csrfTokenValue);

                $.ajax({
                    url: '<?= base_url('api/home/home-services/create') ?>',
                    method: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    headers: {
                        'Authorization': 'Bearer ' + jwtToken
                    },
                    success: function (response) {
                        if (response.status) {
                            toast('success', response.message);
                            window.location.href = '<?= base_url('backdesk/home-services/index') ?>';
                        } else {
                            toast('danger', response.message || 'Something went wrong!');
                        }
                    },
                    error: function (xhr) {
                        toast('danger', 'API error: ' + xhr.responseText);
                    }
                });
            });
        });
    <?php endif; ?>
</script>




</body>
</html>
