<?php
session_start();
require_once '../db.php'; // include your db connection via PDO

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Fetch blog post
$stmt = $pdo->prepare("SELECT * FROM blogs WHERE id = ?");
$stmt->execute([$id]);
$blog = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$blog) {
    die("Blog post not found.");
}

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'];

    $image = $blog['image'];
    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("UPDATE blogs SET title = ?, slug = ?, content = ?, image = ?, category_id = ? WHERE id = ?");
    $stmt->execute([$title, $slug, $content, $image, $category_id, $id]);

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

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

<?php include 'menu.php'; ?>
<!DOCTYPE html>
<html>
<head><title>Edit Blog Post</title></head>
<body>
<h1>Edit Blog Post</h1>
<form method="post" enctype="multipart/form-data">
    <input type="text" name="title" value="<?= htmlspecialchars($blog['title']) ?>" required><br><br>
    <textarea name="content" rows="5" required><?= htmlspecialchars($blog['content']) ?></textarea><br><br>

    <select name="category_id" required>
        <option value="">-- Select Category --</option>
        <?php foreach ($categories as $cat): ?>
            <option value="<?= $cat['id'] ?>" <?= $cat['id'] == $blog['category_id'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($cat['name']) ?>
            </option>
        <?php endforeach; ?>
    </select><br><br>

    <?php if (!empty($blog['image'])): ?>
        <img src="../uploads/<?= htmlspecialchars($blog['image']) ?>" width="100"><br>
    <?php endif; ?>

    <input type="file" name="image"><br><br>
    <button type="submit">Update Blog</button>
</form>
</body>
</html>
