diff --git a/lib/presentation/routes/auth_routes/login_route.dart b/lib/presentation/routes/auth_routes/login_route.dart index 0359ab44..7e56df9f 100644 --- a/lib/presentation/routes/auth_routes/login_route.dart +++ b/lib/presentation/routes/auth_routes/login_route.dart @@ -1,10 +1,9 @@ -import 'package:excel/excel.dart'; import 'package:external_repos/external_repos.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import 'package:the_validator/the_validator.dart'; import 'package:uae_stat/config/my_theme.dart'; import 'package:uae_stat/domain/use_cases/auth_use_case.dart'; @@ -19,746 +18,329 @@ import 'package:uae_stat/presentation/components/space.dart'; import 'package:uae_stat/presentation/components/themed_text_field.dart'; import 'package:uae_stat/presentation/routes/bottom_bar_routes/tab_routes/home_route.dart'; -import '../../Screens/profilepage.dart'; import '../../Screens/auth_verification/registration.dart'; import 'package:pocketbase/pocketbase.dart'; -// class LoginRoute extends HookConsumerWidget { -// final pb = PocketBase('https://pb.venbait.in'); -// // final _pb = PocketBase('http://127.0.0.1:8090'); -// LoginRoute({super.key}); -// -// static final formKey = GlobalKey(); -// -// Future profileStatus(String userId) async { -// try { -// // Authenticate admin -// final adminAuth = await pb.admins.authWithPassword( -// 'pb@venbainfotech.com', -// 'pb@venbainfotech.com', -// ); -// final String adminToken = adminAuth.token; -// print('adminToken: $adminToken'); -// -// // Fetch user details -// final userDetailsResponse = await pb.collection('users').getOne( -// userId, -// headers: { -// 'Authorization': 'Bearer $adminToken', -// }, -// ); -// print('userDetailsLogin: $userDetailsResponse'); -// -// // Check if 'is_profile_completed' is true or false -// if (userDetailsResponse != null && -// userDetailsResponse.data['is_profile_completed'] != null) { -// return userDetailsResponse.data['is_profile_completed']; -// } else { -// return false; // Default to false if the field is missing or response is null -// } -// } catch (e) { -// print('Error fetching user details: $e'); -// return false; // Return false on error -// } -// } -// -// @override -// Widget build(BuildContext context, WidgetRef ref) { -// final emailCtl = useTextEditingController(); -// final pwCtl = useTextEditingController(); -// final forgotPwBtn = TextButton( -// onPressed: () async { -// final forgotPwFormKey = GlobalKey(); -// final email = await showDialog( -// context: context, -// builder: (dialogCtx) => AlertDialog( -// title: Text( -// context.translate( -// 'Reset Password', -// 'إعادة تعيين كلمة المرور', -// ), -// ), -// content: Form( -// key: forgotPwFormKey, -// child: TextFormField( -// validator: FieldValidator.email(), -// controller: emailCtl, -// decoration: InputDecoration( -// labelText: context.translate( -// 'Email address', -// 'عنوان البريد الإلكتروني', -// ), -// ), -// ), -// ), -// actions: [ -// TextButton( -// onPressed: Navigator.of(dialogCtx, rootNavigator: true).pop, -// child: Text( -// context.translate( -// 'Return', -// 'يعود', -// ), -// ), -// ), -// ElevatedButton( -// onPressed: () { -// final isValid = forgotPwFormKey.currentState!.validate(); -// if (!isValid) return; -// Navigator.of(dialogCtx, rootNavigator: true).pop( -// emailCtl.text, -// ); -// }, -// child: Text( -// context.translate( -// 'Send Reset Email', -// 'إرسال إعادة تعيين البريد الإلكتروني', -// ), -// ), -// ), -// ], -// ), -// ); -// if (email == null) return; -// if (!context.mounted) return; -// await context.loaderWithErrorDialog( -// () => ref -// .read( -// authUseCaseProvider.notifier, -// ) -// .requestPwReset(email), -// ); -// if (!context.mounted) return; -// context.simpleDialog( -// title: context.translate( -// 'Success!', -// 'نجاح', -// ), -// content: context.translate( -// 'An email has been sent to $email with further details.', -// 'تم إرسال بريد إلكتروني إلى $email يتضمن المزيد من التفاصيل.', -// ), -// ); -// }, -// child: Text( -// context.translate( -// 'Forgot Password?', -// 'هل نسيت كلمة السر؟', -// ), -// style: TextStyle( -// fontFamily: context.translate( -// 'Roboto', -// 'NotoKufi', -// ), -// fontWeight: FontWeight.bold, -// fontSize: 14, -// color: MyTheme.topicColor(IndicatorTopic.economy).shade600, -// ), -// ), -// ); -// final loginBtn = SizedBox( -// width: double.infinity, -// child: ElevatedButton( -// onPressed: () { -// context.go('/profile'); -// }, -// // async { -// // final isValid = formKey.currentState!.validate(); -// // if (!isValid) return; -// // final session = await context.loaderWithErrorDialog( -// // () => ref -// // .read( -// // authUseCaseProvider.notifier, -// // ) -// // .login( -// // emailCtl.text, -// // pwCtl.text, -// // ), -// // errorDialogBuilder: ( -// // error, [ -// // StackTrace? stackTrace, -// // ]) { -// // if (error == LoginError.invalidEmailPw) { -// // return context.simpleDialog( -// // title: context.translate( -// // 'Incorrect credentials', -// // 'أوراق غير صحيحة', -// // ), -// // content: context.translate( -// // 'Your email or password is invalid. Please try again.', -// // 'بريدك الإلكتروني أو كلمة المرور غير صالحة. حاول مرة اخرى.', -// // ), -// // ); -// // } -// // if (error == LoginError.emailAddressNotVerified) { -// // return context.simpleDialog( -// // title: context.translate( -// // 'Verification Error', -// // 'خطأ التحقق', -// // ), -// // content: context.translate( -// // '${emailCtl.text} is not a verified email address. Please check your email for a verification link.', -// // '${emailCtl.text} ليس عنوان بريد إلكتروني تم التحقق منه. يرجى التحقق من بريدك الإلكتروني للحصول على رابط التحقق.', -// // ), -// // extraAction: ElevatedButton( -// // onPressed: () { -// // context.go('/profile'); -// // }, -// // // async { -// // // Navigator.of( -// // // context, -// // // rootNavigator: true, -// // // ).pop(); -// // // await context.loaderWithErrorDialog( -// // // () => ref -// // // .read(authUseCaseProvider.notifier) -// // // .requestVerificationEmail(emailCtl.text), -// // // ); -// // // if (!context.mounted) return; -// // // context.simpleDialog( -// // // title: 'Email Re-sent', -// // // content: -// // // 'We\'ve sent you the verification email at ${emailCtl.text} again.', -// // // ); -// // // }, -// // child: Text( -// // context.translate( -// // 'I did not receive an email', -// // 'لم أتلق بريدًا إلكترونيًا', -// // ), -// // ), -// // ), -// // ); -// // } -// // return context.simpleDialog(); -// // }, -// // ); -// // // if (!context.mounted || session == null) return; -// // // Extract userId from the session -// // // final userId = session.id; -// // // -// // // final bool isUpdate = await profileStatus(userId); -// // // -// // // print('Is profile completed: $isUpdate'); -// // -// // // if (isUpdate) { -// // // Navigator.pushReplacement( -// // // context, -// // // MaterialPageRoute(builder: (context) => DemoHome()), -// // // ); -// // // } -// // // else { -// // -// // // Navigator.pushReplacement( -// // // context, -// // // MaterialPageRoute( -// // // builder: (context) => ProfileScreen(userId: userId)), -// // // ); -// // //} -// // -// // // context.go('/${context.language}/${BottomNavBarItem.home.routePath}'); -// // }, -// style: ButtonStyle( -// shape: WidgetStatePropertyAll( -// RoundedRectangleBorder( -// borderRadius: BorderRadius.circular(10), -// ), -// ), -// padding: const WidgetStatePropertyAll( -// EdgeInsets.symmetric(vertical: 10.5), -// ), -// textStyle: WidgetStatePropertyAll( -// TextStyle( -// fontFamily: context.translate( -// 'Roboto', -// 'NotoKufi', -// ), -// fontSize: 16, -// fontWeight: FontWeight.w600, -// ), -// ), -// backgroundColor: WidgetStatePropertyAll( -// MyTheme.topicColor(IndicatorTopic.social), -// ), -// // surfaceTintColor: MaterialStatePropertyAll( -// // MyTheme.economy[800], -// // ), -// foregroundColor: const WidgetStatePropertyAll( -// Colors.white, -// ), -// ), -// child: Row( -// mainAxisAlignment: MainAxisAlignment.center, -// children: [ -// Text( -// context.translate( -// 'Login', -// 'تسجيل الدخول', -// ), -// ), -// 6.horizontalSpace, -// const Icon(Icons.chevron_right_outlined), -// ], -// ), -// ), -// ); -// final form = Form( -// key: formKey, -// child: Column( -// children: [ -// ThemedFormField( -// hintText: context.translate( -// 'Email', -// 'بريد إلكتروني', -// ), -// validator: FieldValidator.email(), -// imgPath: MiscIconAssetPath.person, -// controller: emailCtl, -// ), -// 15.verticalSpace, -// ThemedFormField( -// validator: (text) { -// if (text!.length < 10) { -// return 'The password must be at least 10 characters'; -// } -// return FieldValidator.password(minLength: 10)(text); -// }, -// hintText: context.translate( -// 'Password', -// 'كلمة المرور', -// ), -// imgPath: MiscIconAssetPath.lock, -// controller: pwCtl, -// isObscurable: true, -// ), -// // 6.verticalSpace, -// Align( -// alignment: AlignmentDirectional.topEnd, -// child: forgotPwBtn, -// ), -// 10.verticalSpace, -// loginBtn, -// ], -// ), -// ); -// final helloAndPleaseLoginTexts = Column( -// children: [ -// Text( -// context.translate( -// 'Hello Again!', -// 'مرحبا مجددا!', -// ), -// style: TextStyle( -// fontFamily: context.translate( -// 'Roboto', -// 'NotoKufi', -// ), -// fontSize: 40, -// fontWeight: FontWeight.w300, -// ), -// ), -// 10.verticalSpace, -// Text( -// context.translate( -// 'Please login to access UAE’s key official statistics', -// 'يرجى تسجيل الدخول للوصول إلى الإحصاءات الرسمية الرئيسية لدولة الإمارات العربية المتحدة', -// ), -// textAlign: TextAlign.center, -// style: TextStyle( -// fontFamily: context.translate( -// 'Roboto', -// 'NotoKufi', -// ), -// fontSize: 18, -// color: const Color(0xff898C81), -// fontWeight: FontWeight.w700, -// ), -// ), -// ], -// ); -// final dontHaveAnAccountRegisterBtn = TextButton( -// onPressed: () => { -// Navigator.push( -// context, -// MaterialPageRoute(builder: (context) => RegisterScreen()), -// ), -// }, -// child: Text.rich( -// textAlign: TextAlign.center, -// TextSpan( -// style: TextStyle( -// fontFamily: context.translate( -// 'Roboto', -// 'NotoKufi', -// ), -// fontSize: 18, -// fontWeight: FontWeight.bold, -// ), -// children: [ -// TextSpan( -// text: context.translate( -// 'Don\'t have an account? ', -// 'ليس لديك حساب؟', -// ), -// style: const TextStyle( -// color: Color(0xff898C81), -// ), -// ), -// const TextSpan( -// text: ' ', -// ), -// TextSpan( -// text: context.translate( -// 'Register Now', -// 'سجل الان', -// ), -// style: TextStyle( -// color: MyTheme.topicColor(IndicatorTopic.economy).shade600, -// ), -// ), -// ], -// ), -// ), -// ); -// final continueAsGuestBtn = SizedBox( -// width: double.infinity, -// child: ElevatedButton( -// onPressed: () => context -// .go('/${context.language}/${BottomNavBarItem.home.routePath}'), -// style: ButtonStyle( -// shape: WidgetStatePropertyAll( -// RoundedRectangleBorder( -// borderRadius: BorderRadius.circular(10), -// ), -// ), -// padding: const WidgetStatePropertyAll( -// EdgeInsets.symmetric(vertical: 10.5), -// ), -// textStyle: WidgetStatePropertyAll( -// TextStyle( -// fontFamily: context.translate( -// 'Roboto', -// 'NotoKufi', -// ), -// fontSize: 16, -// fontWeight: FontWeight.w600, -// ), -// ), -// backgroundColor: WidgetStatePropertyAll( -// MyTheme.topicColor(IndicatorTopic.environment), -// ), -// foregroundColor: const WidgetStatePropertyAll( -// Colors.white, -// ), -// ), -// child: Row( -// mainAxisAlignment: MainAxisAlignment.center, -// children: [ -// Text( -// context.translate( -// 'Continue as Guest', -// 'استمر كضيف', -// ), -// ), -// 6.horizontalSpace, -// const Icon(Icons.chevron_right_outlined), -// ], -// ), -// ), -// ); -// final fcscBanner = Image.asset( -// BannerAssetPath.fcsc, -// height: 56, -// ); -// final screenWidth = MediaQuery.of(context).size.width; -// final listViewHorizontalPadding = -// screenWidth < 700 ? 30 : 30 + (screenWidth - 700) / 2; -// final scaffoldBody = ListView( -// padding: EdgeInsets.symmetric( -// horizontal: listViewHorizontalPadding.toDouble(), -// ), -// children: [ -// 36.verticalSpace, -// const Align( -// alignment: AlignmentDirectional.topEnd, -// child: LangToggle(), -// ), -// 16.verticalSpace, -// helloAndPleaseLoginTexts, -// 42.verticalSpace, -// form, -// 20.verticalSpace, -// dontHaveAnAccountRegisterBtn, -// 36.verticalSpace, -// continueAsGuestBtn, -// 72.verticalSpace, -// fcscBanner, -// ], -// ); -// final bgScaffold = Scaffold( -// backgroundColor: Colors.white, -// body: SafeArea(child: scaffoldBody), -// ); -// return bgScaffold; -// } -// } +class LoginRoute extends HookConsumerWidget { + final pb = PocketBase('https://pb.venbait.in'); + // final _pb = PocketBase('http://127.0.0.1:8090'); + LoginRoute({super.key}); + dynamic userData; + String? role; -class LoginRoute extends StatefulWidget { - const LoginRoute({super.key}); + static final formKey = GlobalKey(); + + Future profileStatus(String userId) async { + try { + // Authenticate admin + final adminAuth = await pb.admins.authWithPassword( + 'pb@venbainfotech.com', + 'pb@venbainfotech.com', + ); + final String adminToken = adminAuth.token; + print('adminToken: $adminToken'); + + // Fetch user details + final userDetailsResponse = await pb.collection('users').getOne( + userId, + headers: { + 'Authorization': 'Bearer $adminToken', + }, + ); + + print('userDetailsLogin: $userDetailsResponse'); + + // Check if user is verified + role = userDetailsResponse.data['role']; + final bool? isVerified = userDetailsResponse.data['verified']; + final bool? isUserMailVerified = + userDetailsResponse.data['user_mail_verify']; + + // Check admin and email verification statuses + if (isVerified == false) { + throw Exception('Admin not approved'); + } + if (isUserMailVerified == false) { + throw Exception('Email not verified'); + } + userData = userDetailsResponse; + // Check if 'is_profile_completed' is true + final bool isProfileCompleted = + userDetailsResponse.data['is_profile_completed'] ?? false; + + return isProfileCompleted; + } catch (e) { + print('Error fetching user details: $e'); + rethrow; + } + } + + Future saveUserId(String userId) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('userId', userId); // Save userId locally + } @override - State createState() => _LoginRouteState(); -} - -class _LoginRouteState extends State { - final _formKey = GlobalKey(); - bool _obscurePassword = true; - @override - Widget build(BuildContext context) { - double screenheight = MediaQuery - .of(context) - .size - .height; - double screenwidth = MediaQuery - .of(context) - .size - .width; - return Scaffold( - body: Padding( - padding: const EdgeInsets.all(20.0), - child: Form( - key: _formKey, - child: SingleChildScrollView( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - SizedBox(height: screenheight / 6), - Text( - 'Hello Again !', - style: TextStyle( - fontSize: 32, fontWeight: FontWeight.w400), - ), - SizedBox(height: 5), - Text('Please login to access', style: TextStyle( - fontFamily: context.translate( - 'Roboto', - 'NotoKufi', - ), - color: Color(0xFF898C81), - fontSize: 18, fontWeight: FontWeight.bold),), - Text("UAE's key official statistics", style: TextStyle( - fontFamily: context.translate( - 'Roboto', - 'NotoKufi', - ), - color: Color(0xFF898C81), - fontSize: 16, fontWeight: FontWeight.bold),), - - SizedBox(height: 10), - // Display this if registration is pending approval - TextFormField( - // controller: _usernameController, - // focusNode: _focusNodes[0], - decoration: InputDecoration( - hintText: "Username", - //hintText: _showHints[0] ? 'Username' : null, - prefixIcon: Image.asset( - "assets/icons/misc/person.png", scale: 2, - color: Colors.lightBlueAccent,), - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(15)), - focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(10), - borderSide: BorderSide(color: Colors.blue.shade900,) - ), - enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(10), - // Keep rounded corners - borderSide: BorderSide( - color: Colors.blue, // Default border color - width: 1.0, // Border width when not focused - ), - ), - counterText: '', - ), - //validator: _validateUsername, - maxLength: - 40, // Set the maximum length to 20 characters - //maxLengthEnforcement: MaxLengthEnforcement.enforced, - ), - SizedBox(height: 20), - TextFormField( - // controller: _passwordController, - // focusNode: _focusNodes[2], - // obscureText: _obscurePassword, - decoration: InputDecoration( - hintText: "Password", - // hintText: _showHints[2] ? 'Enter your password' : null, - prefixIcon: Image.asset( - "assets/icons/misc/lock.png", scale: 2, - color: Colors.lightBlueAccent,), - suffixIcon: IconButton( - icon: Icon( - _obscurePassword - ? Icons.visibility - : Icons.visibility_off, - color: Colors.grey, - ), - onPressed: () { - setState(() { - _obscurePassword = !_obscurePassword; - }); - }, - ), - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(15)), - focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(10), - borderSide: BorderSide(color: Colors.blue.shade900,), - - ), - enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(10), - // Keep rounded corners - borderSide: BorderSide( - color: Colors.blue, // Default border color - width: 1.0, // Border width when not focused - ), - ), - counterText: '', - ), - //validator: _validatePassword, - maxLength: 40, - maxLengthEnforcement: MaxLengthEnforcement.enforced, - ), - - SizedBox(height: 10), - Row(mainAxisAlignment: MainAxisAlignment.end, - children: [Text("Forgot Password?", - style: TextStyle( - color: Color(0xFF985400), fontWeight: FontWeight.bold - ),) - ],), - SizedBox(height: 20), - SizedBox( - width: screenwidth, - child: ElevatedButton( - onPressed: () { - context.go('/profile'); - }, - //_registerUser, - style: ElevatedButton.styleFrom( - backgroundColor: Color( - 0xFFA7887A), // Brownish color for Register - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - ), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - "Login", - style: TextStyle( - fontSize: 16, color: Colors.white), - ), - SizedBox(width: 8), - Icon(Icons.arrow_forward_ios, - color: Colors.white, - size: 10, - ), - ], - ), - ), - ), - SizedBox(height: screenheight / 20), - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - "Don't have an account? ", - style: TextStyle( - fontFamily: context.translate( - 'Roboto', - 'NotoKufi', - ), - color: Color(0xFF898C81), - fontSize: 18, fontWeight: FontWeight.bold), - ), - InkWell( - onTap: () { - context.go('/registration'); - }, - child: Text( - " Register Now", - style: TextStyle( - fontFamily: context.translate( - 'Roboto', - 'NotoKufi', - ), - color: Color(0xFF985400), - fontSize: 18, fontWeight: FontWeight.bold), - ), - ), - ],), - - SizedBox( - height: screenheight / 20, - ), - SizedBox( - width: screenwidth, - child: ElevatedButton( - onPressed: () { - context.go('/myhomepage'); - }, - style: ElevatedButton.styleFrom( - backgroundColor: Color( - 0xFF82AFCB), // Blueish color for Login - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - ), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - "Continue as guest", - style: TextStyle( - fontSize: 16, - color: Colors.white, - ), - ), - SizedBox(width: 8), - Icon(Icons.arrow_forward_ios, - color: Colors.white, size: 10,), - ], - ), - ), - ), - SizedBox( - height: screenheight / 15, - ), - Center( - child: Container( - height: screenheight / 13, - width: screenwidth / 3, - decoration: BoxDecoration( - image: DecorationImage( - image: AssetImage( - "assets/splash_screen/logo.png"), - // Background image asset - fit: BoxFit.fill, - ), - ), - )) - ], + Widget build(BuildContext context, WidgetRef ref) { + final emailCtl = useTextEditingController(); + final pwCtl = useTextEditingController(); + final forgotPwBtn = TextButton( + onPressed: () async { + final forgotPwFormKey = GlobalKey(); + final email = await showDialog( + context: context, + builder: (dialogCtx) => AlertDialog( + title: Text( + context.translate( + 'Reset Password', + 'إعادة تعيين كلمة المرور', + ), ), + content: Form( + key: forgotPwFormKey, + child: TextFormField( + validator: FieldValidator.email(), + controller: emailCtl, + decoration: InputDecoration( + labelText: context.translate( + 'Email address', + 'عنوان البريد الإلكتروني', + ), + ), + ), + ), + actions: [ + TextButton( + onPressed: Navigator.of(dialogCtx, rootNavigator: true).pop, + child: Text( + context.translate( + 'Return', + 'يعود', + ), + ), + ), + ElevatedButton( + onPressed: () { + final isValid = forgotPwFormKey.currentState!.validate(); + if (!isValid) return; + Navigator.of(dialogCtx, rootNavigator: true).pop( + emailCtl.text, + ); + }, + child: Text( + context.translate( + 'Send Reset Email', + 'إرسال إعادة تعيين البريد الإلكتروني', + ), + ), + ), + ], ), + ); + if (email == null) return; + if (!context.mounted) return; + await context.loaderWithErrorDialog( + () => ref + .read( + authUseCaseProvider.notifier, + ) + .requestPwReset(email), + ); + if (!context.mounted) return; + context.simpleDialog( + title: context.translate( + 'Success!', + 'نجاح', + ), + content: context.translate( + 'An email has been sent to $email with further details.', + 'تم إرسال بريد إلكتروني إلى $email يتضمن المزيد من التفاصيل.', + ), + ); + }, + child: Text( + context.translate( + 'Forgot Password?', + 'هل نسيت كلمة السر؟', + ), + style: TextStyle( + fontFamily: context.translate( + 'Roboto', + 'NotoKufi', + ), + fontWeight: FontWeight.bold, + fontSize: 14, + color: MyTheme.topicColor(IndicatorTopic.economy).shade600, ), ), ); + final loginBtn = SizedBox( + width: double.infinity, + child: ElevatedButton( + onPressed: () async { + final isValid = formKey.currentState!.validate(); + if (!isValid) return; + final session = await context.loaderWithErrorDialog( + () => ref + .read( + authUseCaseProvider.notifier, + ) + .login( + emailCtl.text, + pwCtl.text, + ), + errorDialogBuilder: ( + error, [ + StackTrace? stackTrace, + ]) { + if (error == LoginError.invalidEmailPw) { + return context.simpleDialog( + title: context.translate( + 'Incorrect credentials', + 'أوراق غير صحيحة', + ), + content: context.translate( + 'Your email or password is invalid. Please try again.', + 'بريدك الإلكتروني أو كلمة المرور غير صالحة. حاول مرة اخرى.', + ), + ); + } + // if (error == LoginError.emailAddressNotVerified) { + // return context.simpleDialog( + // title: context.translate( + // 'Verification Error', + // 'خطأ التحقق', + // ), + // content: context.translate( + // '${emailCtl.text} is not a verified email address. Please check your email for a verification link.', + // '${emailCtl.text} ليس عنوان بريد إلكتروني تم التحقق منه. يرجى التحقق من بريدك الإلكتروني للحصول على رابط التحقق.', + // ), + // extraAction: ElevatedButton( + // onPressed: () async { + // Navigator.of( + // context, + // rootNavigator: true, + // ).pop(); + // await context.loaderWithErrorDialog( + // () => ref + // .read(authUseCaseProvider.notifier) + // .requestVerificationEmail(emailCtl.text), + // ); + // if (!context.mounted) return; + // context.simpleDialog( + // title: 'Email Re-sent', + // content: + // 'We\'ve sent you the verification email at ${emailCtl.text} again.', + // ); + // }, + // child: Text( + // context.translate( + // 'I did not receive an email', + // 'لم أتلق بريدًا إلكترونيًا', + // ), + // ), + // ), + // ); + // } + return context.simpleDialog(); + }, + ); + if (!context.mounted || session == null) return; + final userId = session.id; + if (userId.isNotEmpty) { + await saveUserId(userId); + } + try { + final bool isProfileComplete = await profileStatus(userId); + print(isProfileComplete); + if (isProfileComplete) { + print('home'); + if (role == 'admin') { + context.go('/manageuser'); + } else { + context.go('/myhomepage'); + } + // context.go('/myhomepage'); + } else { + print('profile'); + if (userId != null && userId.isNotEmpty) { + context.go('/profile/$userId'); + } else { + print('Error: userId is null or empty.'); + } + } + } catch (e) { + // Handle specific errors based on their message + if (e.toString().contains('Admin not approved')) { + context.simpleDialog( + title: context.translate( + 'Admin Approval Required', 'موافقة المسؤول مطلوبة'), + content: context.translate( + 'Your account has not been approved by the admin.', + 'لم تتم الموافقة على حسابك من قبل المسؤول.', + ), + ); + } else if (e.toString().contains('Email not verified')) { + context.simpleDialog( + title: context.translate( + 'Email Not Verified', 'البريد الإلكتروني غير مُحقق'), + content: context.translate( + 'Your email address is not verified. Please check your email.', + 'عنوان بريدك الإلكتروني غير مُحقق. يرجى التحقق من بريدك الإلكتروني.', + ), + ); + } else { + print('Unexpected error: $e'); + } + } + // context.go('/${context.language}/${BottomNavBarItem.home.routePath}'); + }, + style: ButtonStyle( + shape: WidgetStatePropertyAll( + RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(vertical: 10.5), + ), + textStyle: WidgetStatePropertyAll( + TextStyle( + fontFamily: context.translate( + 'Roboto', + 'NotoKufi', + ), + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + backgroundColor: WidgetStatePropertyAll( + MyTheme.topicColor(IndicatorTopic.social), + ), + // surfaceTintColor: MaterialStatePropertyAll( + // MyTheme.economy[800], + // ), + foregroundColor: const WidgetStatePropertyAll( + Colors.white, + ), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + context.translate( + 'Login', + 'تسجيل الدخول', + ), + ), + 6.horizontalSpace, + const Icon(Icons.chevron_right_outlined), + ], + ), + ), + ); final form = Form( key: formKey, child: Column( @@ -834,12 +416,7 @@ class _LoginRouteState extends State { ], ); final dontHaveAnAccountRegisterBtn = TextButton( - onPressed: () => { - Navigator.push( - context, - MaterialPageRoute(builder: (context) => RegisterScreen()), - ), - }, + onPressed: () => {context.go('/register')}, child: Text.rich( textAlign: TextAlign.center, TextSpan( @@ -958,4 +535,4 @@ class _LoginRouteState extends State { ); return bgScaffold; } - +}