prepare("SELECT paciente_id FROM turnero_turnos WHERE id = ? LIMIT 1"); $row->execute([$turnoId]); $t = $row->fetchColumn(); if (!$t) jsonOk(['tomas' => []]); $pacienteId = (int)$t; $stmt = $pdo->prepare( "SELECT tc.id, tc.turno_id, tc.token, tc.siguiente_toma_at, tc.toma_inicio_at, tc.datos_respuestas, f.nombre AS formulario_nombre, f.esquema, tt.codigo AS turno_codigo, tt.creado_at AS turno_fecha FROM turnero_consentimientos tc JOIN lab_formularios f ON f.id = tc.formulario_id AND f.es_toma_progresiva = 1 JOIN turnero_turnos tt ON tt.id = tc.turno_id WHERE tt.paciente_id = ? AND tc.turno_id != ? AND tc.estado = 'en_progreso' ORDER BY tc.id DESC LIMIT 10" ); $stmt->execute([$pacienteId, $turnoId]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); $tomas = []; foreach ($rows as $r) { $esquema = json_decode($r['esquema'] ?? '[]', true) ?: []; $datos = json_decode($r['datos_respuestas'] ?? '[]', true) ?: []; // Contar firmas activas — mismo filtro que guardar_toma.php // (condicionales de separador + _tomas_config) $firmasCampos = []; $separadorLabel = null; $curCondField = null; $curCondVals = []; foreach ($esquema as $c) { $tipo = $c['tipo'] ?? ''; if ($tipo === 'separador') { $separadorLabel = $c['label'] ?? ''; $cond = $c['condicion'] ?? null; if ($cond) { $curCondField = $cond['campo_id'] ?? null; $curCondVals = $cond['valores'] ?? ($cond['valor'] ? [$cond['valor']] : []); } else { $curCondField = null; $curCondVals = []; } } if ($tipo === 'firma_profesional') { if ($curCondField !== null && !empty($curCondVals)) { $ctrlVal = $datos[$curCondField] ?? null; $ctrlArr = is_array($ctrlVal) ? $ctrlVal : ($ctrlVal !== null ? [$ctrlVal] : []); if (empty(array_intersect($curCondVals, $ctrlArr))) continue; } $firmasCampos[] = $c['id']; } } $tcFirmas = $datos['_tomas_config'] ?? null; if (is_array($tcFirmas)) { $allowed = []; foreach ($tcFirmas as $ids) { if (is_array($ids)) foreach ($ids as $id) $allowed[$id] = true; } $firmasCampos = array_values(array_filter($firmasCampos, fn($id) => isset($allowed[$id]))); } $totalFirmas = count($firmasCampos); $firmasHechas = 0; foreach ($firmasCampos as $fid) { if (!empty($datos[$fid]) && strlen($datos[$fid]) > 10) $firmasHechas++; } $tomas[] = [ 'id' => (int)$r['id'], 'turno_id' => (int)$r['turno_id'], 'token' => $r['token'], 'formulario_nombre' => $r['formulario_nombre'], 'siguiente_toma_at' => $r['siguiente_toma_at'], 'toma_inicio_at' => $r['toma_inicio_at'], 'turno_codigo' => $r['turno_codigo'], 'turno_fecha' => $r['turno_fecha'], 'tomas_firmadas' => $firmasHechas, 'tomas_total' => $totalFirmas, ]; } jsonOk(['tomas' => $tomas]);