false, 'message' => 'Metodo non consentito.']); exit; } $pdo = DBHandlerSelect::getInstance()->getConnection(); $id = (int)($_POST['id'] ?? 0); if ($id <= 0) { echo json_encode(['success' => false, 'message' => 'ID formazione non valido.']); exit; } try { $pdo->beginTransaction(); $row = $pdo->prepare("SELECT employee_id FROM employee_trainings WHERE id = :id"); $row->execute(['id' => $id]); $tr = $row->fetch(PDO::FETCH_ASSOC); if (!$tr) { $pdo->rollBack(); echo json_encode(['success' => false, 'message' => 'Formazione non trovata.']); exit; } // Collect attached files BEFORE deletion so we can unlink them after $files = $pdo->prepare("SELECT stored_name FROM employee_training_attachments WHERE training_id = :id"); $files->execute(['id' => $id]); $stored = $files->fetchAll(PDO::FETCH_COLUMN); // Log BEFORE delete (FK on log allows SET NULL on training delete but we want a clean record) $pdo->prepare(" INSERT INTO employee_training_log (employee_id, training_id, action, field, old_value, new_value, changed_by, changed_at) VALUES (:eid, NULL, 'deleted', NULL, NULL, NULL, :cb, NOW()) ")->execute(['eid' => $tr['employee_id'], 'cb' => $currentUserId]); $pdo->prepare("DELETE FROM employee_trainings WHERE id = :id")->execute(['id' => $id]); $pdo->commit(); foreach ($stored as $name) { $path = __DIR__ . '/../../files/employees/' . (int)$tr['employee_id'] . '/trainings/' . $name; if (is_file($path)) { @unlink($path); } } echo json_encode(['success' => true]); } catch (Exception $e) { if ($pdo->inTransaction()) $pdo->rollBack(); echo json_encode(['success' => false, 'message' => $e->getMessage()]); }