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

<!-- External CSS -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap4.min.css"
      integrity="sha512-PT0RvABaDhDQugEbpNMwgYBCnGCiTZMh9yOzUsJHDgl/dMhD9yjHAwoumnUk3JydV3QTcIkNDuN40CJxik5+WQ=="
      crossorigin="anonymous" referrerpolicy="no-referrer" />

<!-- Styling -->
<style>
    select.form-control, .form-control {
        outline: 1px solid #67676b;
        border-radius: 5px;
        color: #67676b;
    }
    input[type="text"], input[type="number"], input[type="date"], input[type="email"], input[type="file"], select {
        padding: 5px 10px;
    }
    .error {
        color: red;
        text-align: right;
        width: 100%;
        padding-top: 15px;
        margin-bottom: 0 !important;
    }
</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">
                        <h4 class="card-title">Edit Library Collection</h4>
                        <hr>

                        <!-- Hidden ID -->
                        <input type="hidden" name="id" value="<?= $collection['id'] ?>">

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Type</label>
                                    <select class="form-control" name="type" id="type" required>
                                        <option value="">Select</option>
                                        <option value="Physical Books Collection" <?= $collection['type'] === 'Physical Books Collection' ? 'selected' : '' ?>>Physical Books Collection</option>
                                        <option value="Digital Resources" <?= $collection['type'] === 'Digital Resources' ? 'selected' : '' ?>>Digital Resources</option>
                                        <option value="Library Services" <?= $collection['type'] === 'Library Services' ? 'selected' : '' ?>>Library Services</option>
                                        <option value="Library Notices" <?= $collection['type'] === 'Library Notices' ? 'selected' : '' ?>>Library Notices</option>
                                        <option value="Digital Initiatives" <?= $collection['type'] === 'Digital Initiatives' ? 'selected' : '' ?>>Digital Initiatives</option>
                                        
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Description -->
                        <div class="row mt-3">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label class="font-weight-bold">Description</label>
                                    <textarea name="description" id="description" class="form-control" rows="6"><?= esc($collection['description']) ?></textarea>
                                </div>
                            </div>
                        </div>

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

                <!-- Footer -->
                <footer class="footer mt-4">
                    <div class="d-sm-flex justify-content-center justify-content-sm-between">
                        <span class="text-muted text-center 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>

<!-- Scripts -->
<?= 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>
    let descriptionEditor;

    $(document).ready(function () {
        // Initialize Trumbowyg editor
        $('#description').trumbowyg({
            btns: [['viewHTML'], ['formatting'], 'bold', 'italic', 'underline'],
            autogrow: true,
            resetCss: true,
            semantic: false
        });
        descriptionEditor = $('#description');

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

            // Get HTML content from Trumbowyg editor
            const descriptionData = descriptionEditor.trumbowyg('html');
            $('textarea[name="description"]').val(descriptionData);

            const jwtToken = localStorage.getItem('jwt_token');
            if (!jwtToken) {
                toast('danger', 'Unauthorized. Token missing.');
                return;
            }

            const formData = new FormData(this);
            const csrfTokenName = '<?= csrf_token() ?>';
            const csrfTokenValue = '<?= csrf_hash() ?>';
            formData.append(csrfTokenName, csrfTokenValue);

            $.ajax({
                url: '<?= base_url("api/library/update-collection") ?>',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'Authorization': 'Bearer ' + jwtToken
                },
                success: function (response) {
                    if (response.status) {
                        toast('success', response.message || 'Updated successfully!');
                        window.location.href = '<?= base_url("backdesk/library/collection") ?>';
                    } else {
                        toast('danger', response.message || 'Update failed.');
                    }
                },
                error: function (xhr) {
                    toast('danger', 'Server error: ' + xhr.statusText);
                }
            });
        });
    });
</script>

</body>
</html>
