<?php
$pageTitle = 'Edit Blog Post';
require_once dirname(__DIR__) . '/includes/header.php';

$id = (int)($_GET['id'] ?? 0);
if (!$id) { redirect(ADMIN_URL . '/pages/blog.php'); }

$post = db()->query("SELECT * FROM blog_posts WHERE id=$id")->fetch_assoc();
if (!$post) { flash('Post not found.','error'); redirect(ADMIN_URL.'/pages/blog.php'); }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title    = trim($_POST['title'] ?? '');
    $slug     = trim($_POST['slug'] ?? '') ?: slug($title);
    $category = trim($_POST['category'] ?? '');
    $excerpt  = trim($_POST['excerpt'] ?? '');
    $content  = $_POST['content'] ?? '';
    $author   = trim($_POST['author'] ?? 'CY Consultancy');
    $status   = $_POST['status'] ?? 'draft';
    $pub_date = $_POST['published_at'] ?? $post['published_at'];
    $image    = handleUpload('featured_image', 'blog') ?? trim($_POST['image_url'] ?? $post['featured_image']);

    $st = db()->prepare("UPDATE blog_posts SET title=?,slug=?,category=?,excerpt=?,content=?,featured_image=?,author=?,status=?,published_at=? WHERE id=?");
    $st->bind_param('sssssssssi', $title,$slug,$category,$excerpt,$content,$image,$author,$status,$pub_date,$id);

    if ($st->execute()) {
        flash('Post updated successfully!', 'success');
        redirect(ADMIN_URL . '/pages/blog-edit.php?id=' . $id);
    } else {
        flash('Error: ' . db()->error, 'error');
    }
}
?>

<div class="page-header">
    <h1>Edit Blog Post</h1>
    <div class="page-header-actions" style="display:flex;gap:8px">
        <a href="blog.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
        <button onclick="confirmDelete('blog.php?delete=<?= $id ?>','<?= e(addslashes($post['title'])) ?>')" class="btn btn-danger"><i class="fas fa-trash"></i> Delete</button>
    </div>
</div>

<form method="POST" enctype="multipart/form-data">
<div style="display:grid;grid-template-columns:1fr 320px;gap:20px;align-items:start">

    <div style="display:flex;flex-direction:column;gap:20px">
        <div class="card">
            <div class="card-header"><i class="fas fa-edit" style="color:var(--brand)"></i><h2>Post Content</h2></div>
            <div class="card-body">
                <div class="form-group">
                    <label class="form-label">Title *</label>
                    <input type="text" name="title" class="form-control" value="<?= e($post['title']) ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Slug</label>
                    <input type="text" name="slug" class="form-control" value="<?= e($post['slug']) ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">Excerpt</label>
                    <textarea name="excerpt" class="form-control" rows="3"><?= e($post['excerpt']) ?></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">Content</label>
                    <div id="editor"><?= $post['content'] ?></div>
                    <input type="hidden" name="content" id="content-input">
                </div>
            </div>
        </div>
    </div>

    <div style="display:flex;flex-direction:column;gap:16px">
        <div class="card">
            <div class="card-header"><i class="fas fa-cog" style="color:var(--muted)"></i><h2>Publish</h2></div>
            <div class="card-body">
                <div class="form-group">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <option value="draft" <?= $post['status']==='draft'?'selected':'' ?>>Draft</option>
                        <option value="published" <?= $post['status']==='published'?'selected':'' ?>>Published</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Publish Date</label>
                    <input type="datetime-local" name="published_at" class="form-control" value="<?= date('Y-m-d\TH:i', strtotime($post['published_at'] ?: $post['created_at'])) ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">Author</label>
                    <input type="text" name="author" class="form-control" value="<?= e($post['author']) ?>">
                </div>
                <button type="submit" class="btn btn-primary" style="width:100%"><i class="fas fa-save"></i> Update Post</button>
            </div>
        </div>
        <div class="card">
            <div class="card-header"><i class="fas fa-tag" style="color:var(--muted)"></i><h2>Category</h2></div>
            <div class="card-body">
                <select name="category" class="form-select">
                    <?php foreach(['','Study Tips','Visa Guide','Education News','Destination Guide','Scholarship','Announcements'] as $cat): ?>
                    <option value="<?= e($cat) ?>" <?= $post['category']===$cat?'selected':'' ?>><?= $cat ?: 'Select Category' ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <div class="card">
            <div class="card-header"><i class="fas fa-image" style="color:var(--muted)"></i><h2>Featured Image</h2></div>
            <div class="card-body">
                <?php if ($post['featured_image']): ?>
                <img src="<?= e(SITE_URL.'/'.$post['featured_image']) ?>" style="width:100%;height:120px;object-fit:cover;border-radius:8px;margin-bottom:10px">
                <?php endif; ?>
                <div class="form-group">
                    <label class="form-label">Upload New Image</label>
                    <input type="file" name="featured_image" class="form-control" accept="image/*">
                </div>
                <div class="form-group">
                    <label class="form-label">Or Image URL</label>
                    <input type="text" name="image_url" class="form-control" value="<?= e($post['featured_image']) ?>">
                </div>
            </div>
        </div>
    </div>
</div>
</form>

<link href="https://cdn.quilljs.com/1.3.7/quill.snow.css" rel="stylesheet">
<script src="https://cdn.quilljs.com/1.3.7/quill.min.js"></script>
<script>
var quill = new Quill('#editor', {
    theme: 'snow',
    modules: { toolbar: [
        [{ header: [1,2,3,false] }],
        ['bold','italic','underline','strike'],
        [{ list: 'ordered'},{ list: 'bullet'}],
        ['link','image','blockquote','code-block'],
        [{ color: [] },{ background: [] }],
        ['clean']
    ]}
});
document.querySelector('form').addEventListener('submit', function() {
    document.getElementById('content-input').value = quill.root.innerHTML;
});
</script>

<?php require_once dirname(__DIR__) . '/includes/footer.php'; ?>
