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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title     = trim($_POST['title'] ?? '');
    $slug_raw  = 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'] ?? date('Y-m-d H:i:s');
    $image     = handleUpload('featured_image', 'blog') ?? trim($_POST['image_url'] ?? '');

    // Ensure unique slug
    $slug = $slug_raw;
    $i = 1;
    while (db()->query("SELECT id FROM blog_posts WHERE slug='".db()->real_escape_string($slug)."'")->num_rows > 0) {
        $slug = $slug_raw . '-' . $i++;
    }

    $st = db()->prepare("INSERT INTO blog_posts (title,slug,category,excerpt,content,featured_image,author,status,published_at,created_by) VALUES (?,?,?,?,?,?,?,?,?,?)");
    $uid = (int)$admin['id'];
    $st->bind_param('sssssssssi', $title,$slug,$category,$excerpt,$content,$image,$author,$status,$pub_date,$uid);
    
    if ($st->execute()) {
        flash('Blog post created successfully!', 'success');
        redirect(ADMIN_URL . '/pages/blog.php');
    } else {
        flash('Error creating post: ' . db()->error, 'error');
    }
}
?>

<div class="page-header">
    <h1>Add Blog Post</h1>
    <div class="page-header-actions">
        <a href="blog.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
    </div>
</div>

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

    <!-- Main -->
    <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" placeholder="Enter blog post title..." required
                        oninput="this.form.slug.value = this.value.toLowerCase().replace(/[^a-z0-9\s-]/g,'').replace(/[\s]+/g,'-').replace(/^-+|-+$/g,'')">
                </div>
                <div class="form-group">
                    <label class="form-label">Slug</label>
                    <input type="text" name="slug" class="form-control" placeholder="auto-generated-from-title">
                    <div class="form-hint">URL-friendly version of the title. Leave blank to auto-generate.</div>
                </div>
                <div class="form-group">
                    <label class="form-label">Excerpt</label>
                    <textarea name="excerpt" class="form-control" rows="3" placeholder="Short description shown in blog listing..."></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">Content</label>
                    <div id="editor"></div>
                    <input type="hidden" name="content" id="content-input">
                </div>
            </div>
        </div>
    </div>

    <!-- Sidebar -->
    <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">Draft</option>
                        <option value="published">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') ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">Author</label>
                    <input type="text" name="author" class="form-control" value="CY Consultancy">
                </div>
                <button type="submit" class="btn btn-primary" style="width:100%"><i class="fas fa-save"></i> Save 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">
                <div class="form-group" style="margin:0">
                    <select name="category" class="form-select">
                        <option value="">Select Category</option>
                        <option value="Study Tips">Study Tips</option>
                        <option value="Visa Guide">Visa Guide</option>
                        <option value="Education News">Education News</option>
                        <option value="Destination Guide">Destination Guide</option>
                        <option value="Scholarship">Scholarship</option>
                        <option value="Announcements">Announcements</option>
                    </select>
                </div>
            </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">
                <div class="form-group">
                    <label class="form-label">Upload Image</label>
                    <input type="file" name="featured_image" class="form-control" accept="image/*" onchange="previewImage(this)">
                </div>
                <img id="img-preview" src="" alt="" class="img-preview" style="display:none;width:100%;height:120px">
                <div class="form-group" style="margin-top:10px">
                    <label class="form-label">Or Image URL</label>
                    <input type="text" name="image_url" class="form-control" placeholder="https://...">
                </div>
            </div>
        </div>
    </div>
</div>
</form>

<!-- Quill Editor -->
<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;
});

function previewImage(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var prev = document.getElementById('img-preview');
            prev.src = e.target.result;
            prev.style.display = 'block';
        };
        reader.readAsDataURL(input.files[0]);
    }
}
</script>

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