import 'package:flutter_bloc/flutter_bloc.dart'; import '../../data/auth_repository.dart'; import 'auth_state.dart'; // English: AuthCubit manages authentication states. // Arabic: يدير ملف الكيوبيت حالات المصادقة للمستخدمين. // // English: In GetX, you would use a GetxController and update observable variables. // Arabic: في غيت إكس، كنت ستستخدم وحدة التحكم وتحدث المتغيرات المرصودة. // // English: In Bloc/Cubit, you inherit from Cubit and emit new immutable states. // Arabic: في بلوك أو كيوبيت، ترث من الكيوبيت وترسل حالات غير قابلة للتعديل. class AuthCubit extends Cubit { final AuthRepository _authRepository; // English: Constructor initializing the Cubit with the AuthInitial state. // Arabic: منشئ يقوم بتهيئة الكيوبيت بالحالة الأولية. AuthCubit(this._authRepository) : super(const AuthInitial()); // English: Check if the user is already authenticated on app launch. // Arabic: التحقق مما إذا كان المستخدم مصدقًا عليه بالفعل عند تشغيل التطبيق. Future checkAuthStatus() async { // English: Emit loading state while reading storage. // Arabic: إرسال حالة التحميل أثناء قراءة وحدة التخزين. emit(const AuthLoading()); try { final user = await _authRepository.getCachedUser(); if (user != null) { // English: Emit Authenticated state if user exists. // Arabic: إرسال حالة مصادق عليه إذا كان المستخدم موجودًا. emit(Authenticated(user)); } else { // English: Emit Unauthenticated if no cached token is found. // Arabic: إرسال حالة غير مصادق عليه في حال لم يتم العثور على رمز مخزن مؤقتًا. emit(const Unauthenticated()); } } catch (e) { // English: Fail check, treat as unauthenticated. // Arabic: فشل التحقق، يتم اعتباره غير مصادق عليه. emit(const Unauthenticated()); } } // English: Perform login request using email and password. // Arabic: إجراء طلب تسجيل الدخول باستخدام البريد الإلكتروني وكلمة المرور. Future login(String email, String password) async { // English: Validate input locally before hitting the server. // Arabic: التحقق من صحة المدخلات محليًا قبل الاتصال بالخادم. if (email.isEmpty || password.isEmpty) { emit(const AuthFailure('الرجاء إدخال جميع الحقول بشكل صحيح')); return; } emit(const AuthLoading()); try { final user = await _authRepository.login(email, password); // English: Emit Authenticated state with user profile on success. // Arabic: إرسال حالة مصادق عليه مع ملف تعريف المستخدم عند النجاح. emit(Authenticated(user)); } catch (e) { // English: Clean the error message to display to the user. // Arabic: تنظيف رسالة الخطأ لعرضها على المستخدم. final cleanError = e.toString().replaceAll('Exception: ', ''); emit(AuthFailure(cleanError)); } } // English: Clear user token and log out. // Arabic: مسح رمز المستخدم وتسجيل الخروج. Future logout() async { emit(const AuthLoading()); await _authRepository.logout(); // English: Emit Unauthenticated state to return user to login screen. // Arabic: إرسال حالة غير مصادق عليه لإرجاع المستخدم إلى شاشة تسجيل الدخول. emit(const Unauthenticated()); } }