<?php echo view('common/top_header_backdesk.php') ?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap4.min.css" />
<style>
    .form-control { outline: 1px solid #67676b; border-radius: 5px; padding: 5px 10px; }
    .error { color: red; margin-top: 10px; }
    .form-group { margin-bottom: 20px; }
    .img-preview { max-width: 150px; margin-top: 10px; border-radius: 5px; border: 1px solid #ddd; }
</style>
</head>
<?php $session = session(); ?>

<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="library_edit_form" method="post" class="card-body" enctype="multipart/form-data" novalidate>
                        <h4 class="card-title">Edit Library</h4>
                        <hr>

                        <input type="hidden" name="id" value="<?= esc($library['id'] ?? 1) ?>">

                        <div class="row">
                            <div class="col-md-6 form-group">
                                <label class="font-weight-bold">Heading</label>
                                <input type="text" name="heading" class="form-control" value="<?= esc($library['heading'] ?? '') ?>" required>
                            </div>
                            <div class="col-md-6 form-group">
                                <label class="font-weight-bold">Head Name</label>
                                <input type="text" name="head_name" class="form-control" value="<?= esc($library['head_name'] ?? '') ?>" required>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 form-group">
                                <label class="font-weight-bold">Designation</label>
                                <input type="text" name="designation" class="form-control" value="<?= esc($library['designation'] ?? '') ?>" required>
                            </div>
                            <div class="col-md-6 form-group">
                                <label class="font-weight-bold">Head Image</label>
                                <input type="file" name="image" id="image" class="form-control" accept="image/*">
                               <?php if (!empty($library['image'])): ?>
                                    <img src="<?= base_url('uploads/library/' . esc($library['image'])) ?>" class="img-preview" id="image_preview">
                                <?php else: ?>
                                    <img src="" class="img-preview" id="image_preview" style="display:none;">
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 form-group">
                                <label class="font-weight-bold">Description</label>
                                <textarea name="description" id="description" class="form-control" rows="5" required><?= esc($library['description'] ?? '') ?></textarea>
                            </div>
                            <div class="col-md-6 form-group">
                                <label class="font-weight-bold">Vision</label>
                                <textarea name="vision" id="vision" class="form-control" rows="5" required><?= esc($library['vision'] ?? '') ?></textarea>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 form-group">
                                <label class="font-weight-bold">Featured Databases</label>
                                <textarea name="featured_databases" id="featured_databases" class="form-control" rows="5" required><?= esc($library['featured_databases'] ?? '') ?></textarea>
                            </div>
                            <div class="col-md-6 form-group">
                                <label class="font-weight-bold">Special Notes</label>
                                <textarea name="special_notes" id="special_notes" class="form-control" rows="5" required><?= esc($library['special_notes'] ?? '') ?></textarea>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12 form-group">
                                <label class="font-weight-bold">Contact Information</label>
                                <textarea name="contact_information" id="contact_information" class="form-control" rows="5" required><?= esc($library['contact_information'] ?? '') ?></textarea>
                            </div>
                        </div>

                        <button type="submit" name="update_library" class="btn btn-success btn-sm mt-4">
                            <i class="mdi mdi-content-save"></i> &nbsp; Update
                        </button>
                    </form>
                </div>

                <footer class="footer">
                    <div class="d-sm-flex justify-content-between">
                        <span class="text-muted text-sm-left d-block d-sm-inline-block">Copyright ©
                            <?= date('Y') . ' ' . COMPANY_FULL_NAME ?>. All rights reserved.</span>
                        <span class="float-none float-sm-right d-block mt-1 mt-sm-0 text-center">
                            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>

<?php echo 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 src="https://cdn.ckeditor.com/ckeditor5/39.0.1/classic/ckeditor.js"></script>
<script>
    const fields = ['description', 'vision', 'featured_databases', 'special_notes', 'contact_information'];
    const editors = {};

    // Sync Trumbowyg editors content back to textareas
    function syncEditors() {
        fields.forEach(id => {
            if (editors[id]) {
                document.getElementById(id).value = editors[id].trumbowyg('html');
            }
        });
    }

    // Form validation for empty editor content & HTML5 form validation
    function isValidForm() {
        for (let id of fields) {
            const content = editors[id]?.trumbowyg('html').trim() || '';
            if (!content || content === '<p></p>') {
                toast('danger', `${id.replace(/_/g, ' ')} is required`);
                editors[id].trumbowyg('focus');
                return false;
            }
        }
        const form = document.getElementById('library_edit_form');
        if (!form.checkValidity()) {
            form.reportValidity();
            return false;
        }
        return true;
    }

    $(document).ready(function () {
        // Initialize Trumbowyg editors for each field
        fields.forEach(id => {
            editors[id] = $(`#${id}`).trumbowyg({
                btns: [['viewHTML'], ['formatting'], 'bold', 'italic', 'underline', 'link'],
                autogrow: true,
                resetCss: true,
                semantic: false
            });
        });

        // Image preview handler
        $('#image').on('change', function () {
            const reader = new FileReader();
            reader.onload = e => $('#image_preview').attr('src', e.target.result).show();
            reader.readAsDataURL(this.files[0]);
        });

        // Form submit handler
        $('#library_edit_form').on('submit', function (e) {
            e.preventDefault();

            syncEditors();

            if (!isValidForm()) return;

            const formData = new FormData(this);
            formData.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');
            const jwtToken = localStorage.getItem('jwt_token');

            $.ajax({
                url: '<?= base_url('api/library/update-library') ?>',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'Authorization': 'Bearer ' + jwtToken
                },
                success: function (response) {
                    if (response.status) {
                        toast('success', response.message || 'Library updated successfully!');
                        window.location.href = '<?= base_url('backdesk/library/index') ?>';
                    } else {
                        toast('danger', response.message || 'Something went wrong.');
                    }
                },
                error: function (xhr) {
                    toast('danger', xhr.status + ': Server error.');
                }
            });
        });
    });
</script>
</body>
</html>
