<?php
include 'db_connection.php';
session_start();

// Check if the student is logged in
if (!isset($_SESSION['student_id'])) {
    echo "You need to log in first.";
    exit;
}

$logged_in_student_id = $_SESSION['student_id'];

// Fetch students for the dropdown
$sql_students = "SELECT student_id, name FROM students";
$result_students = $conn->query($sql_students);

$students = [];
while ($row = $result_students->fetch_assoc()) {
    $students[] = $row;
}

// Fetch groups created by the logged-in student for the dropdown
$sql_groups = "SELECT group_id, group_name 
               FROM student_groups 
               WHERE created_by = ?";
$stmt_groups = $conn->prepare($sql_groups);
$stmt_groups->bind_param("i", $logged_in_student_id);
$stmt_groups->execute();
$result_groups = $stmt_groups->get_result();

$groups = [];
while ($row = $result_groups->fetch_assoc()) {
    $groups[] = $row;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $selected_student_id = $_POST['student_id'];
    $selected_group_id = $_POST['group_id'];
    $joined_at = date('Y-m-d H:i:s');

    // Proceed with insertion into soc_group_members
    $sql_insert = "INSERT INTO soc_group_members (group_id, student_id, joined_at) VALUES (?, ?, ?)";
    $stmt_insert = $conn->prepare($sql_insert);
    $stmt_insert->bind_param("iis", $selected_group_id, $selected_student_id, $joined_at);

    if ($stmt_insert->execute()) {
        echo "Member added successfully!";
    } else {
        echo "Error adding member: " . $stmt_insert->error;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Member to Group</title>
</head>
<body>
    <h2>Add Member to Group</h2>
    <form method="post" action="">
        <label for="student_id">Select Student:</label>
        <select name="student_id" id="student_id" required>
            <?php foreach ($students as $student): ?>
                <option value="<?php echo htmlspecialchars($student['student_id']); ?>">
                    <?php echo htmlspecialchars($student['name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
        <br><br>
        <label for="group_id">Select Group:</label>
        <select name="group_id" id="group_id" required>
            <?php foreach ($groups as $group): ?>
                <option value="<?php echo htmlspecialchars($group['group_id']); ?>">
                    <?php echo htmlspecialchars($group['group_name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
        <br><br>
        <input type="submit" value="Add Member">
    </form>
</body>
</html>
