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


if (isset($_GET['request_id'])) {
    $request_id = intval($_GET['request_id']);
    
    // Fetch join request details
    $stmt = $conn->prepare("SELECT group_id, student_id FROM join_requests WHERE request_id = ?");
    $stmt->bind_param('i', $request_id);
    $stmt->execute();
    $stmt->bind_result($group_id, $student_id);
    $stmt->fetch();
    $stmt->close();

    if ($group_id && $student_id) {
        // Update join request status to 'Approved'
        $stmt = $conn->prepare("UPDATE join_requests SET status = 'Approved' WHERE request_id = ?");
        $stmt->bind_param('i', $request_id);
        
        if ($stmt->execute()) {
            $stmt->close();
            
            // Insert member into group_members table
            $stmt = $conn->prepare("INSERT INTO group_members (group_id, student_id, join_date) VALUES (?, ?, NOW())");
            $stmt->bind_param('ii', $group_id, $student_id);
            
            if ($stmt->execute()) {
                echo "Join request approved and member added to the group.";
            } else {
                echo "Error: " . $stmt->error;
            }

            $stmt->close();
        } else {
            echo "Error: " . $stmt->error;
        }
    } else {
        echo "Invalid join request.";
    }
} else {
    echo "Invalid request ID.";
}

$conn->close();

// Redirect back to the pending requests page (adjust the path as necessary)
header("Location: pending_requests.php");
exit;
?>
