false, 'message' => 'ID non valido.']); exit; } $id = (int)$_GET['id']; $db = DBHandlerSelect::getInstance(); $pdo = $db->getConnection(); // Collect the physical files referenced by this deadline before the FK cascade removes its links $attStmt = $pdo->prepare("SELECT DISTINCT stored_name FROM scad_deadline_attachments WHERE deadline_id = ?"); $attStmt->execute([$id]); $storedNames = $attStmt->fetchAll(PDO::FETCH_COLUMN); // Deleting the deadline cascades to its attachment/employee/history rows (FK ON DELETE CASCADE) $stmt = $pdo->prepare("DELETE FROM scad_deadlines WHERE id = ?"); $stmt->execute([$id]); if ($stmt->rowCount() > 0) { // Unlink physical files no longer referenced by any other deadline (shared-file safe) if (!empty($storedNames)) { $refStmt = $pdo->prepare("SELECT COUNT(*) FROM scad_deadline_attachments WHERE stored_name = ?"); foreach ($storedNames as $storedName) { $refStmt->execute([$storedName]); if ((int)$refStmt->fetchColumn() === 0) { $filePath = __DIR__ . '/../attachments/' . $storedName; if (file_exists($filePath)) { unlink($filePath); } } } } echo json_encode(['success' => true, 'message' => 'Scadenza eliminata con successo.']); } else { echo json_encode(['success' => false, 'message' => 'Scadenza non trovata.']); } } catch (Exception $e) { echo json_encode(['success' => false, 'message' => 'Errore: ' . $e->getMessage()]); }