<?php
// delete-document.php
header('Content-Type: application/json');

include('include/headscript.php');
$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {
    die(json_encode(["success" => false, "message" => "Errore di connessione al database."]));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $documentId = isset($_POST['document_id']) ? intval($_POST['document_id']) : 0;

    if ($documentId > 0) {
        // Elimina i tag associati
        $stmt = $conn->prepare("DELETE FROM document_tags WHERE document_id = ?");
        $stmt->bind_param("i", $documentId);
        $stmt->execute();
        $stmt->close();

        // Elimina il documento
        $stmt = $conn->prepare("DELETE FROM documents WHERE document_id = ?");
        $stmt->bind_param("i", $documentId);
        if ($stmt->execute()) {
            echo json_encode(["success" => true]);
        } else {
            echo json_encode(["success" => false, "message" => "Errore durante l'eliminazione dal database."]);
        }
        $stmt->close();
    } else {
        echo json_encode(["success" => false, "message" => "Parametri non validi."]);
    }
} else {
    echo json_encode(["success" => false, "message" => "Metodo non consentito."]);
}

$conn->close();
