false, 'message' => 'ID non valido.']); exit; } $id = (int)$_GET['id']; $db = DBHandlerSelect::getInstance(); $pdo = $db->getConnection(); $stmt = $pdo->prepare("SELECT * FROM scad_deadline_attachments WHERE id = ?"); $stmt->execute([$id]); $att = $stmt->fetch(PDO::FETCH_ASSOC); if (!$att) { echo json_encode(['success' => false, 'message' => 'Allegato non trovato.']); exit; } // Remove this link (DB record) first $pdo->prepare("DELETE FROM scad_deadline_attachments WHERE id = ?")->execute([$id]); // The same physical file may be shared with other deadlines (carried forward on completion). // Only unlink it when no other link references the same stored file. $refStmt = $pdo->prepare("SELECT COUNT(*) FROM scad_deadline_attachments WHERE stored_name = ?"); $refStmt->execute([$att['stored_name']]); $stillReferenced = (int)$refStmt->fetchColumn() > 0; if ($stillReferenced) { $action = 'attachment_unlinked'; $message = 'Collegamento rimosso. Il file รจ conservato (usato da un\'altra scadenza).'; } else { $filePath = __DIR__ . '/../attachments/' . $att['stored_name']; if (file_exists($filePath)) { unlink($filePath); } $action = 'attachment_removed'; $message = 'Allegato eliminato.'; } // History $pdo->prepare("INSERT INTO scad_deadline_histories (deadline_id, user_id, action, notes) VALUES (?, ?, ?, ?)") ->execute([$att['deadline_id'], $currentUserId, $action, $att['original_name']]); echo json_encode(['success' => true, 'message' => $message]); } catch (Exception $e) { echo json_encode(['success' => false, 'message' => 'Errore: ' . $e->getMessage()]); }