<?php
require '../includes/config.php';

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: index.php');
    exit;
}
$post_id = (int)$_GET['id'];

// Fetch post
$query = "SELECT title, content, tags, created_at FROM blog_posts WHERE post_id = ? AND status = 'published'";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $post_id);
$stmt->execute();
$post = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$post) {
    header('Location: index.php');
    exit;
}

// Handle comment submission
$errors = [];
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $commenter_name = trim($_POST['commenter_name'] ?? '');
    $comment_text = trim($_POST['comment_text'] ?? '');

    if (empty($commenter_name) || empty($comment_text)) {
        $errors[] = 'Name and comment are required.';
    } else {
        $query = "INSERT INTO blog_comments (post_id, commenter_name, comment_text) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($query);
        $stmt->bind_param('iss', $post_id, $commenter_name, $comment_text);
        if ($stmt->execute()) {
            $success = 'Comment posted successfully.';
        } else {
            $errors[] = 'Failed to post comment: ' . $stmt->error;
        }
        $stmt->close();
    }
}

// Fetch comments
$query = "SELECT commenter_name, comment_text, created_at FROM blog_comments WHERE post_id = ? ORDER BY created_at DESC";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $post_id);
$stmt->execute();
$comments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($post['title']); ?> - WebsiteUnder999</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="style.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h1 class="my-4"><?php echo htmlspecialchars($post['title']); ?></h1>
        <p><small class="text-muted">Posted on <?php echo htmlspecialchars($post['created_at']); ?></small></p>
        <?php if (!empty($post['tags'])): ?>
            <p>
                Tags:
                <?php foreach (array_map('trim', explode(',', $post['tags'])) as $t): ?>
                    <a href="index.php?tag=<?php echo urlencode($t); ?>" class="badge bg-secondary"><?php echo htmlspecialchars($t); ?></a>
                <?php endforeach; ?>
            </p>
        <?php endif; ?>
        <div class="card mb-4">
            <div class="card-body">
                <p><?php echo nl2br(htmlspecialchars($post['content'])); ?></p>
            </div>
        </div>

        <!-- Comments -->
        <h3>Comments</h3>
        <?php if ($errors): ?>
            <div class="alert alert-danger">
                <?php foreach ($errors as $error): ?>
                    <p><?php echo htmlspecialchars($error); ?></p>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?php if (empty($comments)): ?>
            <p>No comments yet.</p>
        <?php else: ?>
            <?php foreach ($comments as $comment): ?>
                <div class="card mb-2">
                    <div class="card-body">
                        <p><strong><?php echo htmlspecialchars($comment['commenter_name']); ?></strong> <small class="text-muted"><?php echo htmlspecialchars($comment['created_at']); ?></small></p>
                        <p><?php echo nl2br(htmlspecialchars($comment['comment_text'])); ?></p>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>

        <!-- Comment Form -->
        <h4>Leave a Comment</h4>
        <form method="POST" action="">
            <div class="mb-3">
                <label for="commenter_name" class="form-label">Name</label>
                <input type="text" name="commenter_name" id="commenter_name" class="form-control" required>
            </div>
            <div class="mb-3">
                <label for="comment_text" class="form-label">Comment</label>
                <textarea name="comment_text" id="comment_text" class="form-control" rows="5" required></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Submit Comment</button>
        </form>
        <a href="index.php" class="btn btn-secondary mt-3">Back to Blog</a>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<?php
$conn->close();
?>