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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $student_id = $_SESSION['student_id'];
    $group_id = $_POST['group_id'];
    $group_type = $_POST['group_type'];
    $join_date = date('Y-m-d H:i:s');

    try {
        // Begin a transaction
        $conn->begin_transaction();

        // Verify that the group_id exists in student_groups table
        $group_check_sql = "SELECT 1 FROM student_groups WHERE group_id = ?";
        $group_check_stmt = $conn->prepare($group_check_sql);
        if (!$group_check_stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        $group_check_stmt->bind_param("i", $group_id);
        $group_check_stmt->execute();
        $group_check_result = $group_check_stmt->get_result();
        
        if ($group_check_result->num_rows === 0) {
            throw new Exception("Group does not exist.");
        }

        if ($group_type == 'public') {
            // Insert into group_members for public groups
            $sql = "INSERT INTO group_members (group_id, student_id, join_date) VALUES (?, ?, ?)";
        } else {
            // Insert into join_requests for private groups
            $sql = "INSERT INTO join_requests (group_id, student_id, status, request_date) VALUES (?, ?, 'Pending', ?)";
        }

        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }

        if ($group_type == 'public') {
            $stmt->bind_param("iis", $group_id, $student_id, $join_date);
        } else {
            $stmt->bind_param("iis", $group_id, $student_id, $join_date);
        }

        $stmt->execute();
        if ($stmt->affected_rows === 0) {
            throw new Exception("Execute failed: " . $stmt->error);
        }
        
        $stmt->close();
        $group_check_stmt->close();

        // Commit the transaction
        $conn->commit();

        // Redirect back to the groups page with success message
        header("Location: groups.php?message=success");
        exit();
    } catch (mysqli_sql_exception $exception) {
        $conn->rollback();
        error_log("Database error: " . $exception->getMessage());
        // Detailed error message for debugging
        header("Location: groups.php?message=db_error&error=" . urlencode($exception->getMessage()));
        exit();
    } catch (Exception $exception) {
        $conn->rollback();
        error_log("Error: " . $exception->getMessage());
        // Detailed error message for debugging
        header("Location: groups.php?message=" . urlencode($exception->getMessage()));
        exit();
    } finally {
        $conn->close();
    }
} else {
    // Redirect if the request method is not POST
    header("Location: groups.php?message=invalid_request");
    exit();
}
