<?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;
$request_date = date('Y-m-d H:i:s'); // Current date and time
$status = 'Pending'; // Initial status

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $group_id = isset($_POST['group_id']) ? intval($_POST['group_id']) : 0;
    $student_id = isset($_POST['student_id']) ? intval($_POST['student_id']) : 0;
    
    if ($group_id > 0 && $student_id > 0) {
        // Insert join request
        $stmt = $conn->prepare("INSERT INTO join_requests (group_id, student_id, status, request_date) VALUES (?, ?, 'Pending', NOW())");
        $stmt->bind_param('ii', $group_id, $student_id);
        
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $group_id = isset($_POST['group_id']) ? intval($_POST['group_id']) : 0;
    $student_id = isset($_POST['student_id']) ? intval($_POST['student_id']) : 0;
    
    if ($group_id > 0 && $student_id > 0) {
        // Insert join request
        $stmt = $conn->prepare("INSERT INTO join_requests (group_id, student_id, status, request_date) VALUES (?, ?, 'Pending', NOW())");
        $stmt->bind_param('ii', $group_id, $student_id);
        
        if ($stmt->execute()) {
            // Fetch group admin (assuming created_by is a column in student_groups)
            $admin_stmt = $conn->prepare("SELECT created_by FROM student_groups WHERE group_id = ?");
            $admin_stmt->bind_param('i', $group_id);
            $admin_stmt->execute();
            $admin_stmt->bind_result($created_by);
            $admin_stmt->fetch();
            $admin_stmt->close();
            
            // Fetch student's name
            $student_stmt = $conn->prepare("SELECT name FROM students WHERE student_id = ?");
            $student_stmt->bind_param('i', $student_id);
            $student_stmt->execute();
            $student_stmt->bind_result($student_name);
            $student_stmt->fetch();
            $student_stmt->close();
            
            // Insert notification for group admin
            if ($created_by) {
                $message = "New join request from $student_name";
                $notif_stmt = $conn->prepare("INSERT INTO group_notifications (group_id, student_id, message) VALUES (?, ?, ?)");
                $notif_stmt->bind_param('iis', $group_id, $created_by, $message);
                $notif_stmt->execute();
                $notif_stmt->close();
            }
            
            echo "Join request submitted successfully.";
        } else {
            echo "Error: " . $stmt->error;
        }

        $stmt->close();
    } else {
        echo "Invalid data provided.";
    }

    $conn->close();
}
}
}
?>