<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';


// --- Page-Specific Logic Starts Here ---

// 2. HANDLE FORM SUBMISSIONS (BULK ACTIONS, DELETE)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    // --- HANDLE BULK ACTIONS ---
    if ($action === 'bulk_update' && isset($_POST['comment_ids']) && is_array($_POST['comment_ids'])) {
        $bulk_action = $_POST['bulk_action'];
        $comment_ids = array_map('intval', $_POST['comment_ids']);
        
        if (!empty($comment_ids)) {
            $ids_placeholder = implode(',', array_fill(0, count($comment_ids), '?'));
            $types = str_repeat('i', count($comment_ids));
            
            if ($bulk_action === 'delete') {
                $stmt = $conn->prepare("DELETE FROM comments WHERE id IN ($ids_placeholder)");
                $stmt->bind_param($types, ...$comment_ids);
                $_SESSION['success_message'] = "Selected comments deleted successfully.";
            } elseif (in_array($bulk_action, ['approved', 'pending', 'spam'])) {
                $stmt = $conn->prepare("UPDATE comments SET status = ? WHERE id IN ($ids_placeholder)");
                $types = 's' . $types;
                $params = array_merge([$bulk_action], $comment_ids);
                $stmt->bind_param($types, ...$params);
                $_SESSION['success_message'] = "Selected comments updated to '" . ucfirst($bulk_action) . "'.";
            }
            
            if (isset($stmt) && !$stmt->execute()) {
                $_SESSION['error_message'] = "An error occurred during the bulk action.";
            }
            if (isset($stmt)) $stmt->close();
        }
    }
    
    header("Location: manage-comments.php");
    exit();
}

// 3. FETCH COMMENTS FOR DISPLAY
$records_per_page = 20;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

$where_clauses = []; $params = []; $types = '';

// Search by content or author
$search_term = $_GET['search'] ?? '';
if (!empty($search_term)) {
    $where_clauses[] = "(c.comment_text LIKE ? OR u.full_name LIKE ?)";
    $like_term = "%{$search_term}%";
    array_push($params, $like_term, $like_term);
    $types .= 'ss';
}

// Filter by status
$status_filter = $_GET['status'] ?? '';
if (in_array($status_filter, ['approved', 'pending', 'spam'])) {
    $where_clauses[] = "c.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

$where_sql = count($where_clauses) > 0 ? "WHERE " . implode(' AND ', $where_clauses) : '';

// Count for pagination
$count_sql = "SELECT COUNT(c.id) as total FROM comments c JOIN users u ON c.user_id = u.id $where_sql";
$stmt_count = $conn->prepare($count_sql);
if (count($params) > 0) { $stmt_count->bind_param($types, ...$params); }
$stmt_count->execute();
$total_records = $stmt_count->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);
$stmt_count->close();

// Fetch comments for display
$fetch_sql = "SELECT c.id, c.comment_text, c.created_at, c.status, c.article_id,
              u.full_name as author_name, 
              a.title as article_title
              FROM comments c 
              JOIN users u ON c.user_id = u.id
              LEFT JOIN articles a ON c.article_id = a.id
              $where_sql 
              ORDER BY c.created_at DESC 
              LIMIT ? OFFSET ?";
$params[] = $records_per_page; $params[] = $offset; $types .= 'ii';
$stmt_fetch = $conn->prepare($fetch_sql);
if (count($params) > 0) { $stmt_fetch->bind_param($types, ...$params); }
$stmt_fetch->execute();
$comments_result = $stmt_fetch->get_result();

$status_map = ['approved' => 'success', 'pending' => 'warning', 'spam' => 'danger'];


// 4. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<style>
    .row-actions { visibility: hidden; opacity: 0; transition: opacity 0.2s ease-in-out; }
    tr:hover .row-actions { visibility: visible; opacity: 1; }
</style>

<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<div class="card mb-4 shadow-sm">
    <div class="card-header"><i class="bi bi-filter me-1"></i> Filter Comments</div>
    <div class="card-body">
        <form action="manage-comments.php" method="GET" class="row g-3">
            <div class="col-md-6"><input type="text" name="search" class="form-control" placeholder="Search by comment content or author..." value="<?php echo htmlspecialchars($search_term); ?>"></div>
            <div class="col-md-3">
                <select name="status" class="form-select">
                    <option value="">All Statuses</option>
                    <option value="pending" <?php if($status_filter == 'pending') echo 'selected'; ?>>Pending</option>
                    <option value="approved" <?php if($status_filter == 'approved') echo 'selected'; ?>>Approved</option>
                    <option value="spam" <?php if($status_filter == 'spam') echo 'selected'; ?>>Spam</option>
                </select>
            </div>
            <div class="col-md-3 d-grid d-md-flex gap-2"><button type="submit" class="btn btn-primary flex-grow-1">Filter</button><a href="manage-comments.php" class="btn btn-secondary flex-grow-1">Clear</a></div>
        </form>
    </div>
