<?php
$page_title = "افزودن مطلب وبلاگ";
require 'config/db.php';
require 'includes/header.php';
require 'includes/sidebar.php';
require 'check_admin.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $title   = $_POST['title'] ?? '';
    $content = $_POST['content'] ?? '';

    // آپلود عکس
    $image_path = null;

    if (!empty($_FILES['image']['name'])) {

        $upload_dir = 'uploads/blog/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $newname = 'blog_' . time() . '.' . $ext;
        $dest = $upload_dir . $newname;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $dest)) {
            $image_path = $dest;
        }
    }

    // ذخیره در دیتابیس (بدون slug)
    $stmt = $pdo->prepare("
        INSERT INTO blog_posts (title, content, image_path)
        VALUES (:title, :content, :image_path)
    ");

    $stmt->execute([
        ':title'      => $title,
        ':content'    => $content,
        ':image_path' => $image_path
    ]);

    echo "<p style='color:green; font-weight:bold;'>✔ مطلب وبلاگ با موفقیت ثبت شد.</p>";
}
?>

<h1>افزودن مطلب وبلاگ</h1>

<form action="" method="post" enctype="multipart/form-data">

    <label>عنوان:</label>
    <input type="text" name="title" required>

    <label>متن:</label>
    <textarea name="content" rows="6" required></textarea>

    <label>عکس مطلب:</label>
    <input type="file" name="image">

    <button type="submit">ثبت</button>

</form>

<?php
require 'includes/footer.php';
?>