<?php
include "db.php"; // Ensure this includes your database connection

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['voice_message'], $_POST['user_id'])) {
    $uploadDir = "uploads/media/"; // Make sure this folder is writable
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $userId = $_POST['user_id'];
    $timestamp = time();
    $fileName = $timestamp . ".ogg";
    $filePath = $uploadDir . $fileName;

    if (move_uploaded_file($_FILES['voice_message']['tmp_name'], $filePath)) {
        // Get existing voice_message value
        $stmt = $conn->prepare("SELECT voice_message FROM user_category_message_settings WHERE user_id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $stmt->bind_result($existingVoiceMessage);
        $stmt->fetch();
        $stmt->close();

        // Append new file path if existing data is not empty or null
        $newVoiceMessage = empty($existingVoiceMessage) ? $filePath : $existingVoiceMessage . "," . $filePath;

        // Update the database
        $updateStmt = $conn->prepare("UPDATE user_category_message_settings SET voice_message = ? WHERE user_id = ?");
        $updateStmt->bind_param("si", $newVoiceMessage, $userId);
        $updateStmt->execute();
        $updateStmt->close();

        echo "Success: File uploaded and database updated.";
    } else {
        echo "Error: Failed to upload file.";
    }
} else {
    echo "Error: No file uploaded or user ID missing.";
}
?>
