<?php
include 'admin-header.php';

$message = '';
// --- ACTION HANDLING ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['comment_id'])) {
    $comment_id = intval($_POST['comment_id']);

    if (isset($_POST['approve'])) {
        $stmt = $conn->prepare("UPDATE comments SET is_approved = 1 WHERE id = ?");
        $stmt->bind_param("i", $comment_id);
        $stmt->execute();
        $message = '<div class="alert alert-success">Comment approved and is now live.</div>';
    } elseif (isset($_POST['unapprove'])) {
        $stmt = $conn->prepare("UPDATE comments SET is_approved = 0 WHERE id = ?");
        $stmt->bind_param("i", $comment_id);
        $stmt->execute();
        $message = '<div class="alert alert-warning">Comment has been hidden.</div>';
    } elseif (isset($_POST['delete'])) {
        $stmt = $conn->prepare("DELETE FROM comments WHERE id = ?");
        $stmt->bind_param("i", $comment_id);
        $stmt->execute();
        $message = '<div class="alert alert-danger">Comment has been permanently deleted.</div>';
    }
}

// --- DATA FETCHING ---
$view = $_GET['view'] ?? 'pending'; // Default view is pending comments
$where_clause = "WHERE c.is_approved = 0";
if ($view === 'approved') { $where_clause = "WHERE c.is_approved = 1"; } 
elseif ($view === 'all') { $where_clause = ""; }

$sql = "SELECT c.*, u.full_name, a.title as article_title 
        FROM comments c 
        JOIN users u ON c.user_id = u.id 
        JOIN articles a ON c.article_id = a.id 
        $where_clause 
        ORDER BY c.created_at DESC";
$comments_result = $conn->query($sql);

// Counts for badges
$pending_count = $conn->query("SELECT COUNT(*) as total FROM comments WHERE is_approved = 0")->fetch_assoc()['total'];
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Manage Comments</h1>
</div>
<?php echo $message; ?>

<ul class="nav nav-tabs mb-3">
    <li class="nav-item">
        <a class="nav-link <?php if($view == 'pending') echo 'active'; ?>" href="?view=pending">
            Pending Approval <span class="badge bg-danger rounded-pill"><?php echo $pending_count; ?></span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php if($view == 'approved') echo 'active'; ?>" href="?view=approved">Approved</a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php if($view == 'all') echo 'active'; ?>" href="?view=all">All Comments</a>
    </li>
</ul>

<div class="card shadow-sm">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-dark"><tr><th>Author</th><th>Comment</th><th>In Response To</th><th>Submitted</th><th class="text-center">Actions</th></tr></thead>
                <tbody>
                    <?php if ($comments_result && $comments_result->num_rows > 0): ?>
                        <?php while($comment = $comments_result->fetch_assoc()): ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($comment['full_name']); ?></strong></td>
                            <td><em>"<?php echo htmlspecialchars(substr($comment['comment_text'], 0, 100)); ?>..."</em></td>
                            <td><a href="../article-details.php?id=<?php echo $comment['article_id']; ?>" target="_blank"><?php echo htmlspecialchars($comment['article_title']); ?></a></td>
                            <td><?php echo date('M d, Y H:i', strtotime($comment['created_at'])); ?></td>
                            <td class="text-center">
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="comment_id" value="<?php echo $comment['id']; ?>">
                                    <?php if($comment['is_approved'] == 0): ?>
                                        <button type="submit" name="approve" class="btn btn-sm btn-success">Approve</button>
                                    <?php else: ?>
                                        <button type="submit" name="unapprove" class="btn btn-sm btn-warning">Unapprove</button>
                                    <?php endif; ?>
                                    <button type="submit" name="delete" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to permanently delete this comment?');">Delete</button>
                                </form>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="5" class="text-center text-muted p-4">No comments found in this view.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php include 'admin-footer.php'; ?>
