function generarTicket(Request $request) { $ordenId = $request->query('orden_id'); if (!$ordenId) { return response()->json(['success' => false, 'message' => 'Orden ID requerido'], 400); } try { \Illuminate\Support\Facades\Log::info("📄 [Ticket/Generar] Iniciando para Orden: " . $ordenId); // 0. Obtener la orden base $ordenBase = \Illuminate\Support\Facades\DB::table('Ventas_Ordenes')->where('id_ordenes', $ordenId)->first(); if (!$ordenBase) { return response()->json(['success' => false, 'message' => 'Orden base no encontrada'], 404); } // 1. ¿Ya existe un comprobante real? Intentar sacar los datos de ahí (Snapshot del cliente) $comprobanteReal = \Illuminate\Support\Facades\DB::table('Facturacion_Comprobantes') ->where('orden_id', $ordenId) ->orderBy('fecha_emision', 'desc') ->first(); $mappedCliente = [ 'tipo_documento' => '1', 'numero_documento' => '00000000', 'razon_social' => 'CLIENTE VARIOS', 'direccion' => null ]; if ($comprobanteReal && $comprobanteReal->cliente_snapshot_id) { $snapshot = \Illuminate\Support\Facades\DB::table('Facturacion_Clientes_Snapshot') ->where('id', $comprobanteReal->cliente_snapshot_id) ->first(); if ($snapshot) { $mappedCliente = [ 'tipo_documento' => (string) ($snapshot->tipo_documento_id ?? '1'), 'numero_documento' => $snapshot->documento_numero ?? '00000000', 'razon_social' => $snapshot->razon_social ?? 'CLIENTE VARIOS', 'direccion' => $snapshot->direccion ]; } } else { // FALLBACK: Buscar en Notificaciones (Solicitud de Pago) por si hay datos ahí try { $notificacion = \Illuminate\Support\Facades\DB::table('Comunicaciones_Notificaciones') ->where('sucursal_id', $ordenBase->sucursal_id) ->where(function ($q) use ($ordenId, $ordenBase) { $q->where('data', 'LIKE', "%$ordenId%") ->orWhere('data', 'LIKE', "%{$ordenBase->recurso_id}%"); }) ->whereIn('tipo', ['solicitud_pago_pos', 'solicitud_pago_efectivo', 'pago_tarjeta_pos', 'pago_efectivo']) ->orderBy('fecha', 'desc') ->first(); if ($notificacion) { $notifData = json_decode($notificacion->data, true); $billingData = $notifData['comprobante_datos'] ?? $notifData['payload']['comprobante_datos'] ?? null;