query( "SELECT t.id, t.nombre, t.porcentaje, t.tarifa_origen, tb.nombre AS tarifa_origen_nombre FROM lab_tarifas_id t LEFT JOIN lab_tarifas_id tb ON tb.id = t.tarifa_origen ORDER BY t.id ASC" )->fetchAll(PDO::FETCH_ASSOC); jsonOk(['tarifas' => $rows]); } requireMethod('POST'); $data = json_decode(file_get_contents('php://input'), true) ?? []; $action = $data['action'] ?? ''; if ($action === 'delete') { $id = (int)($data['id'] ?? 0); if ($id <= 0) jsonError('id requerido'); $chk = $pdo->prepare("SELECT COUNT(*) FROM lab_tarifas WHERE tarifa_id = ? LIMIT 1"); $chk->execute([$id]); if ((int)$chk->fetchColumn() > 0) { jsonError('No se puede eliminar: la tarifa tiene precios de exámenes asociados.', 409); } $pdo->prepare("DELETE FROM lab_tarifas_id WHERE id = ?")->execute([$id]); jsonOk(['deleted' => true]); } if ($action === 'save') { $id = isset($data['id']) && $data['id'] !== '' ? (int)$data['id'] : null; $nombre = trim($data['nombre'] ?? ''); $porcentaje = isset($data['porcentaje']) ? (float)$data['porcentaje'] : 0; $origen = isset($data['tarifa_origen']) && $data['tarifa_origen'] !== '' ? (int)$data['tarifa_origen'] : null; if ($nombre === '') jsonError('nombre requerido'); if ($id !== null) { $chk = $pdo->prepare("SELECT id FROM lab_tarifas_id WHERE id = ?"); $chk->execute([$id]); if ($chk->fetch()) { $pdo->prepare( "UPDATE lab_tarifas_id SET nombre=?, porcentaje=?, tarifa_origen=? WHERE id=?" )->execute([$nombre, $porcentaje, $origen, $id]); } else { $pdo->prepare( "INSERT INTO lab_tarifas_id (id, nombre, porcentaje, tarifa_origen) VALUES (?,?,?,?)" )->execute([$id, $nombre, $porcentaje, $origen]); } } else { $maxId = (int)$pdo->query("SELECT COALESCE(MAX(id),0)+1 FROM lab_tarifas_id")->fetchColumn(); $pdo->prepare( "INSERT INTO lab_tarifas_id (id, nombre, porcentaje, tarifa_origen) VALUES (?,?,?,?)" )->execute([$maxId, $nombre, $porcentaje, $origen]); $id = $maxId; } jsonOk(['id' => $id]); } jsonError('Acción no reconocida', 400);