<?php
include 'db_connection.php';

// Check if group_id is set in the query string
if (!isset($_GET['group_id']) || empty($_GET['group_id'])) {
    echo "Invalid group ID.";
    exit;
}

// Get the group_id from the query string
$group_id = intval($_GET['group_id']);

// Fetch group details
$sql = "SELECT group_name FROM student_groups WHERE group_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $group_id);
$stmt->execute();
$groupResult = $stmt->get_result();
$group = $groupResult->fetch_assoc();

if (!$group) {
    echo "Group not found.";
    exit;
}

// Fetch group members
$sql = "SELECT gm.id, gm.group_id, gm.user_id, s.name AS student_name
        FROM group_members gm
        JOIN students s ON gm.user_id = s.student_id
        WHERE gm.group_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $group_id);
$stmt->execute();
$result = $stmt->get_result();
$members = [];
while ($row = $result->fetch_assoc()) {
    $members[] = $row;
}
?>

<h2>Members of Group: <?php echo htmlspecialchars($group['group_name']); ?></h2>
<?php if (count($members) > 0): ?>
    <table border='1'>
        <tr>
            
            <th>Group Name</th>
            
            <th>Student Name</th>
        </tr>
        <?php foreach ($members as $member): ?>
            <tr>
                
                <td><?php echo htmlspecialchars($group['group_name']); ?></td>
                
                <td>
                    <a href="view_profile.php?user_id=<?php echo $member['user_id']; ?>">
                        <?php echo htmlspecialchars($member['student_name']); ?>
                    </a>
                </td>
            </tr>
        <?php endforeach; ?>
    </table>
<?php else: ?>
    <p>No members found for this group.</p>
<?php endif; ?>
