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

if ($_SERVER["REQUEST_METHOD"] === "POST" && !empty($_POST["file"])) {
    $file_to_delete = $_POST["file"];
    $user_id = $_POST["user_id"] ?? null; // Ensure user_id is available

    // Fetch existing media files from the database
    $select_query = "SELECT media_files FROM user_category_message_settings WHERE user_id = ?";
    $stmt = $conn->prepare($select_query);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->bind_result($media_files_str);
    $stmt->fetch();
    $stmt->close();

    if ($media_files_str) {
        $media_files = explode(',', $media_files_str);

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

                // Update database with the new file list
                $update_query = "UPDATE user_category_message_settings SET media_files = ? WHERE user_id = ?";
                $stmt = $conn->prepare($update_query);
                $stmt->bind_param("si", $updated_media_files_str, $user_id);
                $stmt->execute();
                $stmt->close();

                echo "success";
                exit;
            }
        }
    }

    echo "error";
}
?>
