validate([ 'message' => ['required', 'string', 'max:2000'], 'history' => ['nullable', 'array', 'max:20'], 'history.*.role' => ['nullable', 'string'], 'history.*.text' => ['nullable', 'string'], ]); if (! $afia->enabled()) { return response()->json(['message' => 'Afia is not available right now.'], 503); } try { $reply = $afia->chat(trim($validated['message']), $validated['history'] ?? [], $this->context($request)); } catch (\Throwable $e) { report($e); return response()->json(['message' => 'Afia could not respond right now. Please try again.'], 502); } return response()->json(['reply' => $reply]); } /** @return array */ private function context(Request $request): array { $user = $this->accountUser($request); $store = $this->currentStore($request); $storeIds = WooStore::query()->where('user_id', $user->id)->pluck('id'); return [ 'signed_in' => 'yes', 'plan' => $this->subscriptions->hasPaidPlan($user) ? 'paid' : 'free', 'connected_stores' => WooStore::query()->where('user_id', $user->id)->where('status', WooStore::STATUS_ACTIVE)->count(), 'active_store' => $store?->site_name ?? $store?->site_url ?? 'none selected', 'products_total' => WooProduct::query()->whereIn('woo_store_id', $storeIds)->count(), 'orders_new' => $store ? WooOrder::query()->where('woo_store_id', $store->id)->where('fulfillment_status', WooOrder::FULFILLMENT_NEW)->count() : 0, ]; } }