<?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
    $group_id = intval($_POST['group_id']);
    $groupName = htmlspecialchars($_POST['group_name']);
    $groupDescription = htmlspecialchars($_POST['group_description']);
    $privacy = $_POST['group_type'];
    $category = $_POST['group_category'];
    $groupRules = htmlspecialchars($_POST['group_rules']);
    $groupImage = '';

    // Retrieve the current group image
    $stmt = $conn->prepare("SELECT group_image FROM student_groups WHERE group_id = ?");
    $stmt->bind_param("i", $group_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $currentGroup = $result->fetch_assoc();
        $groupImage = $currentGroup['group_image'];
    }
    $stmt->close();

    // 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'])) {
        $studentId = $_SESSION['student_id'];
        $createdBy = $_SESSION['student_id'];
    } else {
        echo "User not logged in.";
        exit;
    }

    // Update group data in the database
    $stmt = $conn->prepare("UPDATE student_groups SET group_name = ?, description = ?, created_by = ?, group_type = ?, group_image = ?, group_category = ?, group_rules = ? WHERE group_id = ?");
    $stmt->bind_param("sssssssi", $groupName, $groupDescription, $createdBy, $privacy, $groupImage, $category, $groupRules, $group_id);

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

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