import 'dart:convert'; import 'dart:io'; import 'package:crypto/crypto.dart'; import 'dart:math'; import 'package:http/http.dart' as http; import 'package:permission_handler/permission_handler.dart'; import 'package:secure_string_operations/secure_string_operations.dart'; import 'package:sefer_driver/controller/functions/location_background_controller.dart'; import 'package:sefer_driver/views/auth/captin/cards/sms_signup.dart'; import 'package:sefer_driver/views/widgets/elevated_btn.dart'; import 'package:sefer_driver/views/widgets/error_snakbar.dart'; import 'package:flutter/material.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:get/get.dart'; import 'package:sefer_driver/constant/box_name.dart'; import 'package:sefer_driver/constant/links.dart'; import 'package:sefer_driver/controller/functions/crud.dart'; import 'package:sefer_driver/main.dart'; import 'package:sefer_driver/views/home/Captin/home_captain/home_captin.dart'; import 'package:location/location.dart'; import '../../../constant/api_key.dart'; import '../../../constant/char_map.dart'; import '../../../constant/info.dart'; import '../../../constant/table_names.dart'; import '../../../print.dart'; import '../../../views/auth/captin/cards/egypt_card_a_i.dart'; import '../../firebase/firbase_messge.dart'; import '../../functions/encrypt_decrypt.dart'; import '../../functions/package_info.dart'; import '../../functions/secure_storage.dart'; import '../../functions/security_checks.dart'; class LoginDriverController extends GetxController { final formKey = GlobalKey(); TextEditingController emailController = TextEditingController(); TextEditingController phoneController = TextEditingController(); TextEditingController passwordController = TextEditingController(); TextEditingController passwordController2 = TextEditingController(); bool isAgreeTerms = false; bool isGoogleDashOpen = false; bool isGoogleLogin = false; bool isloading = false; late int isTest = 1; final FlutterSecureStorage _storage = const FlutterSecureStorage(); final location = Location(); void changeAgreeTerm() { isAgreeTerms = !isAgreeTerms; update(); } bool showManualForm = false; bool isRegisterMode = false; // false = Login, true = Register /// تبديل عرض نموذج الدخول/التسجيل اليدوي void toggleManualFormView() { showManualForm = !showManualForm; // مسح الحقول عند إغلاق النموذج if (!showManualForm) { emailController.clear(); passwordController.clear(); } update(); } /// تبديل بين وضع تسجيل الدخول ووضع إنشاء حساب جديد void toggleRegisterMode() { isRegisterMode = !isRegisterMode; update(); } bool isRegistering = false; void toggleRegistration() { isRegistering = !isRegistering; update(); } bool isPasswordHidden = true; void togglePasswordVisibility() { isPasswordHidden = !isPasswordHidden; update([ 'passwordVisibility' ]); // Use a unique ID to only update the password field } void changeGoogleDashOpen() { isGoogleDashOpen = !isGoogleDashOpen; update(); } @override void onInit() async { box.read(BoxName.isTest) == null || box.read(BoxName.isTest).toString() == '0' ? await getAppTester() : null; super.onInit(); } getAppTester() async { var res = await CRUD().get( link: AppLink.getTesterApp, payload: {'appPlatform': AppInformation.appName}); if (res != 'failure') { var d = jsonDecode(res); isTest = d['message'][0]['isTest']; update(); } else { return false; } } updateAppTester(String appPlatform) async { await CRUD().post( link: AppLink.updateTesterApp, payload: {'appPlatform': appPlatform}); } void saveAgreementTerms() { box.write(BoxName.agreeTerms, 'agreed'); update(); } void saveCountryCode(String countryCode) { box.write(BoxName.countryCode, countryCode); update(); } var dev = ''; getJwtWallet() async { final random = Random(); if (random.nextBool()) { await SecurityHelper.performSecurityChecks(); } else { await SecurityChecks.isDeviceRootedFromNative(Get.context!); } String fingerPrint = await DeviceHelper.getDeviceFingerprint(); // print('fingerPrint: ${fingerPrint}'); dev = Platform.isAndroid ? 'android' : 'ios'; var payload = { 'id': box.read(BoxName.driverID), 'password': AK.passnpassenger, 'aud': '${AK.allowedWallet}$dev', 'fingerPrint': fingerPrint }; var response1 = await http.post( Uri.parse(AppLink.loginJwtWalletDriver), body: payload, ); // Log.print('response.request: ${response1.request}'); // Log.print('response.body: ${response1.body}'); // print(payload); // Log.print( // 'jsonDecode(response1.body)["jwt"]: ${jsonDecode(response1.body)['jwt']}'); await box.write(BoxName.hmac, jsonDecode(response1.body)['hmac']); return jsonDecode(response1.body)['jwt'].toString(); } String shortHash(String password) { var bytes = utf8.encode(password); var digest = sha256.convert(bytes); return base64UrlEncode(digest.bytes); } getJWT() async { dev = Platform.isAndroid ? 'android' : 'ios'; Log.print( 'box.read(BoxName.firstTimeLoadKey): ${box.read(BoxName.firstTimeLoadKey)}'); if (box.read(BoxName.firstTimeLoadKey).toString() != 'false') { var response0 = await http.post( Uri.parse(AppLink.loginFirstTimeDriver), body: { 'id': box.read(BoxName.driverID) ?? AK.newId, 'password': AK.passnpassenger, 'aud': '${AK.allowed}$dev', }, ); if (response0.statusCode == 200) { final decodedResponse1 = jsonDecode(response0.body); Log.print('decodedResponse1: ${decodedResponse1}'); final jwt = decodedResponse1['jwt']; box.write(BoxName.jwt, X.c(X.c(X.c(jwt, cn), cC), cs)); // await box.write(BoxName.hmac, decodedResponse1['hmac']); await AppInitializer().getAIKey(Driver.payMobApikey); await AppInitializer().getAIKey(Driver.FCM_PRIVATE_KEY); await AppInitializer().getAIKey(Driver.initializationVector); await AppInitializer().getAIKey(Driver.keyOfApp); // ✅ بعد التأكد أن كل المفاتيح موجودة await EncryptionHelper.initialize(); await AppInitializer().getKey(); } else {} } else { await EncryptionHelper.initialize(); var emailDecrypted = (box.read(BoxName.emailDriver)); var pass = passwordController.text.isEmpty ? '$emailDecrypted${box.read(BoxName.driverID)}' : '${emailController.text.toString()}${box.read(BoxName.driverID)}'; String hashedPassword = shortHash(pass); var payload = { 'id': box.read(BoxName.driverID), 'password': hashedPassword, 'aud': '${AK.allowed}$dev', }; var response1 = await http.post( Uri.parse(AppLink.loginJwtDriver), body: payload, ); // print(response1.request); // print(response1.body); // print(payload); if (response1.statusCode == 200) { final decodedResponse1 = jsonDecode(response1.body); // Log.print('decodedResponse1: ${decodedResponse1}'); final jwt = decodedResponse1['jwt']; // await box.write(BoxName.hmac, decodedResponse1['hmac']); await box.write(BoxName.jwt, X.c(X.c(X.c(jwt, cn), cC), cs)); await AppInitializer().getKey(); } } } Future getLocationPermission() async { var status = await Permission.locationAlways.status; if (!status.isGranted) { await Permission.locationAlways.request(); } update(); } String generateUniqueIdFromEmail(String email) { // Step 1: Extract the local part of the email String localPart = email.split('@')[0]; // Step 2: Replace invalid characters (if any) String cleanLocalPart = localPart.replaceAll(RegExp(r'[^a-zA-Z0-9]'), ''); // Step 3: Ensure it does not exceed 24 characters if (cleanLocalPart.length > 24) { cleanLocalPart = cleanLocalPart.substring(0, 24); } // Step 4: Generate a random suffix if needed String suffix = generateRandomSuffix(24 - cleanLocalPart.length); return cleanLocalPart + suffix; } String generateRandomSuffix(int length) { const String chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; Random random = Random(); return List.generate(length, (index) => chars[random.nextInt(chars.length)]) .join(''); } loginWithGoogleCredential(String driverID, email) async { isloading = true; update(); // await SecurityHelper.performSecurityChecks(); Log.print('(BoxName.emailDriver): ${box.read(BoxName.emailDriver)}'); Log.print('email: ${email}'); Log.print('driverID: ${driverID}'); var res = await CRUD().get(link: AppLink.loginFromGoogleCaptin, payload: { 'email': email, 'id': driverID, }); // print('res is $res'); if (res == 'failure') { //Failure if (box.read(BoxName.phoneVerified).toString() == '1') { Get.offAll(() => EgyptCardAI()); } else { Get.offAll(() => SmsSignupEgypt()); } isloading = false; update(); // Get.snackbar('Failure', '', backgroundColor: Colors.red); } else { var jsonDecoeded = jsonDecode(res); if (jsonDecoeded.isNotEmpty) { if (jsonDecoeded['status'] == 'success' && jsonDecoeded['data'][0]['is_verified'].toString() == '1') { box.write(BoxName.emailDriver, jsonDecoeded['data'][0]['email']); box.write(BoxName.firstTimeLoadKey, 'false'); box.write(BoxName.driverID, (jsonDecoeded['data'][0]['id'])); box.write(BoxName.isTest, '1'); box.write(BoxName.gender, (jsonDecoeded['data'][0]['gender'])); box.write(BoxName.phoneVerified, jsonDecoeded['data'][0]['is_verified'].toString()); box.write(BoxName.phoneDriver, (jsonDecoeded['data'][0]['phone'])); box.write(BoxName.is_claimed, jsonDecoeded['data'][0]['is_claimed']); box.write(BoxName.isInstall, jsonDecoeded['data'][0]['isInstall']); // box.write( // BoxName.isGiftToken, jsonDecoeded['data'][0]['isGiftToken']); box.write( BoxName.nameArabic, (jsonDecoeded['data'][0]['name_arabic'])); box.write(BoxName.carYear, jsonDecoeded['data'][0]['year']); box.write( BoxName.bankCodeDriver, (jsonDecoeded['data'][0]['bankCode'])); box.write(BoxName.accountBankNumberDriver, (jsonDecoeded['data'][0]['accountBank'])); box.write( BoxName.nameDriver, '${(jsonDecoeded['data'][0]['first_name'])}' ' ${(jsonDecoeded['data'][0]['last_name'])}'); if (((jsonDecoeded['data'][0]['model']) .toString() .contains('دراجه') || jsonDecoeded['data'][0]['make'].toString().contains('دراجه '))) { if ((jsonDecoeded['data'][0]['gender']).toString() == 'Male') { box.write(BoxName.carTypeOfDriver, 'Scooter'); } else { box.write(BoxName.carTypeOfDriver, 'Pink Bike'); } } else if (int.parse(jsonDecoeded['data'][0]['year'].toString()) > 2016) { if (jsonDecoeded['data'][0]['gender'].toString() != 'Male') { box.write(BoxName.carTypeOfDriver, 'Lady'); } else { box.write(BoxName.carTypeOfDriver, 'Comfort'); } } else if (int.parse(jsonDecoeded['data'][0]['year'].toString()) > 2002 && int.parse(jsonDecoeded['data'][0]['year'].toString()) < 2016) { box.write(BoxName.carTypeOfDriver, 'Speed'); } else if (int.parse(jsonDecoeded['data'][0]['year'].toString()) < 2002) { box.write(BoxName.carTypeOfDriver, 'Awfar Car'); } updateAppTester(AppInformation.appName); var token = await CRUD().get( link: AppLink.getDriverToken, payload: {'captain_id': (box.read(BoxName.driverID)).toString()}); String fingerPrint = await DeviceHelper.getDeviceFingerprint(); await storage.write( key: BoxName.fingerPrint, value: fingerPrint.toString()); if (token != 'failure') { Log.print( 'box.read(BoxName.tokenDriver): ${box.read(BoxName.tokenDriver)}'); Log.print( ' (jsonDecode(token): ${(jsonDecode(token)['data'][0]['token']).toString()}'); if ((jsonDecode(token)['data'][0]['token']) != (box.read(BoxName.tokenDriver))) { final fcm = Get.isRegistered() ? Get.find() : Get.put(FirebaseMessagesController()); fcm.sendNotificationToDriverMAP( 'token change', 'change device'.tr, (jsonDecode(token)['data'][0]['token']).toString(), [], 'promo.wav'); await Get.defaultDialog( title: 'you will use this device?'.tr, middleText: '', barrierDismissible: false, confirm: MyElevatedButton( title: 'Ok'.tr, onPressed: () async { await CRUD() .post(link: AppLink.addTokensDriver, payload: { 'token': (box.read(BoxName.tokenDriver)), 'captain_id': (box.read(BoxName.driverID)).toString(), 'fingerPrint': (fingerPrint).toString() }); // to save in payment server fingerprint await CRUD().post( link: "${AppLink.seferPaymentServer}/ride/firebase/addDriver.php", payload: { 'token': (box.read(BoxName.tokenDriver)), 'captain_id': (box.read(BoxName.driverID)).toString(), 'fingerPrint': (fingerPrint).toString() }); Get.back(); })); } } Get.off(() => HomeCaptain()); } else { Get.offAll(() => SmsSignupEgypt()); isloading = false; update(); } } else { mySnackbarSuccess(''); isloading = false; update(); } } } loginUsingCredentialsWithoutGoogle(String password, email) async { isloading = true; isGoogleLogin = true; // update(); var res = await CRUD() .get(link: AppLink.loginUsingCredentialsWithoutGoogle, payload: { 'email': (email), 'password': password, }); box.write(BoxName.emailDriver, (email).toString()); // print(res); if (res == 'failure') { //Failure if (box.read(BoxName.phoneVerified).toString() == '1') { Get.offAll(() => EgyptCardAI()); } else { Get.offAll(() => SmsSignupEgypt()); } isloading = false; update(); } else { var jsonDecoeded = jsonDecode(res); if (jsonDecoeded.isNotEmpty) { if (jsonDecoeded['status'] == 'success' && jsonDecoeded['data'][0]['is_verified'].toString() == '1') { box.write(BoxName.emailDriver, (jsonDecoeded['data'][0]['email'])); box.write(BoxName.driverID, (jsonDecoeded['data'][0]['id'])); box.write(BoxName.isTest, '1'); box.write(BoxName.gender, (jsonDecoeded['data'][0]['gender'])); box.write(BoxName.phoneVerified, jsonDecoeded['data'][0]['is_verified'].toString()); box.write(BoxName.phoneDriver, (jsonDecoeded['data'][0]['phone'])); box.write( BoxName.nameArabic, (jsonDecoeded['data'][0]['name_arabic'])); box.write( BoxName.bankCodeDriver, (jsonDecoeded['data'][0]['bankCode'])); box.write(BoxName.accountBankNumberDriver, jsonDecoeded['data'][0]['accountBank']); box.write( BoxName.nameDriver, '${(jsonDecoeded['data'][0]['first_name'])}' ' ${(jsonDecoeded['data'][0]['last_name'])}'); if ((jsonDecoeded['data'][0]['model'].toString().contains('دراجه') || jsonDecoeded['data'][0]['make'].toString().contains('دراجه '))) { if ((jsonDecoeded['data'][0]['gender']).toString() == 'Male') { box.write(BoxName.carTypeOfDriver, 'Scooter'); } else { box.write(BoxName.carTypeOfDriver, 'Pink Bike'); } } else if (int.parse(jsonDecoeded['data'][0]['year'].toString()) > 2017) { if ((jsonDecoeded['data'][0]['gender']).toString() != 'Male') { box.write(BoxName.carTypeOfDriver, 'Lady'); } else { box.write(BoxName.carTypeOfDriver, 'Comfort'); } } else if (int.parse(jsonDecoeded['data'][0]['year'].toString()) > 2002 && int.parse(jsonDecoeded['data'][0]['year'].toString()) < 2017) { box.write(BoxName.carTypeOfDriver, 'Speed'); } else if (int.parse(jsonDecoeded['data'][0]['year'].toString()) < 2002) { box.write(BoxName.carTypeOfDriver, 'Awfar Car'); } updateAppTester(AppInformation.appName); var fingerPrint = DeviceHelper.getDeviceFingerprint().toString(); await storage.write(key: BoxName.fingerPrint, value: fingerPrint); var token = await CRUD().get( link: AppLink.getDriverToken, payload: {'captain_id': box.read(BoxName.driverID).toString()}); if (token != 'failure') { if ((jsonDecode(token)['data'][0]['token']) != (box.read(BoxName.tokenDriver))) { Get.put(FirebaseMessagesController()).sendNotificationToDriverMAP( 'token change'.tr, 'change device'.tr, (jsonDecode(token)['data'][0]['token']).toString(), [], 'ding.wav'); Get.defaultDialog( title: 'you will use this device?'.tr, middleText: '', confirm: MyElevatedButton( title: 'Ok'.tr, onPressed: () async { await CRUD() .post(link: AppLink.addTokensDriver, payload: { 'token': box.read(BoxName.tokenDriver), 'captain_id': box.read(BoxName.driverID).toString(), 'fingerPrint': (fingerPrint).toString() }); await CRUD().post( link: "${AppLink.seferAlexandriaServer}/ride/firebase/addDriver.php", payload: { 'token': box.read(BoxName.tokenDriver), 'captain_id': box.read(BoxName.driverID).toString(), 'fingerPrint': (fingerPrint).toString() }); await CRUD().post( link: "${AppLink.seferGizaServer}/ride/firebase/addDriver.php", payload: { 'token': box.read(BoxName.tokenDriver), 'captain_id': box.read(BoxName.driverID).toString(), 'fingerPrint': (fingerPrint).toString() }); Get.back(); })); } } Get.off(() => HomeCaptain()); // Get.off(() => LoginCaptin()); } else { Get.offAll(() => SmsSignupEgypt()); isloading = false; update(); } } else { mySnackeBarError(''); isloading = false; update(); } } } void loginByBoxData() async { Get.to(() => HomeCaptain()); await CRUD().post(link: AppLink.addTokensDriver, payload: { 'token': box.read(BoxName.tokenDriver).toString(), 'captain_id': box.read(BoxName.driverID).toString() }); CRUD().post( link: "${AppLink.seferAlexandriaServer}/ride/firebase/addDriver.php", payload: { 'token': box.read(BoxName.tokenDriver), 'captain_id': box.read(BoxName.driverID).toString() }); CRUD().post( link: "${AppLink.seferGizaServer}/ride/firebase/addDriver.php", payload: { 'token': box.read(BoxName.tokenDriver), 'captain_id': box.read(BoxName.driverID).toString() }); } }