<?php
include("../config/db.php");
if(!isset($_SESSION['user_id'])) header("Location: login.php");
$id = intval($_GET['id']);
$article = $conn->query("SELECT a.*, c.name AS category, u.name AS author 
                         FROM articles a
                         JOIN categories c ON a.category_id=c.id
                         JOIN users u ON a.user_id=u.id
                         WHERE a.id=$id")->fetch_assoc();
$comments = $conn->query("SELECT comments.*, users.name AS username 
                          FROM comments 
                          LEFT JOIN users ON comments.user_id=users.id 
                          WHERE article_id=$id ORDER BY created_at DESC");
?>
<!DOCTYPE html>
<html lang="th">
<head><meta charset="UTF-8"><title><?= htmlspecialchars($article['title']) ?></title></head>
<body>
    <h1><?= htmlspecialchars($article['title']) ?></h1>
    <p><b>หมวดหมู่:</b> <?= $article['category'] ?> | <b>ผู้เขียน:</b> <?= $article['author'] ?></p>
    <p><?= nl2br(htmlspecialchars($article['content'])) ?></p>

    <h3>แสดงความคิดเห็น</h3>
    <form method="post" action="comment.php">
        <input type="hidden" name="article_id" value="<?= $article['id'] ?>">
        <textarea name="comment" placeholder="แสดงความคิดเห็น"></textarea><br>
        <button type="submit">ส่ง</button>
    </form>

    <h3>ความคิดเห็น</h3>
    <?php while($c=$comments->fetch_assoc()): ?>
        <p><b><?= $c['username']??$c['guest_name'] ?>:</b> <?= htmlspecialchars($c['content']) ?></p>
    <?php endwhile; ?>
</body>
</html>
