import 'package:flutter_bloc/flutter_bloc.dart'; import '../../../core/api/api_exception.dart'; import '../../../core/api/api_failure.dart'; import '../data/driver_repository.dart'; import 'onboarding_state.dart'; /// تسجيل السائق حتى الاعتماد. /// /// **الخطوة تُشتقّ من حالة الخادم لا من تقدّم محلّي**: سائق يعيد تثبيت /// التطبيق يجب أن يعود إلى حيث وقف، لا أن يبدأ من الصفر. class OnboardingCubit extends Cubit { OnboardingCubit(this._repo) : super(const OnboardingState()); final DriverRepository _repo; Future load() async { emit(state.copyWith(step: OnboardingStep.loading, clearFailure: true)); try { final driver = await _repo.me(); if (isClosed) return; if (driver == null) { emit(state.copyWith(step: OnboardingStep.apply, driver: null)); return; } if (driver.isApproved) { emit(state.copyWith(step: OnboardingStep.approved, driver: driver)); return; } // الملف ناقص ما لم يُدخل الاسم العربي — أول ما يطلبه الخادم. if (driver.nameArabic == null || driver.nameArabic!.isEmpty) { emit(state.copyWith(step: OnboardingStep.profile, driver: driver)); return; } final vehicles = await _repo.vehicles(); if (isClosed) return; if (vehicles.isEmpty) { emit(state.copyWith( step: OnboardingStep.vehicle, driver: driver, vehicles: vehicles, )); return; } final reqs = await _repo.requirements(); if (isClosed) return; emit(state.copyWith( // اكتملت الوثائق ولم يُعتمد بعد: مراجعة بشرية جارية. step: reqs.complete ? OnboardingStep.pending : OnboardingStep.documents, driver: driver, vehicles: vehicles, requirements: reqs.items, )); } on ApiException catch (e) { if (!isClosed) { emit(state.copyWith( step: OnboardingStep.apply, failure: e.toApiFailure(), )); } } } Future apply({required String vehicleMake, required String serviceClass}) => _run(() => _repo.apply(vehicleMake: vehicleMake, serviceClass: serviceClass)); Future saveProfile({ required String nameArabic, required String nationalNumber, String? gender, }) => _run(() => _repo.setProfile( nameArabic: nameArabic, nationalNumber: nationalNumber, gender: gender, )); Future addVehicle({ required String make, required String model, required int year, required String color, required String plate, }) => _run(() => _repo.addVehicle( make: make, model: model, year: year, color: color, plate: plate, )); Future uploadDocument({ required String filePath, required String type, required String side, }) => _run(() => _repo.uploadDocument( filePath: filePath, type: type, side: side, )); /// كل فعل ينتهي بإعادة قراءة الحالة من الخادم — فلا يتقدّم التطبيق خطوةً /// لم يقبلها الخادم فعلاً. Future _run(Future Function() action) async { emit(state.copyWith(busy: true, clearFailure: true)); try { await action(); if (isClosed) return; emit(state.copyWith(busy: false)); await load(); } on ApiException catch (e) { if (!isClosed) { emit(state.copyWith(busy: false, failure: e.toApiFailure())); } } } }