<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';

// 2. DETERMINE MODE (CREATE VS EDIT) & FETCH DATA
$edit_mode = false;
$page_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$page = [
    'id' => null,
    'title' => '',
    'slug' => '',
    'content' => '',
    'is_published' => 0
];

if ($page_id) {
    $edit_mode = true;
    $stmt = $conn->prepare("SELECT * FROM pages WHERE id = ?");
    $stmt->bind_param("i", $page_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $page = $result->fetch_assoc();
    $stmt->close();
    if (!$page) {
        $_SESSION['error_message'] = "Page not found.";
        header("Location: manage-pages.php");
        exit();
    }
}

// 3. HANDLE FORM SUBMISSION
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $slug = $_POST['slug'] ?? '';
    $content = $_POST['content'] ?? '';
    $is_published = isset($_POST['is_published']) ? 1 : 0;

    // A simple function to create a URL-friendly slug
    if (empty($slug)) {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));
    }

    if ($edit_mode) {
        // UPDATE existing page
        $stmt = $conn->prepare("UPDATE pages SET title = ?, slug = ?, content = ?, is_published = ? WHERE id = ?");
        $stmt->bind_param("sssii", $title, $slug, $content, $is_published, $page_id);
        $_SESSION['success_message'] = "Page updated successfully.";
    } else {
        // INSERT new page
        $stmt = $conn->prepare("INSERT INTO pages (title, slug, content, is_published) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("sssi", $title, $slug, $content, $is_published);
        $_SESSION['success_message'] = "Page created successfully.";
    }
    
    $stmt->execute();
    $stmt->close();
    
    header("Location: manage-pages.php");
    exit();
}


$page_title = $edit_mode ? 'Edit Page' : 'Add New Page';
$current_page = 'manage-pages.php';
$active_category = 'contentMenu';

// 4. INCLUDE THE HTML HEADER
include 'admin-header.php';

// Fetch TinyMCE API key from settings
$tinymce_api_key = $settings['tinymce_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: 'textarea#content-editor',
        plugins: 'preview importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount help charmap quickbars emoticons',
        menubar: 'file edit view insert format tools table help',
        toolbar: 'undo redo | bold italic underline strikethrough | fontfamily fontsize blocks | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist | forecolor backcolor removeformat | pagebreak | charmap emoticons | fullscreen  preview | image media link anchor codesample | ltr rtl',
        height: 500,
        skin: (document.documentElement.getAttribute('data-bs-theme') === 'dark') ? 'oxide-dark' : 'oxide',
        content_css: (document.documentElement.getAttribute('data-bs-theme') === 'dark') ? 'dark' : 'default'
    });
</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"><i class="bi bi-file-earmark-plus-fill me-2"></i><?php echo $page_title; ?></h1>
</div>

<form method="POST">
    <div class="row">
        <div class="col-lg-9">
            <div class="card shadow-sm">
                <div class="card-body">
                    <div class="mb-3">
                        <label for="title" class="form-label fs-5">Page Title</label>
                        <input type="text" class="form-control form-control-lg" id="title" name="title" value="<?php echo htmlspecialchars($page['title']); ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="content-editor" class="form-label">Content</label>
                        <textarea id="content-editor" name="content"><?php echo htmlspecialchars($page['content']); ?></textarea>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3">
            <div class="card shadow-sm mb-3">
                <div class="card-header"><strong>Publish</strong></div>
                <div class="card-body">
                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" role="switch" id="is_published" name="is_published" value="1" <?php if($page['is_published']) echo 'checked'; ?>>
                        <label class="form-check-label" for="is_published">Publish Page</label>
                    </div>
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle-fill me-1"></i> Save Page</button>
                        <a href="manage-pages.php" class="btn btn-outline-secondary">Cancel</a>
                    </div>
                </div>
            </div>
            <div class="card shadow-sm">
                <div class="card-header"><strong>Page Attributes</strong></div>
                <div class="card-body">
                    <label for="slug" class="form-label">Slug (URL)</label>
                    <input type="text" class="form-control" id="slug" name="slug" value="<?php echo htmlspecialchars($page['slug']); ?>">
                    <small class="text-muted">The unique, URL-friendly name. Auto-generated from title if left blank.</small>
                </div>
            </div>
        </div>
    </div>
</form>

<script>
    // Live Slug Generation Script
    document.addEventListener('DOMContentLoaded', function() {
        const titleInput = document.getElementById('title');
        const slugInput = document.getElementById('slug');

        const slugify = (text) => {
            return text.toString().toLowerCase().trim()
                .replace(/\s+/g, '-')           // Replace spaces with -
                .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
                .replace(/\-\-+/g, '-')         // Replace multiple - with single -
                .replace(/^-+/, '')             // Trim - from start of text
                .replace(/-+$/, '');            // Trim - from end of text
        };

        titleInput.addEventListener('keyup', function() {
            slugInput.value = slugify(titleInput.value);
        });
    });
</script>

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