<?php
include 'admin-header.php';

$message = '';
// Handle form submission to save page content
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_pages'])) {
    $terms_content = $_POST['terms_content'];
    $privacy_content = $_POST['privacy_content'];

    $stmt_terms = $conn->prepare("UPDATE site_settings SET setting_value = ? WHERE setting_name = 'page_content_terms'");
    $stmt_terms->bind_param("s", $terms_content);
    $stmt_terms->execute();

    $stmt_privacy = $conn->prepare("UPDATE site_settings SET setting_value = ? WHERE setting_name = 'page_content_privacy'");
    $stmt_privacy->bind_param("s", $privacy_content);
    $stmt_privacy->execute();

    $message = '<div class="alert alert-success">Page content has been updated successfully.</div>';
}

// Fetch current page content
$terms_content = $site_settings['page_content_terms'] ?? '';
$privacy_content = $site_settings['page_content_privacy'] ?? '';
$tinymce_api_key = $site_settings['tinymce_api_key'] ?? 'no-api-key';
?>
<script src="https://cdn.tiny.cloud/1/<?php echo htmlspecialchars($tinymce_api_key); ?>/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
  tinymce.init({ selector: '.wysiwyg-editor', height: 500, plugins: 'code lists link table', toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright | bullist numlist | code | table | link' });
</script>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Static Page Editor</h1>
</div>
<?php echo $message; ?>

<form method="POST">
    <div class="card shadow-sm">
        <div class="card-body">
            <ul class="nav nav-tabs" id="pageTabs" role="tablist">
                <li class="nav-item" role="presentation"><button class="nav-link active" id="terms-tab" data-bs-toggle="tab" data-bs-target="#terms-panel" type="button">Terms & Conditions</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" id="privacy-tab" data-bs-toggle="tab" data-bs-target="#privacy-panel" type="button">Privacy Policy</button></li>
            </ul>
            <div class="tab-content pt-3">
                <div class="tab-pane fade show active" id="terms-panel" role="tabpanel">
                    <textarea name="terms_content" class="wysiwyg-editor"><?php echo htmlspecialchars($terms_content); ?></textarea>
                </div>
                <div class="tab-pane fade" id="privacy-panel" role="tabpanel">
                    <textarea name="privacy_content" class="wysiwyg-editor"><?php echo htmlspecialchars($privacy_content); ?></textarea>
                </div>
            </div>
        </div>
        <div class="card-footer text-end">
            <button type="submit" name="save_pages" class="btn btn-primary">Save All Changes</button>
        </div>
    </div>
</form>

<?php include 'admin-footer.php'; ?>
