prepare("SELECT id, name FROM inv_equipment WHERE id = ?"); $stmt->execute([$id]); $equipment = $stmt->fetch(PDO::FETCH_ASSOC); if (!$equipment) { mnt_json_fail('Attrezzatura non trovata.'); } // Legacy production records reference tools without ON DELETE CASCADE: // refuse with a clear message instead of letting the FK throw. $stmt = $pdo->prepare("SELECT COUNT(*) FROM productiondata_tools WHERE tool_id = ?"); $stmt->execute([$id]); $usedInProduction = (int)$stmt->fetchColumn(); if ($usedInProduction > 0) { mnt_json_fail( 'Impossibile eliminare: l\'attrezzatura รจ usata in ' . $usedInProduction . ' registrazioni di produzione. Impostala su "Dismesso" per escluderla dalle pianificazioni.' ); } // Collect stored files before the cascade removes their rows $storedNames = []; $stmt = $pdo->prepare("SELECT stored_name FROM inv_equipment_files WHERE equipment_id = ?"); $stmt->execute([$id]); $storedNames = array_merge($storedNames, $stmt->fetchAll(PDO::FETCH_COLUMN)); $stmt = $pdo->prepare(" SELECT f.stored_name FROM maint_maintenance_files f INNER JOIN maint_maintenances m ON m.id = f.maintenance_id WHERE m.equipment_id = ? "); $stmt->execute([$id]); $storedNames = array_merge($storedNames, $stmt->fetchAll(PDO::FETCH_COLUMN)); $stmt = $pdo->prepare(" SELECT f.stored_name FROM maint_intervention_files f INNER JOIN maint_interventions i ON i.id = f.intervention_id WHERE i.equipment_id = ? "); $stmt->execute([$id]); $storedNames = array_merge($storedNames, $stmt->fetchAll(PDO::FETCH_COLUMN)); $stmt = $pdo->prepare("SELECT signature_path FROM maint_interventions WHERE equipment_id = ? AND signature_path IS NOT NULL"); $stmt->execute([$id]); $storedNames = array_merge($storedNames, $stmt->fetchAll(PDO::FETCH_COLUMN)); // cover_file_id points at inv_equipment_files, which cascades from the // equipment row: clear it first so the FK does not block the delete. $pdo->beginTransaction(); $pdo->prepare("UPDATE inv_equipment SET cover_file_id = NULL WHERE id = ?")->execute([$id]); $pdo->prepare("DELETE FROM inv_equipment WHERE id = ?")->execute([$id]); $pdo->commit(); foreach (array_filter($storedNames) as $storedName) { mnt_delete_stored_file($storedName); } mnt_log($pdo, 'equipment_deleted', null, null, null, $currentUserId, null, $equipment['name']); mnt_json_ok(); } catch (Throwable $e) { if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); } mnt_json_fail('Errore: ' . $e->getMessage()); }