<?php
session_start();
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'teacher')) {
    header("Location: ../login.php");
    exit();
}

include(__DIR__ . '/../config/db.php');

$id = intval($_GET['id'] ?? 0);
if($id <= 0){
    die("ไม่พบข่าวนี้");
}

// ดึงข่าว
$article = $conn->query("SELECT * FROM articles WHERE id=$id")->fetch_assoc();
if(!$article){
    die("ไม่พบข่าวนี้");
}

// ดึงหมวดข่าว
$categories = $conn->query("SELECT * FROM categories ORDER BY name ASC");

// ฟังก์ชันสร้าง slug ไม่ซ้ำ
function generateSlug($title, $conn, $id){
    $slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', trim($title)));
    $slug = trim($slug, '-');
    $baseSlug = $slug;
    $i = 1;
    while(true){
        $stmt = $conn->prepare("SELECT id FROM articles WHERE slug=? AND id<>?");
        $stmt->bind_param("si", $slug, $id);
        $stmt->execute();
        $result = $stmt->get_result();
        if($result->num_rows == 0) break;
        $slug = $baseSlug . '-' . $i;
        $i++;
    }
    return $slug;
}

// บันทึกข่าว
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $title = $_POST['title'];
    $content = $_POST['content'];
    $category_id = intval($_POST['category_id']);
    $status = $_POST['status'];
    $slug = generateSlug($title, $conn, $id);

    $stmt = $conn->prepare("UPDATE articles SET title=?, slug=?, content=?, category_id=?, status=? WHERE id=?");
    $stmt->bind_param("sssisi", $title, $slug, $content, $category_id, $status, $id);

    if($stmt->execute()){
        header("Location: manage_articles.php");
        exit();
    } else {
        $error = "บันทึกไม่สำเร็จ: ".$stmt->error;
    }
    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title>แก้ไขข่าว</title>
</head>
<body>
<h2>แก้ไขข่าว</h2>
<a href="manage_articles.php">กลับหน้าจัดการข่าว</a><br><br>
<?php if(isset($error)) echo "<p style='color:red;'>$error</p>"; ?>
<form method="post">
    <label>หัวข้อข่าว:</label><br>
    <input type="text" name="title" value="<?php echo htmlspecialchars($article['title']); ?>" required><br><br>

    <label>หมวดข่าว:</label><br>
    <select name="category_id" required>
        <?php while($row = $categories->fetch_assoc()): ?>
            <option value="<?php echo $row['id']; ?>" <?php if($row['id']==$article['category_id']) echo "selected"; ?>>
                <?php echo htmlspecialchars($row['name']); ?>
            </option>
        <?php endwhile; ?>
    </select><br><br>

    <label>เนื้อหาข่าว:</label><br>
    <textarea name="content" rows="10" cols="70" required><?php echo htmlspecialchars($article['content']); ?></textarea><br><br>

    <label>สถานะ:</label><br>
    <select name="status">
        <option value="draft" <?php if($article['status']=='draft') echo 'selected'; ?>>Draft</option>
        <option value="published" <?php if($article['status']=='published') echo 'selected'; ?>>Published</option>
    </select><br><br>

    <button type="submit">บันทึกการแก้ไข</button>
</form>
</body>
</html>
