<?php
include "db.php";  // Ensure this file connects to your database

if ($_SERVER["REQUEST_METHOD"] === "POST" && !empty($_POST["file"]) && !empty($_POST["user_id"])) {
    $file_to_delete = $_POST["file"];
    $user_id = $_POST["user_id"];

    // Fetch existing voice messages
    $select_query = "SELECT voice_message FROM user_category_message_settings WHERE user_id = ?";
    $stmt = $conn->prepare($select_query);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->bind_result($voice_messages_str);
    $stmt->fetch();
    $stmt->close();

    if ($voice_messages_str) {
        $voice_messages = explode(',', $voice_messages_str);

        if (in_array($file_to_delete, $voice_messages) && file_exists($file_to_delete)) {
            if (unlink($file_to_delete)) { // Delete from server
                $voice_messages = array_diff($voice_messages, [$file_to_delete]); // Remove from array
                $updated_voice_messages_str = implode(',', $voice_messages); // Convert back to string

                // Update database
                $update_query = "UPDATE user_category_message_settings SET voice_message = ? WHERE user_id = ?";
                $stmt = $conn->prepare($update_query);
                $stmt->bind_param("si", $updated_voice_messages_str, $user_id);
                $stmt->execute();
                $stmt->close();

                echo "success";
                exit;
            }
        }
    }
}

echo "error";
?>
