prepare( "SELECT tlc.formulario_id FROM turnero_lugar_consentimientos tlc JOIN lab_formularios f ON f.id = tlc.formulario_id AND f.is_active = 1 WHERE tlc.lugar_id = ? ORDER BY tlc.formulario_id ASC LIMIT 1" ); $formRow->execute([$lugarId]); $form = $formRow->fetch(PDO::FETCH_ASSOC); if (!$form) jsonError('No hay formulario configurado para este lugar', 404); $formularioId = (int)$form['formulario_id']; // Buscar token existente $existing = $pdo->prepare( "SELECT token FROM turnero_consentimientos WHERE turno_id = ? AND formulario_id = ? LIMIT 1" ); $existing->execute([$turnoId, $formularioId]); $row = $existing->fetch(PDO::FETCH_ASSOC); if ($row) { jsonOk(['token' => $row['token'], 'nuevo' => false]); } // Crear nuevo token $token = sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0,0xffff), mt_rand(0,0xffff), mt_rand(0,0xffff), mt_rand(0,0x0fff)|0x4000, mt_rand(0,0x3fff)|0x8000, mt_rand(0,0xffff), mt_rand(0,0xffff), mt_rand(0,0xffff) ); $pdo->prepare( "INSERT IGNORE INTO turnero_consentimientos (turno_id, formulario_id, token, estado, creado_por) VALUES (?, ?, ?, 'pendiente', ?)" )->execute([$turnoId, $formularioId, $token, adminId()]); jsonOk(['token' => $token, 'nuevo' => true]);