<?php
session_start();
include(__DIR__ . '/../config/db.php'); // ตรวจสอบว่าไฟล์อยู่ public/article.php

// รับ ID ข่าวจาก GET
$id = $_GET['id'] ?? 0;
$id = intval($id);

// ดึงข่าวตาม ID (published เท่านั้น) ด้วย prepared statement
$stmt = $conn->prepare("
    SELECT a.*, c.name AS category_name 
    FROM articles a 
    JOIN categories c ON a.category_id = c.id 
    WHERE a.id = ? AND a.status = 'published'
");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$article = $result->fetch_assoc();
$stmt->close();

if (!$article) {
    // ข่าวไม่พบ → redirect กลับหน้าหลัก
    header("Location: index.php");
    exit;
}

// ดึง comment ของข่าวนี้ด้วย prepared statement
$stmt_c = $conn->prepare("
    SELECT * FROM comments 
    WHERE article_id = ? AND is_approved = 1 
    ORDER BY created_at DESC
");
$stmt_c->bind_param("i", $article['id']);
$stmt_c->execute();
$comments = $stmt_c->get_result();
$stmt_c->close();
?>

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title><?php echo htmlspecialchars($article['title']); ?></title>
</head>
<body>
    <h1><?php echo htmlspecialchars($article['title']); ?></h1>
    <p>
        <strong>หมวด:</strong> <?php echo htmlspecialchars($article['category_name']); ?> | 
        <strong>วันที่:</strong> <?php echo $article['created_at']; ?>
    </p>
    <hr>
    <p><?php echo nl2br(htmlspecialchars($article['content'])); ?></p>

    <h3>ความคิดเห็น</h3>
    <?php if($comments->num_rows > 0): ?>
        <?php while($c = $comments->fetch_assoc()): ?>
            <p>
                <strong><?php echo htmlspecialchars($c['author_name']); ?>:</strong> 
                <?php echo nl2br(htmlspecialchars($c['comment'])); ?><br>
                <small><?php echo $c['created_at']; ?></small>
            </p>
        <?php endwhile; ?>
    <?php else: ?>
        <p>ยังไม่มีความคิดเห็น</p>
    <?php endif; ?>

    <h3>แสดงความคิดเห็น</h3>
    <form method="post" action="comments.php">
        <input type="hidden" name="article_id" value="<?php echo $article['id']; ?>">
        <label>ชื่อ:</label><br>
        <input type="text" name="author_name" required><br><br>

        <label>ความคิดเห็น:</label><br>
        <textarea name="comment" rows="5" cols="70" required></textarea><br><br>

        <button type="submit">ส่งความคิดเห็น</button>
    </form>

    <br><a href="index.php">กลับสู่หน้าหลัก</a>
</body>
</html>
