<?php echo 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" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap4.min.css" />

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

                        <!-- Hidden ID -->
                        <input type="hidden" name="id" value="<?= esc($post['id']) ?>">

                        <!-- Department & Type -->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Department</label>
                                    <select class="form-control" name="department_id" id="department_id" required>
                                        <option value="">Select</option>
                                        <?php foreach ($departments as $row): ?>
                                            <option value="<?= esc($row['id']) ?>" <?= $row['id'] == $post['department_id'] ? 'selected' : '' ?>>
                                                <?= esc($row['department_name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <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>
                                        <?php 
                                            $types = ['Research Projects', 'Recent Publications', 'Clinical Services', 'Community Programs', 'Recent Events'];
                                            foreach ($types as $type):
                                        ?>
                                            <option value="<?= $type ?>" <?= $type == $post['type'] ? 'selected' : '' ?>><?= $type ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Heading -->
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Heading</label>
                                    <input type="text" name="heading" id="heading" class="form-control" value="<?= esc($post['heading']) ?>" required>
                                </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($post['description']) ?></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Image -->
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Change Image (Optional)</label>
                                    <input type="file" name="image" id="image" class="form-control" accept="image/*">
                                    <?php if (!empty($post['image']) && file_exists(FCPATH . $post['image'])): ?>
                                        <p class="mt-2">Current: <a href="<?= base_url($post['image']) ?>" target="_blank">View Image</a></p>
                                    <?php endif; ?>
                                </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>
    $(document).ready(function () {
        // ✅ Initialize Trumbowyg on #description
        const $description = $('#description').trumbowyg({
            btns: [['viewHTML'], ['formatting'], 'bold', 'italic', 'underline', 'link'],
            autogrow: true,
            resetCss: true,
            semantic: false
        });

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

            // ✅ Sync Trumbowyg data to textarea
            const descriptionData = $description.trumbowyg('html').trim();
            $('textarea[name="description"]').val(descriptionData);

            if (!descriptionData || descriptionData === '<p></p>') {
                toast('danger', 'Description is required.');
                $description.trumbowyg('focus');
                return;
            }

            const csrfTokenName = '<?= csrf_token() ?>';
            const csrfTokenValue = '<?= csrf_hash() ?>';
            const jwtToken = localStorage.getItem('jwt_token');

            if (!jwtToken) {
                toast('danger', 'Unauthorized. Token missing.');
                return;
            }

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

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