where('mobile', $request->mobile) ->firstOr(function () use ($request) { return User::create([ 'name' => 'Law', 'mobile' => $request->mobile, 'email' => 'law'.$request->mobile.'@law.com', 'password' => Hash::make($request->mobile), ]); }); $code = random_int(1000, 9999); UserCode::create([ 'user_id' => $user->id, 'code' => $code, 'expired_at' => Carbon::now()->addMinutes(10), ]); $url = 'https://api.sms.ir/v1/send/verify'; $payload = [ 'mobile' => $request->mobile, 'templateId' => '383927', 'parameters' => [ [ 'name' => 'CODE', 'value' => strval($code), ], ], ]; $response = Http::withHeaders([ 'Content-Type' => 'application/json', 'Accept' => 'text/plain', 'x-api-key' => 'VNXiXc1ERkFUwifxfYFzOIOCjNow9E8as1NpUE5EtkDkaWUlmC09nGxJCFX3kSqD', ]) ->post('https://api.sms.ir/v1/send/verify', $payload); if ($response->successful()) { return $this->success([], 'موفق', 'کد ورود به شماره موبایل شما ارسال شد'); } else { return $this->failed([], [ 'title' => 'نا موفق', 'message' => 'در ارسال کد به شماره شما مشکلی وجود دارد', ]); } } public function verify(Request $request) { $request->validate([ 'mobile' => 'required', 'code' => 'required', ]); $user = User::where('mobile', $request->mobile)->first(); if (! $user) { return response()->json(['error' => 'کاربر یافت نشد'], 404); } $latestCode = UserCode::where('user_id', $user->id) ->where('code', $request->code) ->latest() ->first(); if (! $latestCode) { return $this->failed([], 'کد ورود اشتباه است', 404); } if ($latestCode->code === $request->code) { $token = $user->createToken('mobile')->plainTextToken; // --- NEW: AUTOMATIC FREE SUBSCRIPTION LOGIC --- // 1. Check if they have ever used a free plan before $hasUsedFreePlan = $user->userSubscribers() ->whereHas('subscribe', function ($query) { $query->where('is_free', true); })->exists(); // 2. If not, find the active free plan and assign it if (!$hasUsedFreePlan) { $freePlan = SubscribePlan::where('is_free', true)->where('is_active', true)->first(); if ($freePlan) { $user->userSubscribers()->create([ 'subscribe_plan_id' => $freePlan->id, 'expired_at' => now()->addDays($freePlan->expired_day + 1), // Using your existing +1 logic 'is_free' => true, ]); } } // ---------------------------------------------- return $this->success(['token' => $token], 'ورود موفقیت امیز بود'); } else { return $this->failed([], 'کد ورود اشتباه است', 404); } } }