<?= view('common/top_header_backdesk.php') ?>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    .form-control, select.form-control {
        outline: 1px solid #67676b;
        border-radius: 5px;
        padding: 8px 10px;
    }
    .error {
        color: red;
        padding-top: 10px;
    }
</style>
</head>

<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">
                    <form id="page_content_form" class="card-body" method="post">
                        <h4 class="card-title">Add Page Content</h4>
                        <hr>

                        <!-- Menu -->
                        <div class="row">
                            <div class="col-md-6">
                                <label class="font-weight-bold">Menu <span class="text-danger">*</span></label>
                                <select name="menu_id" id="menu_id" class="form-control select2" required>
                                    <option value="">-- Select Menu --</option>
                                    <?php foreach ($menus as $menu): ?>
                                        <?php if ($menu['parent_id'] == 0): ?>
                                            <option value="<?= esc($menu['id']) ?>"><?= esc($menu['name']) ?></option>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <!-- Submenu -->
                            <div class="col-md-6">
                                <label class="font-weight-bold">Submenu <span class="text-danger">*</span></label>
                                <select name="submenu_id" id="submenu_id" class="form-control select2" required>
                                    <option value="">-- Select Submenu --</option>
                                    <?php foreach ($menus as $menu): ?>
                                        <?php if ($menu['parent_id'] != 0): ?>
                                            <option value="<?= esc($menu['id']) ?>" data-parent="<?= esc($menu['parent_id']) ?>">
                                                <?= esc($menu['name']) ?>
                                            </option>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <!-- Sections with CKEditor -->
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                            <div class="row mt-3">
                                <div class="col-md-12">
                                    <label class="font-weight-bold">Section <?= $i ?></label>
                                    <textarea name="section<?= $i ?>" id="section<?= $i ?>" class="form-control ckeditor" rows="4" placeholder="Enter Section <?= $i ?> content..."></textarea>
                                </div>
                            </div>
                        <?php endfor; ?>

                        <div class="col-md-6 mt-3">
                            <div class="form-group">
                                <label>Banner Image</label>
                                <input type="file" name="banner_image" class="form-control-file" id="banner_image_input">
                                
                                <!-- Banner Preview -->
                                <div id="banner_preview_container" class="mt-2">
                                    <img id="banner_preview" src="" alt="Banner Image" style="max-width: 100%; height: auto; display: none;">
                                </div>
                            </div>
                        </div>


                        <!-- Submit -->
                        <div class="row mt-4">
                            <div class="col-md-12">
                                <button type="submit" class="btn btn-success btn-sm">
                                    <i class="mdi mdi-content-save"></i> Save Content
                                </button>
                                <a href="<?= base_url('backdesk/dashboard') ?>" class="btn btn-secondary btn-sm">Cancel</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <footer class="footer">
                <div class="d-sm-flex justify-content-center justify-content-sm-between">
                    <span class="text-muted d-block d-sm-inline-block">© <?= date('Y') . ' ' . COMPANY_FULL_NAME ?></span>
                    <span class="float-none float-sm-right d-block mt-1 mt-sm-0 text-center">
                        With ❤️ from <a href="<?= CREDIT_LINK ?>" target="_blank"><?= CREDIT_TITLE ?></a>
                    </span>
                </div>
            </footer>
        </div>
    </div>
</div>

<!-- JS Includes -->
<?= view('common/footer_backdesk.php') ?>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function () {
    $('.select2').select2();

    const allMenus = <?= json_encode($menus) ?>;

    // Filter submenu options when menu changes
    $('#menu_id').on('change', function () {
        const selectedMenu = $(this).val();
        const submenuSelect = $('#submenu_id');
        submenuSelect.empty().append('<option value="">-- Select Submenu --</option>');

        allMenus.forEach(menu => {
            if (menu.parent_id == selectedMenu) {
                submenuSelect.append(`<option value="${menu.id}">${menu.name}</option>`);
            }
        });

        submenuSelect.val('').trigger('change');
    });

    // Initialize Trumbowyg editors for each section textarea
    const editorInstances = {};
    for (let i = 1; i <= 5; i++) {
        editorInstances[`section${i}`] = $(`#section${i}`).trumbowyg({
            btns: [['viewHTML'], ['formatting'], 'bold', 'italic', 'underline'],
            autogrow: true,
            resetCss: true,
            semantic: false
        });
    }

    $('#submenu_id').on('change', function () {
        const menuId = $('#menu_id').val();
        const submenuId = $(this).val();

        if (!menuId || !submenuId) {
            return;
        }

        const jwtToken = localStorage.getItem('jwt_token');

        $.ajax({
            url: '<?= base_url('api/page-contents/get-by-menu-submenu') ?>',
            method: 'GET',
            data: {
                menu_id: menuId,
                submenu_id: submenuId
            },
            headers: {
                'Authorization': 'Bearer ' + jwtToken
            },
            success: function (response) {
                if (response.status === true && response.data) {
                    for (let i = 1; i <= 5; i++) {
                        const content = response.data[`section${i}`] || '';
                        // Set content in Trumbowyg editor
                        editorInstances[`section${i}`].trumbowyg('html', content);
                    }
                    const bannerImage = response.data['banner_image'];
                    if (bannerImage) {
                        const imageUrl = '<?= base_url('uploads/page_banners/') ?>' + bannerImage;
                        $('#banner_preview').attr('src', imageUrl).show();
                    } else {
                        $('#banner_preview').hide().attr('src', '');
                    }
                } else {
                    for (let i = 1; i <= 5; i++) {
                        editorInstances[`section${i}`].trumbowyg('html', '');
                    }
                }
            },
            error: function (xhr) {
                toast('danger', 'Failed to load existing content.');
                for (let i = 1; i <= 5; i++) {
                    editorInstances[`section${i}`].trumbowyg('html', '');
                }
            }
        });
    });

    // Handle form submission
    $('#page_content_form').on('submit', function (e) {
        e.preventDefault();

        const jwtToken = localStorage.getItem('jwt_token');
        const formData = new FormData(this);

        // Add Trumbowyg data to FormData
        for (let i = 1; i <= 5; i++) {
            const editorData = editorInstances[`section${i}`].trumbowyg('html') || '';
            formData.set(`section${i}`, editorData);
        }

        formData.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');

        $.ajax({
            url: '<?= base_url('api/page-contents/save-or-update') ?>',
            method: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            headers: {
                'Authorization': 'Bearer ' + jwtToken
            },
            success: function (response) {
                if (response.status === true) {
                    toast('success', response.message || 'Page content saved successfully');
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                } else {
                    toast('danger', response.message || 'Something went wrong');
                }
            },
            error: function (xhr) {
                toast('danger', 'Request failed: ' + xhr.statusText);
            }
        });
    });
});
</script>

</body>
</html>