</div>

<form method="POST" action="manage-comments.php">
    <input type="hidden" name="action" value="bulk_update">
    <div class="d-flex mb-3">
        <div class="me-2">
            <select name="bulk_action" class="form-select form-select-sm" style="width: auto;">
                <option value="">Bulk Actions</option>
                <option value="approved">Approve</option>
                <option value="pending">Mark as Pending</option>
                <option value="spam">Mark as Spam</option>
                <option value="delete">Delete</option>
            </select>
        </div>
        <button type="submit" class="btn btn-sm btn-outline-secondary">Apply</button>
    </div>
    
    <div class="table-responsive">
        <table class="table table-hover align-middle">
            <thead class="table-dark">
                <tr>
                    <th style="width: 3%;"><input type="checkbox" id="select-all-checkbox" class="form-check-input"></th>
                    <th>Author</th>
                    <th>Comment</th>
                    <th>In Response To</th>
                    <th>Date</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($comments_result->num_rows > 0): while ($comment = $comments_result->fetch_assoc()): ?>
                <tr>
                    <td><input type="checkbox" name="comment_ids[]" value="<?php echo $comment['id']; ?>" class="form-check-input row-checkbox"></td>
                    <td><strong><?php echo htmlspecialchars($comment['author_name']); ?></strong></td>
                    <td>
                        <span class="badge bg-<?php echo $status_map[$comment['status']] ?? 'secondary'; ?>"><?php echo htmlspecialchars(ucfirst($comment['status'])); ?></span>
                        <p class="mt-2 text-muted"><?php echo htmlspecialchars(substr($comment['comment_text'], 0, 150)); ?><?php if(strlen($comment['comment_text']) > 150) echo '...'; ?></p>
                        <div class="row-actions small">
                            <?php if($comment['status'] !== 'approved'): ?><a href="actions/update_comment_status.php?id=<?php echo $comment['id']; ?>&status=approved" class="text-success">Approve</a> | <?php endif; ?>
                            <?php if($comment['status'] !== 'pending'): ?><a href="actions/update_comment_status.php?id=<?php echo $comment['id']; ?>&status=pending" class="text-warning">Mark as Pending</a> | <?php endif; ?>
                            <a href="#" class="text-primary">Reply</a> |
                            <a href="#" class="text-primary">Edit</a> |
                            <?php if($comment['status'] !== 'spam'): ?><a href="actions/update_comment_status.php?id=<?php echo $comment['id']; ?>&status=spam" class="text-danger">Spam</a> | <?php endif; ?>
                            <a href="actions/delete_comment.php?id=<?php echo $comment['id']; ?>" class="text-danger" onclick="return confirm('Are you sure you want to permanently delete this comment?');">Delete</a>
                        </div>
                    </td>
                    <td>
                        <a href="../article-details.php?id=<?php echo $comment['article_id']; ?>" target="_blank">
                            <?php echo htmlspecialchars($comment['article_title'] ?? 'N/A'); ?>
                        </a>
                    </td>
                    <td><?php echo date('M d, Y', strtotime($comment['created_at'])); ?></td>
                </tr>
                <?php endwhile; else: ?>
                <tr><td colspan="5" class="text-center p-4">No comments found.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</form>

<?php if($total_pages > 1): ?>
<nav><ul class="pagination justify-content-center mt-4">
    <?php $query_params = $_GET; for ($i = 1; $i <= $total_pages; $i++): $query_params['page'] = $i; ?>
        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>"><a class="page-link" href="?<?php echo http_build_query($query_params); ?>"><?php echo $i; ?></a></li>
    <?php endfor; ?>
</ul></nav>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const selectAllCheckbox = document.getElementById('select-all-checkbox');
    const rowCheckboxes = document.querySelectorAll('.row-checkbox');
    selectAllCheckbox.addEventListener('change', function() {
        rowCheckboxes.forEach(checkbox => {
            checkbox.checked = selectAllCheckbox.checked;
        });
    });
});
</script>

<?php include 'admin-footer.php'; ?>
