<?php
require_once 'connection.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $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();
    }

    // Get sender and receiver email from request
    $senderEmail = $_POST['senderEmail'];
    $receiverEmail = $_POST['receiverEmail'];

    // 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
        // echo "File uploaded successfully";

        $message = $filePath; // File path as message
        $type = 'audio'; // Type is audio

        $query = "INSERT INTO `chat` (`sender_email`, `receiver_email`, `message`, `type`) VALUES ('$senderEmail', '$receiverEmail', '$message', '$type')";
        $result = mysqli_query($conn, $query);

        if ($result) {
            echo $message;
       } else {
            http_response_code(500);
            echo "Error inserting into chat table: " . mysqli_error($conn);
        }
    } else {
        // Failed to move file
        http_response_code(500);
        echo "Error saving file";
    }
} else {
    // Invalid request
    http_response_code(400);
    echo "Invalid request";
}
$conn->close();
?>