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

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Capture the group ID from the URL query parameter
    $group_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

    // Ensure a valid group ID
    if ($group_id <= 0) {
        die("Invalid Group ID.");
    }

    // Capture the student ID from the session
    $student_id = isset($_SESSION['student_id']) ? (int)$_SESSION['student_id'] : 0;

    // Get the post content
    $post_content = isset($_POST['post_content']) ? trim($_POST['post_content']) : '';
    
    // Check if the anonymous checkbox is checked
    $anonymous = isset($_POST['anonymous']) ? 1 : 0;

    // Set the post sender and profile picture based on anonymity
    if ($anonymous) {
        $post_sender = 'Anonymous Sender';
        $profile_picture = ''; // No profile picture needed for anonymous posts
    } else {
        $post_sender = $student_id;
        $profile_picture = ''; // Regular profile picture handling
    }

    // Handle file upload for group image
    $upload_dir = 'uploads/'; // Directory where the images will be stored
    $group_image = ''; // Default empty

    if (isset($_FILES['group_image']) && $_FILES['group_image']['error'] === UPLOAD_ERR_OK) {
        $file_tmp = $_FILES['group_image']['tmp_name'];
        $file_name = basename($_FILES['group_image']['name']);
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        // Define allowed file types and maximum file size
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
        $max_file_size = 2 * 1024 * 1024; // 2MB

        if (in_array($file_ext, $allowed_types) && $_FILES['group_image']['size'] <= $max_file_size) {
            $group_image = uniqid('', true) . '.' . $file_ext;
            $destination = $upload_dir . $group_image;

            if (move_uploaded_file($file_tmp, $destination)) {
                // File uploaded successfully
            } else {
                die("Error moving uploaded file.");
            }
        } else {
            die("Invalid file type or file too large.");
        }
    } elseif (isset($_FILES['group_image']) && $_FILES['group_image']['error'] != UPLOAD_ERR_NO_FILE) {
        // Handle file upload error
        die("File upload error: " . $_FILES['group_image']['error']);
    }

    // Ensure post content is not empty
    if (empty($post_content)) {
        die("Post content cannot be empty.");
    }

    // Set the current timestamp
    $timestamp = date('Y-m-d H:i:s');

    // Prepare the SQL statement to insert the post
    $sql = "INSERT INTO group_posts (group_id, student_id, post_sender, post_content, group_image, timestamp) VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);

    // Bind the parameters
    $stmt->bind_param("iissss", $group_id, $student_id, $post_sender, $post_content, $group_image, $timestamp);

    // Execute the statement and check if it was successful
    if ($stmt->execute()) {
        // Redirect to the group details page after successful post
        header("Location: group_details.php?id=$group_id");
        exit();
    } else {
        die("Error: " . $stmt->error);
    }

    // Close the statement and connection
    $stmt->close();
    $conn->close();
} else {
    // Redirect to the group details page if the form is not submitted
    header("Location: group_details.php?id=$group_id");
    exit();
}
?>