<?php
require_once 'connection.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['file']) && isset($_POST['groupId']) && isset($_POST['senderEmail'])) {
        $uploadDir = 'voice_messages/'; 

        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $file = $_FILES['file'];

        if ($file['error'] !== UPLOAD_ERR_OK) {
            http_response_code(400);
            echo "Error uploading file: " . $file['error'];
            exit();
        }

        $groupId = $_POST['groupId'];
        $senderEmail = $_POST['senderEmail'];

        // Generate a random filename for the uploaded file
        $randomFileName = uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);

        // Move the uploaded file to the specified directory with the random filename
        $filePath = $uploadDir . $randomFileName;
        if (move_uploaded_file($file['tmp_name'], $filePath)) {
            // File uploaded successfully
            $messageContent = $filePath; // File path as message
            $messageType = 'GroupVoice'; // Type is audio

            // Prepare and execute SQL statement
            $sql = "INSERT INTO groupmessagetable (groupId, senderEmail, messageContent, messageType) 
                    VALUES (?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);

            if ($stmt) {
                $stmt->bind_param("ssss", $groupId, $senderEmail, $messageContent, $messageType);

                if ($stmt->execute()) {
                    echo $messageContent; // Return file path for client-side use
                } else {
                    http_response_code(500);
                    echo "Error inserting into groupmessagetable: " . $stmt->error;
                }

                $stmt->close();
            } else {
                http_response_code(500);
                echo "Error preparing SQL statement: " . $conn->error;
            }
        } else {
            // Failed to move file
            http_response_code(500);
            echo "Error saving file";
        }
    } else {
        // Missing file or POST data
        http_response_code(400);
        echo "Missing file or POST data";
    }
} else {
    // Invalid request
    http_response_code(400);
    echo "Invalid request";
}

$conn->close();
?>
