<?php
session_start();
include '../db.php'; // adjust the path if needed

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = $_POST['title'];
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));
    $content = $_POST['content'];
    $category_id = $_POST['category_id'];

    // handle image upload
    $image = null;
    if (!empty($_FILES['image']['name'])) {
        $target = "../uploads/" . basename($_FILES['image']['name']);
        if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
            $image = $_FILES['image']['name'];
        }
    }

    $stmt = $pdo->prepare("INSERT INTO blogs (title, slug, content, image, category_id) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$title, $slug, $content, $image, $category_id]);

    header("Location: blog_list.php");
    exit;
}

// fetch categories
$categories = $pdo->query("SELECT * FROM categories")->fetchAll(PDO::FETCH_ASSOC);
?>

<?php include 'menu.php'; ?>
<!DOCTYPE html>
<html>
<head><title>Add Blog Post</title></head>
<body>
<h1>Add Blog Post</h1>
<form method="post" enctype="multipart/form-data">
    <input type="text" name="title" placeholder="Title" required><br><br>
    <textarea name="content" placeholder="Content" rows="5" required></textarea><br><br>
    <select name="category_id">
        <option value="">-- Select Category --</option>
        <?php foreach($categories as $cat): ?>
            <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
        <?php endforeach; ?>
    </select><br><br>
    <input type="file" name="image"><br><br>
    <button type="submit">Add Blog</button>
</form>
</body>
</html>

