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


// Assuming $group_id and $student_id are obtained from user input or session
$group_id = isset($_POST['group_id']) ? intval($_POST['group_id']) : 0;
$student_id = isset($_POST['student_id']) ? intval($_POST['student_id']) : 0;
$join_date = date('Y-m-d H:i:s'); // Current date and time

if ($group_id > 0 && $student_id > 0) {
    // Validate group_id
    $groupCheckSql = "SELECT COUNT(*) FROM student_groups WHERE group_id = ?";
    $groupCheckStmt = $conn->prepare($groupCheckSql);
    $groupCheckStmt->bind_param("i", $group_id);
    $groupCheckStmt->execute();
    $groupCheckStmt->bind_result($groupCount);
    $groupCheckStmt->fetch();
    $groupCheckStmt->close();

    // Validate student_id
    $studentCheckSql = "SELECT COUNT(*) FROM students WHERE student_id = ?";
    $studentCheckStmt = $conn->prepare($studentCheckSql);
    $studentCheckStmt->bind_param("i", $student_id);
    $studentCheckStmt->execute();
    $studentCheckStmt->bind_result($studentCount);
    $studentCheckStmt->fetch();
    $studentCheckStmt->close();

    if ($groupCount > 0 && $studentCount > 0) {
        // SQL query to insert into group_members table
        $sql = "INSERT INTO group_members (group_id, student_id, join_date) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iis", $group_id, $student_id, $join_date);

        if ($stmt->execute()) {
            echo "Joined the group successfully.";
        } else {
            echo "Error: " . $stmt->error;
        }
        $stmt->close();
    } else {
        if ($groupCount == 0) {
            echo "Invalid group ID.";
        }
        if ($studentCount == 0) {
            echo "Invalid student ID.";
        }
    }
} else {
    echo "Group ID and Student ID must be greater than 0.";
}

$conn->close();
?>