<?php
session_start(); // Start the session to access session variables

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Include database connection
    include('db_connection.php');

    // Get form data
    $groupName = htmlspecialchars($_POST['group_name']);
    $groupDescription = htmlspecialchars($_POST['group_description']);
    $privacy = $_POST['group_type'];
    $category = $_POST['group_category'];
    $groupRules = htmlspecialchars($_POST['group_rules']);
    $groupImage = '';

    // Handle file upload
    if (isset($_FILES['group_image']) && $_FILES['group_image']['error'] === UPLOAD_ERR_OK) {
        $imageTmpPath = $_FILES['group_image']['tmp_name'];
        $imageName = basename($_FILES['group_image']['name']);
        $uploadDir = 'uploads/';
        $destPath = $uploadDir . $imageName;

        if (move_uploaded_file($imageTmpPath, $destPath)) {
            $groupImage = $imageName;
        } else {
            echo "Failed to upload image.";
            exit;
        }
    }

    // Retrieve student_id and created_by from the session
    if (isset($_SESSION['student_id']) && isset($_SESSION['student_id'])) {
        $studentId = $_SESSION['student_id'];
        $createdBy = $_SESSION['student_id'];
    } else {
        echo "User not logged in.";
        exit;
    }

    // Insert group data into the database
    $stmt = $conn->prepare("INSERT INTO student_groups (student_id, group_name, description, created_by, group_type, group_image, created_at, group_rules) VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)");
    $stmt->bind_param("issssss", $studentId, $groupName, $groupDescription, $createdBy, $privacy, $groupImage, $groupRules);

    if ($stmt->execute()) {
        // Redirect to the create group page after successful creation
        header("Location: creat_group.php");
        exit;
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
    $conn->close();
} else {
    echo "Invalid request method.";
}
?>
