import 'package:bloc/bloc.dart'; import 'package:flutter/material.dart'; import 'package:kmobile/api/services/user_service.dart'; import 'package:kmobile/core/errors/exceptions.dart'; import 'package:kmobile/data/models/user.dart'; import 'package:kmobile/features/auth/models/auth_token.dart'; import 'package:kmobile/security/secure_storage.dart'; import '../../../data/repositories/auth_repository.dart'; import 'auth_state.dart'; class AuthCubit extends Cubit { final AuthRepository _authRepository; final UserService _userService; final SecureStorage _secureStorage; AuthCubit(this._authRepository, this._userService, this._secureStorage) : super(AuthInitial()) { checkAuthStatus(); } Future checkAuthStatus() async { emit(AuthLoading()); try { final isLoggedIn = await _authRepository.isLoggedIn(); if (isLoggedIn) { final users = await _userService.getUserDetails(); emit(Authenticated(users)); } else { emit(Unauthenticated()); } } catch (e) { emit(AuthError(e.toString())); } } Future refreshUserData() async { try { final users = await _userService.getUserDetails(); emit(Authenticated(users)); } catch (e) { emit(AuthError('Failed to refresh user data: ${e.toString()}')); } } Future login(String customerNo, String password) async { emit(AuthLoading()); try { final (users, authToken) = await _authRepository.login(customerNo, password); if (authToken.tnc == false) { // TNC not accepted, tell UI to show the dialog emit(ShowTncDialog(authToken, users)); } else { // TNC already accepted, emit Authenticated and then proceed to MPIN check emit(Authenticated(users)); await _checkMpinAndNavigate(); } } catch (e) { emit(AuthError(e is AuthException ? e.message : e.toString())); } } Future onTncDialogResult( bool agreed, AuthToken authToken, List users) async { if (agreed) { try { await _authRepository.acceptTnc(); // User agreed, emit Authenticated and then proceed to MPIN check emit(Authenticated(users)); await _checkMpinAndNavigate(); } catch (e) { emit(AuthError('Failed to accept TNC: $e')); } } else { // User disagreed, tell UI to navigate to the required screen emit(NavigateToTncRequiredScreen()); } } Future _checkMpinAndNavigate() async { final mpin = await _secureStorage.read('mpin'); if (mpin == null) { // No MPIN, tell UI to navigate to MPIN setup emit(NavigateToMpinSetupScreen()); } else { // MPIN exists, tell UI to navigate to the dashboard emit(NavigateToDashboardScreen()); } } }