<?php
require 'auth_check.php';
require '../config/db.php';

$post = null;
$msg = "";

// FETCH POST IF EDITING
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM posts WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $post = $stmt->fetch();
}

// SAVE POST
if (isset($_POST['save_post'])) {
    $title = trim($_POST['title']);
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title))); // Auto-slug
    $content = $_POST['content'];
    
    // Handle Image Upload
    $image_path = $post['image'] ?? '';
    if (!empty($_FILES['image']['name'])) {
        $target = "../assets/images/blog/" . time() . "_" . $_FILES['image']['name'];
        // Ensure folder exists
        if (!is_dir("../assets/images/blog/")) mkdir("../assets/images/blog/", 0777, true);
        
        if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
            $image_path = str_replace("../", "", $target); // Save relative path
        }
    }

    if ($post) {
        // UPDATE
        $stmt = $pdo->prepare("UPDATE posts SET title=?, content=?, image=? WHERE id=?");
        $stmt->execute([$title, $content, $image_path, $post['id']]);
        $msg = "Post updated!";
    } else {
        // INSERT
        $stmt = $pdo->prepare("INSERT INTO posts (title, slug, content, image) VALUES (?, ?, ?, ?)");
        $stmt->execute([$title, $slug, $content, $image_path]);
        $msg = "Post published!";
        // Fetch new ID to stay on edit page
        $post = ['id' => $pdo->lastInsertId(), 'title'=>$title, 'content'=>$content, 'image'=>$image_path];
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Write Post</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .editor-container { background: white; padding: 30px; border-radius: 8px; max-width: 800px; margin: 0 auto; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; font-weight: bold; margin-bottom: 5px; }
        .form-control { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        textarea { height: 300px; font-family: sans-serif; line-height: 1.5; }
    </style>
</head>
<body>

    sidebar
    <div class="content">
        
        <div class="editor-container">
            <h2><?php echo $post ? "Edit Post" : "New Article"; ?></h2>
            
            <?php if($msg): ?>
                <div style="background:#d4edda; color:#155724; padding:10px; border-radius:5px; margin-bottom:20px;">
                    <?php echo $msg; ?> <a href="blog.php">Back to List</a>
                </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data">
                
                <div class="form-group">
                    <label>Article Title</label>
                    <input type="text" name="title" class="form-control" required value="<?php echo htmlspecialchars($post['title'] ?? ''); ?>">
                </div>

                <div class="form-group">
                    <label>Cover Image</label>
                    <input type="file" name="image" class="form-control" accept="image/*">
                    <?php if(!empty($post['image'])): ?>
                        <img src="../<?php echo $post['image']; ?>" style="width: 100px; margin-top: 10px; border-radius: 4px;">
                    <?php endif; ?>
                </div>

                <div class="form-group">
                    <label>Content (HTML Allowed)</label>
                    <textarea name="content" class="form-control" required><?php echo htmlspecialchars($post['content'] ?? ''); ?></textarea>
                    <small style="color: #666;">Tip: Use &lt;h2&gt; for headings and &lt;p&gt; for paragraphs.</small>
                </div>

                <button type="submit" name="save_post" class="btn btn-primary" style="width: 100%; padding: 12px; font-size: 16px;">
                    <?php echo $post ? "Update Article" : "Publish Article"; ?>
                </button>

            </form>
        </div>

    </div>

</body>
</html>