<?php
require_once 'connection.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_FILES['groupProfile']) && isset($_POST['groupName']) && isset($_POST['groupOwnerEmail'])) {
        $groupName = $_POST['groupName'];
        $groupOwnerEmail = $_POST['groupOwnerEmail'];
        $groupProfile = $_FILES['groupProfile'];

        if ($groupProfile['error'] === UPLOAD_ERR_OK) {
            $fileExtension = pathinfo($groupProfile['name'], PATHINFO_EXTENSION);
            $fileName = uniqid() . '.' . $fileExtension;
            $filePath = 'profile_images/' . $fileName;

            if (move_uploaded_file($groupProfile['tmp_name'], $filePath)) {
                $fileUrl = 'http://192.168.1.22/push_talk/'  . $filePath;

                // Prepare and execute the insert statement
                $stmt = $conn->prepare("INSERT INTO `grouptable` (`groupName`, `groupOwnerEmail`, `groupProfile`) VALUES (?, ?, ?)");
                $stmt->bind_param("sss", $groupName, $groupOwnerEmail, $fileUrl);
                
                if ($stmt->execute()) {
                    // Get the auto-incremented groupId
                    $groupId = $stmt->insert_id;
                    
                    // Return success message and groupId
                    echo json_encode([
                        'status' => 'success',
                        'message' => 'Group created successfully.',
                        'groupId' => $groupId
                    ]);
                } else {
                    echo json_encode([
                        'status' => 'error',
                        'message' => 'Error: ' . $stmt->error
                    ]);
                }

                $stmt->close();
            } else {
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Failed to move uploaded file.'
                ]);
            }
        } else {
            echo json_encode([
                'status' => 'error',
                'message' => 'Error in file upload: ' . $groupProfile['error']
            ]);
        }
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => 'Required fields or file are missing.'
        ]);
    }
}

$conn->close();
?>
