25-7-28-2

This commit is contained in:
Hamza-Ayed
2025-07-28 12:21:28 +03:00
parent 660d60e1f5
commit 83a97baed1
549 changed files with 109870 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
import 'package:firebase_auth/firebase_auth.dart';
import 'package:get/get.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
class AuthController extends GetxController {
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<User?> signInWithApple() async {
try {
final appleCredential = await SignInWithApple.getAppleIDCredential(
scopes: [
AppleIDAuthorizationScopes.email,
AppleIDAuthorizationScopes.fullName,
],
);
final oAuthProvider = OAuthProvider('apple.com');
final credential = oAuthProvider.credential(
idToken: appleCredential.identityToken,
accessToken: appleCredential.authorizationCode,
);
UserCredential userCredential =
await _auth.signInWithCredential(credential);
return userCredential.user;
} catch (error) {
return null;
}
}
void signOut() async {
await _auth.signOut();
}
}

View File

@@ -0,0 +1,61 @@
import 'dart:convert';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
import 'package:get/get.dart';
import '../../../constant/box_name.dart';
import '../../../constant/links.dart';
import '../../../main.dart';
import '../../../views/home/Captin/history/history_details_page.dart';
import '../../functions/crud.dart';
import '../../functions/encrypt_decrypt.dart';
class HistoryCaptainController extends GetxController {
bool isloading = false;
Map historyData = {};
Map historyDetailsData = {};
late String orderID;
getOrderId(String orderId) {
orderID = orderId;
update();
}
getHistory() async {
isloading = true;
var res = await CRUD().get(
link: AppLink.getDriverOrder,
payload: {'driver_id': box.read(BoxName.driverID)});
if (res != 'failure') {
historyData = jsonDecode(res);
isloading = false;
update();
} else {
Get.defaultDialog(
title: 'No ride yet'.tr,
middleText: '',
barrierDismissible: false,
confirm: MyElevatedButton(
title: 'Back'.tr,
onPressed: () {
Get.back();
Get.back();
}));
}
}
getHistoryDetails(String orderId) async {
isloading = true;
var res = await CRUD()
.get(link: AppLink.getRideOrderID, payload: {'id': (orderId)});
historyDetailsData = jsonDecode(res);
isloading = false;
update();
Get.to(() => HistoryDetailsPage());
}
@override
void onInit() {
getHistory();
super.onInit();
}
}

View File

@@ -0,0 +1,416 @@
import 'dart:convert';
import 'package:local_auth/local_auth.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/firebase/local_notification.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/controller/functions/encrypt_decrypt.dart';
import 'package:sefer_driver/controller/home/payment/captain_wallet_controller.dart';
import 'package:sefer_driver/views/widgets/mydialoug.dart';
import 'package:flutter/material.dart';
import 'package:flutter_contacts/contact.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:get/get.dart';
import 'package:share_plus/share_plus.dart';
import '../../../main.dart';
import '../../../views/widgets/error_snakbar.dart';
import '../../functions/launch.dart';
import '../../notification/notification_captain_controller.dart';
class InviteController extends GetxController {
final TextEditingController invitePhoneController = TextEditingController();
List driverInvitationData = [];
List driverInvitationDataToPassengers = [];
String? couponCode;
String? driverCouponCode;
int selectedTab = 0;
PassengerStats passengerStats = PassengerStats();
void updateSelectedTab(int index) {
selectedTab = index;
update();
}
Future<void> shareCouponCode() async {
// TODO: Implement sharing functionality
// You can use share_plus package to share the coupon code
}
Future<void> shareDriverCode() async {
if (driverCouponCode != null) {
final String shareText = '''
Join Intaleq as a driver using my referral code!
Use code: $driverCouponCode
Download the Intaleq Driver app now and earn rewards!
''';
await Share.share(shareText);
}
}
Future<void> sharePassengerCode() async {
if (couponCode != null) {
final String shareText = '''
Get a discount on your first Intaleq ride!
Use my referral code: $couponCode
Download the Intaleq app now and enjoy your ride!
''';
await Share.share(shareText);
}
}
@override
void onInit() {
super.onInit();
// fetchDriverStats();
}
void fetchDriverStats() async {
try {
var response = await CRUD().get(link: AppLink.getInviteDriver, payload: {
"driverId": box.read(BoxName.driverID),
});
if (response != 'failure') {
var data = jsonDecode(response);
driverInvitationData = data['message'];
update();
}
} catch (e) {}
}
void fetchDriverStatsPassengers() async {
try {
var response = await CRUD()
.get(link: AppLink.getDriverInvitationToPassengers, payload: {
"driverId": box.read(BoxName.driverID),
});
if (response != 'failure') {
var data = jsonDecode(response);
driverInvitationDataToPassengers = data['message'];
update();
}
} catch (e) {}
}
void selectPhone(String phone) {
if (box.read(BoxName.countryCode) == 'Egypt') {
invitePhoneController.text = phone;
update();
Get.back();
}
}
Future<void> saveContactsToServer() async {
try {
// TODO: Implement the actual server upload logic here
// Simulating a server request
await Future.delayed(Duration(seconds: 2));
mySnackbarSuccess(
'${selectedContacts.length} contacts saved to server'.tr);
} catch (e) {
mySnackeBarError(
'An error occurred while saving contacts to server: $e'.tr);
}
}
List<Contact> contacts = <Contact>[];
List<Contact> selectedContacts = <Contact>[];
RxList<Map<String, dynamic>> contactMaps = <Map<String, dynamic>>[].obs;
Future<void> pickContacts() async {
try {
if (await FlutterContacts.requestPermission(readonly: true)) {
final List<Contact> fetchedContacts =
await FlutterContacts.getContacts(withProperties: true);
contacts = fetchedContacts;
// Convert contacts to a list of maps
contactMaps.value = fetchedContacts.map((contact) {
return {
'name': contact.displayName,
'phones':
contact.phones.map((phone) => phone.normalizedNumber).toList(),
'emails': contact.emails.map((email) => email.address).toList(),
};
}).toList();
update();
if (contacts.isEmpty) {
mySnackeBarError('Please add contacts to your phone.'.tr);
}
} else {
mySnackeBarError('Contact permission is required to pick contacts'.tr);
}
} catch (e) {
mySnackeBarError('An error occurred while picking contacts: $e'.tr);
}
}
void onSelectDriverInvitation(int index) async {
MyDialog().getDialog(
int.parse((driverInvitationData[index]['countOfInvitDriver'])) < 100
? '${'When'.tr} ${(driverInvitationData[index]['invitorName'])} ${"complete, you can claim your gift".tr} '
: 'You deserve the gift'.tr,
'${(driverInvitationData[index]['invitorName'])} ${(driverInvitationData[index]['countOfInvitDriver'])} / 100 ${'Trip'.tr}',
() async {
bool isAvailable = await LocalAuthentication().isDeviceSupported();
if (int.parse((driverInvitationData[index]['countOfInvitDriver'])) <
100) {
Get.back();
} else
//claim your gift
if (isAvailable) {
// Authenticate the user
bool didAuthenticate = await LocalAuthentication().authenticate(
localizedReason: 'Use Touch ID or Face ID to confirm payment',
options: AuthenticationOptions(
biometricOnly: true,
sensitiveTransaction: true,
));
if (didAuthenticate) {
if ((driverInvitationData[index]['isGiftToken']).toString() ==
'0') {
Get.back();
await CRUD().post(
link: AppLink.updateInviteDriver,
payload: {'id': (driverInvitationData[index]['id'])});
await Get.find<CaptainWalletController>().addDriverPayment(
'paymentMethod',
('500'),
'',
);
// add for invitor too
await Get.find<CaptainWalletController>()
.addDriverWalletToInvitor(
'paymentMethod',
(driverInvitationData[index]['driverInviterId']),
('500'),
);
// await Get.find<CaptainWalletController>()
// .addSeferWallet('giftInvitation', ('-1000'));
NotificationCaptainController().addNotificationCaptain(
driverInvitationData[index]['driverInviterId'].toString(),
"You have got a gift for invitation".tr,
'${"You have 500".tr} ${'LE'.tr}',
false);
NotificationController().showNotification(
"You have got a gift for invitation".tr,
'${"You have 500".tr} ${'LE'.tr}',
'tone1',
'');
} else {
Get.back();
MyDialog().getDialog("You have got a gift".tr,
"Share the app with another new driver".tr, () {
Get.back();
});
}
} else {
// Authentication failed, handle accordingly
MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
Get.back();
});
}
} else {
MyDialog().getDialog('Biometric Authentication'.tr,
'You should use Touch ID or Face ID to confirm payment'.tr, () {
Get.back();
});
}
},
);
}
void onSelectPassengerInvitation(int index) async {
bool isAvailable = await LocalAuthentication().isDeviceSupported();
MyDialog().getDialog(
int.parse(driverInvitationDataToPassengers[index]['countOfInvitDriver']
.toString()) <
3
? '${'When'.tr} ${(driverInvitationDataToPassengers[index]['passengerName'].toString())} ${"complete, you can claim your gift".tr} '
: 'You deserve the gift'.tr,
'${(driverInvitationDataToPassengers[index]['passengerName'].toString())} ${driverInvitationDataToPassengers[index]['countOfInvitDriver']} / 3 ${'Trip'.tr}',
() async {
if (int.parse(driverInvitationDataToPassengers[index]
['countOfInvitDriver']
.toString()) <
3) {
Get.back();
} else if (isAvailable) {
// Authenticate the user
bool didAuthenticate = await LocalAuthentication().authenticate(
localizedReason: 'Use Touch ID or Face ID to confirm payment',
options: AuthenticationOptions(
biometricOnly: true,
sensitiveTransaction: true,
));
if (didAuthenticate) {
// Claim the gift if 100 trips are completed
if (driverInvitationDataToPassengers[index]['isGiftToken']
.toString() ==
'0') {
Get.back();
// Add wallet to the inviter
await Get.find<CaptainWalletController>()
.addDriverWallet('paymentMethod', '50', '50');
// add for invitor too
await Get.find<CaptainWalletController>()
.addDriverWalletToInvitor('paymentMethod',
driverInvitationData[index]['driverInviterId'], '50');
// Update invitation as claimed
await CRUD().post(
link: AppLink.updatePassengerGift,
payload: {'id': driverInvitationDataToPassengers[index]['id']},
);
// Notify the inviter
NotificationCaptainController().addNotificationCaptain(
driverInvitationDataToPassengers[index]['passengerInviterId']
.toString(),
"You have got a gift for invitation".tr,
'${"You have 50".tr} ${'LE'}',
false,
);
} else {
Get.back();
MyDialog().getDialog(
"You have got a gift".tr,
"Share the app with another new passenger".tr,
() {
Get.back();
},
);
}
} else {
// Authentication failed, handle accordingly
MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
Get.back();
});
}
} else {
MyDialog().getDialog('Biometric Authentication'.tr,
'You should use Touch ID or Face ID to confirm payment'.tr, () {
Get.back();
});
}
},
);
}
savePhoneToServer() async {
for (var i = 0; i < contactMaps.length; i++) {
var phones = contactMaps[i]['phones'];
if (phones != null && phones.isNotEmpty && phones[0].isNotEmpty) {
var res = await CRUD().post(link: AppLink.savePhones, payload: {
"name": contactMaps[i]['name'] ?? 'none',
"phones": phones[0] ?? 'none',
"phones2": phones.join(', ') ??
'none', // Convert List<String> to a comma-separated string
});
if (res != 'failure') {}
} else {}
}
}
String formatPhoneNumber(String input) {
// Remove any non-digit characters
String digitsOnly = input.replaceAll(RegExp(r'\D'), '');
// Ensure the number starts with the country code
if (digitsOnly.startsWith('20')) {
digitsOnly = digitsOnly.substring(1);
}
return digitsOnly;
}
void sendInvite() async {
if (invitePhoneController.text.isEmpty) {
mySnackeBarError('Please enter an phone address'.tr);
return;
}
// try {
String phoneNumber = formatPhoneNumber(invitePhoneController.text);
var response = await CRUD().post(link: AppLink.addInviteDriver, payload: {
"driverId": box.read(BoxName.driverID),
"inviterDriverPhone": '+2$phoneNumber'
});
if (response != 'failure') {
var d = (response);
mySnackbarSuccess('Invite sent successfully'.tr);
String message = '${'*Intaleq DRIVER CODE*'.tr}\n\n'
'${"Use this code in registration".tr}\n'
'${"To get a gift for both".tr}\n\n'
'${"The period of this code is 1 hour".tr}\n\n'
'${'before'.tr} *${d['message']['expirationTime'].toString()}*\n\n'
'_*${d['message']['inviteCode'].toString()}*_\n\n'
'${"Install our app:".tr}\n'
'*Android:* https://play.google.com/store/apps/details?id=com.sefer_driver\n\n\n'
'*iOS:* https://apps.apple.com/ae/app/sefer-driver/id6502189302';
launchCommunication('whatsapp', '+2$phoneNumber', message);
invitePhoneController.clear();
} else {
mySnackeBarError("Invite code already used".tr);
}
}
void sendInviteToPassenger() async {
if (invitePhoneController.text.isEmpty) {
mySnackeBarError('Please enter an phone address'.tr);
return;
}
// try {
String phoneNumber = formatPhoneNumber(invitePhoneController.text);
var response =
await CRUD().post(link: AppLink.addInvitationPassenger, payload: {
"driverId": box.read(BoxName.driverID),
"inviterPassengerPhone": '+2$phoneNumber'
});
if (response != 'failure') {
var d = jsonDecode(response);
mySnackbarSuccess('Invite sent successfully'.tr);
String message = '${'*Intaleq APP CODE*'.tr}\n\n'
'${"Use this code in registration".tr}\n'
'${"To get a gift for both".tr}\n\n'
'${"The period of this code is 1 hour".tr}\n\n'
'${'before'.tr} *${d['message']['expirationTime'].toString()}*\n\n'
'_*${d['message']['inviteCode'].toString()}*_\n\n'
'${"Install our app:".tr}\n'
'*Android:* https://play.google.com/store/apps/details?id=com.mobileapp.store.ride\n\n\n'
'*iOS:* https://apps.apple.com/us/app/sefer/id6458734951';
launchCommunication('whatsapp', '+2$phoneNumber', message);
invitePhoneController.clear();
} else {
mySnackeBarError(
"Invite code already used".tr,
);
}
}
}
class PassengerStats {
final int totalInvites;
final int activeUsers;
final double totalEarnings;
PassengerStats({
this.totalInvites = 0,
this.activeUsers = 0,
this.totalEarnings = 0.0,
});
}

View File

@@ -0,0 +1,608 @@
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/syrian_card_a_i.dart';
import '../../../views/auth/captin/otp_page.dart';
import '../../../views/auth/captin/otp_token_page.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<FormState>();
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 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.write(BoxName.countryCode, 'Syria');
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});
}
isPhoneVerified() async {
var res = await CRUD().post(link: AppLink.isPhoneVerified, payload: {
'phone_number': box.read(
BoxName.phoneDriver,
)
});
if (res != 'failure') {
Get.offAll(() => SyrianCardAI());
// isloading = false;
// update();
} else {
Get.offAll(() => PhoneNumberScreen());
}
}
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 payload = {
'id': box.read(BoxName.driverID) ?? AK.newId,
'password': AK.passnpassenger,
'aud': '${AK.allowed}$dev',
};
Log.print('payload: ${payload}');
var response0 = await http.post(
Uri.parse(AppLink.loginFirstTimeDriver),
body: payload,
);
Log.print('response0: ${response0.body}');
Log.print('request: ${response0.request}');
if (response0.statusCode == 200) {
final decodedResponse1 = jsonDecode(response0.body);
// Log.print('decodedResponse1: ${decodedResponse1}');
final jwt = decodedResponse1['jwt'];
box.write(BoxName.jwt, c(jwt));
// 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 payload = {
'id': box.read(BoxName.driverID),
'password': box.read(BoxName.emailDriver),
'aud': '${AK.allowed}$dev',
};
print(payload);
var response1 = await http.post(
Uri.parse(AppLink.loginJwtDriver),
body: payload,
);
print(response1.request);
print(response1.body);
if (response1.statusCode == 200) {
final decodedResponse1 = jsonDecode(response1.body);
// Log.print('decodedResponse1: ${decodedResponse1}');
final jwt = decodedResponse1['jwt'];
await box.write(BoxName.jwt, c(jwt));
await AppInitializer().getKey();
}
}
}
Future<void> 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)}');
var res = await CRUD().get(link: AppLink.loginFromGoogleCaptin, payload: {
'email': email ?? 'yet',
'id': driverID,
});
// print('res is $res');
if (res == 'failure') {
await isPhoneVerified();
// Get.snackbar('Failure', '', backgroundColor: Colors.red);
} else {
var jsonDecoeded = jsonDecode(res);
var d = jsonDecoeded['data'][0];
if (jsonDecoeded.isNotEmpty) {
if (jsonDecoeded['status'] == 'success' &&
d['is_verified'].toString() == '1') {
box.write(BoxName.emailDriver, d['email']);
box.write(BoxName.firstTimeLoadKey, 'false');
box.write(BoxName.driverID, (d['id']));
box.write(BoxName.isTest, '1');
box.write(BoxName.gender, (d['gender']));
box.write(BoxName.phoneVerified, d['is_verified'].toString());
box.write(BoxName.phoneDriver, (d['phone']));
box.write(BoxName.is_claimed, d['is_claimed']);
box.write(BoxName.isInstall, d['isInstall']);
// box.write(
// BoxName.isGiftToken, d['isGiftToken']);
box.write(BoxName.nameArabic, (d['name_arabic']));
box.write(BoxName.carYear, d['year']);
box.write(BoxName.bankCodeDriver, (d['bankCode']));
box.write(BoxName.accountBankNumberDriver, (d['accountBank']));
box.write(
BoxName.nameDriver,
'${(d['first_name'])}'
' ${(d['last_name'])}');
if (((d['model']).toString().contains('دراجه') ||
d['make'].toString().contains('دراجه '))) {
if ((d['gender']).toString() == 'Male') {
box.write(BoxName.carTypeOfDriver, 'Scooter');
} else {
box.write(BoxName.carTypeOfDriver, 'Pink Bike');
}
} else if (int.parse(d['year'].toString()) > 2016) {
if (d['gender'].toString() != 'Male') {
box.write(BoxName.carTypeOfDriver, 'Lady');
} else {
box.write(BoxName.carTypeOfDriver, 'Comfort');
}
} else if (int.parse(d['year'].toString()) > 2002 &&
int.parse(d['year'].toString()) < 2016) {
box.write(BoxName.carTypeOfDriver, 'Speed');
} else if (int.parse(d['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());
print(jsonDecode(token)['data'][0]['token'].toString());
print(box.read(BoxName.tokenDriver).toString());
if (email == '962798583052@intaleqapp.com') {
} else {
if (token != 'failure') {
if ((jsonDecode(token)['data'][0]['token'].toString()) !=
box.read(BoxName.tokenDriver).toString()) {
await Get.defaultDialog(
title: 'Device Change Detected'.tr,
middleText: 'Please verify your identity'.tr,
textConfirm: 'Verify'.tr,
confirmTextColor: Colors.white,
onConfirm: () {
// Get.back();
// انتقل لصفحة OTP الجديدة
Get.to(
() => OtpVerificationPage(
phone: d['phone'].toString(),
deviceToken: fingerPrint.toString(),
token: token.toString(),
ptoken:
jsonDecode(token)['data'][0]['token'].toString(),
),
);
},
);
}
}
}
Get.off(() => HomeCaptain());
} else {
Get.offAll(() => PhoneNumberScreen());
isloading = false;
update();
}
} else {
mySnackbarSuccess('');
isloading = false;
update();
}
}
}
logintest(String driverID, email) async {
isloading = true;
update();
await SecurityHelper.performSecurityChecks();
Log.print('(BoxName.emailDriver): ${box.read(BoxName.emailDriver)}');
var res = await CRUD().get(link: AppLink.loginFromGoogleCaptin, payload: {
'email': email ?? 'yet',
'id': driverID,
});
// print('res is $res');
if (res == 'failure') {
await isPhoneVerified();
// Get.snackbar('Failure', '', backgroundColor: Colors.red);
} else {
var jsonDecoeded = jsonDecode(res);
var d = jsonDecoeded['data'][0];
if (jsonDecoeded.isNotEmpty) {
if (jsonDecoeded['status'] == 'success' &&
d['is_verified'].toString() == '1') {
box.write(BoxName.emailDriver, d['email']);
box.write(BoxName.firstTimeLoadKey, 'false');
box.write(BoxName.driverID, (d['id']));
box.write(BoxName.isTest, '1');
box.write(BoxName.gender, (d['gender']));
box.write(BoxName.phoneVerified, d['is_verified'].toString());
box.write(BoxName.phoneDriver, (d['phone']));
box.write(BoxName.is_claimed, d['is_claimed']);
box.write(BoxName.isInstall, d['isInstall']);
// box.write(
// BoxName.isGiftToken, d['isGiftToken']);
box.write(BoxName.nameArabic, (d['name_arabic']));
box.write(BoxName.carYear, d['year']);
box.write(BoxName.bankCodeDriver, (d['bankCode']));
box.write(BoxName.accountBankNumberDriver, (d['accountBank']));
box.write(
BoxName.nameDriver,
'${(d['first_name'])}'
' ${(d['last_name'])}');
if (((d['model']).toString().contains('دراجه') ||
d['make'].toString().contains('دراجه '))) {
if ((d['gender']).toString() == 'Male') {
box.write(BoxName.carTypeOfDriver, 'Scooter');
} else {
box.write(BoxName.carTypeOfDriver, 'Pink Bike');
}
} else if (int.parse(d['year'].toString()) > 2016) {
if (d['gender'].toString() != 'Male') {
box.write(BoxName.carTypeOfDriver, 'Lady');
} else {
box.write(BoxName.carTypeOfDriver, 'Comfort');
}
} else if (int.parse(d['year'].toString()) > 2002 &&
int.parse(d['year'].toString()) < 2016) {
box.write(BoxName.carTypeOfDriver, 'Speed');
} else if (int.parse(d['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());
Get.off(() => HomeCaptain());
} else {
Get.offAll(() => PhoneNumberScreen());
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(() => SyrianCardAI());
} else {
Get.offAll(() => SmsSignupEgypt());
}
isloading = false;
update();
} else {
var jsonDecoeded = jsonDecode(res);
var d = jsonDecoeded['data'][0];
if (jsonDecoeded.isNotEmpty) {
if (jsonDecoeded['status'] == 'success' &&
d['is_verified'].toString() == '1') {
box.write(BoxName.emailDriver, (d['email']));
box.write(BoxName.driverID, (d['id']));
box.write(BoxName.isTest, '1');
box.write(BoxName.gender, (d['gender']));
box.write(BoxName.phoneVerified, d['is_verified'].toString());
box.write(BoxName.phoneDriver, (d['phone']));
box.write(BoxName.nameArabic, (d['name_arabic']));
box.write(BoxName.bankCodeDriver, (d['bankCode']));
box.write(BoxName.accountBankNumberDriver, d['accountBank']);
box.write(
BoxName.nameDriver,
'${(d['first_name'])}'
' ${(d['last_name'])}');
if ((d['model'].toString().contains('دراجه') ||
d['make'].toString().contains('دراجه '))) {
if ((d['gender']).toString() == 'Male') {
box.write(BoxName.carTypeOfDriver, 'Scooter');
} else {
box.write(BoxName.carTypeOfDriver, 'Pink Bike');
}
} else if (int.parse(d['year'].toString()) > 2017) {
if ((d['gender']).toString() != 'Male') {
box.write(BoxName.carTypeOfDriver, 'Lady');
} else {
box.write(BoxName.carTypeOfDriver, 'Comfort');
}
} else if (int.parse(d['year'].toString()) > 2002 &&
int.parse(d['year'].toString()) < 2017) {
box.write(BoxName.carTypeOfDriver, 'Speed');
} else if (int.parse(d['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()
});
}
}

View File

@@ -0,0 +1,93 @@
import 'dart:io';
import 'package:get/get.dart';
// import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sefer_driver/constant/colors.dart';
import 'package:sefer_driver/controller/functions/llama_ai.dart';
// class CarRegistrationRecognizerController extends GetxController {
// @override
// void onInit() {
// // scanText();
// super.onInit();
// }
// // The ImagePicker instance
// final ImagePicker _imagePicker = ImagePicker();
// // The GoogleMlKit TextRecognizer instance
// // final TextRecognizer _textRecognizer = TextRecognizer();
// // The scanned text
// String? scannedText;
// String? jsonOutput;
// final List<Map<String, dynamic>> lines = [];
// Map extracted = {};
// XFile? image;
// CroppedFile? croppedFile;
// // Picks an image from the camera or gallery and extracts the text
// final List<Map<String, dynamic>> extractedTextWithCoordinates = [];
// Future<void> scanText() async {
// // Pick an image from the camera or gallery
// image = await _imagePicker.pickImage(source: ImageSource.gallery);
// update();
// // If no image was picked, return
// if (image == null) {
// return;
// }
// // Crop the image
// croppedFile = await ImageCropper().cropImage(
// sourcePath: image!.path,
// //
// uiSettings: [
// AndroidUiSettings(
// toolbarTitle: 'Cropper'.tr,
// toolbarColor: AppColor.blueColor,
// toolbarWidgetColor: AppColor.yellowColor,
// initAspectRatio: CropAspectRatioPreset.original,
// lockAspectRatio: false),
// IOSUiSettings(
// title: 'Cropper'.tr,
// ),
// ],
// );
// // If no cropped image was obtained, return
// if (croppedFile == null) {
// return;
// }
// // Convert the cropped file to an InputImage object
// final InputImage inputImage = InputImage.fromFile(File(croppedFile!.path));
// // Recognize the text in the image
// final RecognizedText recognizedText =
// await _textRecognizer.processImage(inputImage);
// scannedText = recognizedText.text;
// // Extract the scanned text line by line
// final List<Map<String, dynamic>> lines = [];
// for (var i = 0; i < recognizedText.blocks.length; i++) {
// lines.add({
// i.toString(): recognizedText.blocks[i].text,
// });
// }
// String result = lines.map((map) => map.values.first.toString()).join(' ');
// if (result.length > 2200) {
// result = result.substring(0, 2200);
// }
// Map result2 = await LlamaAi().getCarRegistrationData(result,
// 'vin,make,made,year,expiration_date,color,owner,registration_date'); //
// // Assign the result to the extracted variable
// extracted = result2;
// update();
// }
// }

View File

@@ -0,0 +1,108 @@
import 'dart:async';
import 'package:get/get.dart';
import 'package:sefer_driver/views/home/Captin/home_captain/home_captin.dart';
import '../../../constant/box_name.dart';
import '../../../constant/links.dart';
import '../../../main.dart';
import '../../firebase/firbase_messge.dart';
import '../../functions/crud.dart';
class OtpVerificationController extends GetxController {
final String phone;
final String deviceToken;
final String token;
final otpCode = ''.obs;
final isLoading = false.obs;
final isVerifying = false.obs;
var canResend = false.obs;
var countdown = 120.obs;
Timer? _timer;
OtpVerificationController({
required this.phone,
required this.deviceToken,
required this.token,
});
@override
void onInit() {
super.onInit();
sendOtp(); // ترسل تلقائيًا عند فتح الصفحة
startCountdown();
}
void startCountdown() {
canResend.value = false;
countdown.value = 120;
_timer?.cancel();
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (countdown.value > 0) {
countdown.value--;
} else {
canResend.value = true;
timer.cancel();
}
});
}
Future<void> sendOtp() async {
isLoading.value = true;
try {
final response = await CRUD().post(
link:
'${AppLink.server}/auth/token_passenger/driver/send_otp_driver.php',
payload: {
'receiver': phone,
// 'device_token': deviceToken,
},
);
if (response != 'failure') {
// بإمكانك عرض رسالة نجاح هنا
} else {
// Get.snackbar('Error', 'Failed to send OTP');
}
} catch (e) {
Get.snackbar('Error', e.toString());
} finally {
isLoading.value = false;
}
}
Future<void> verifyOtp(String ptoken) async {
isVerifying.value = true;
var finger = await storage.read(key: BoxName.fingerPrint);
try {
final response = await CRUD().post(
link:
'${AppLink.server}/auth/token_passenger/driver/verify_otp_driver/.php',
payload: {
'phone_number': phone,
'otp': otpCode.value,
'token': box.read(BoxName.tokenDriver).toString(),
'fingerPrint': finger.toString(),
},
);
if (response != 'failure' && response['status'] == 'success') {
Get.back(); // توجه إلى الصفحة التالية
Get.put(FirebaseMessagesController()).sendNotificationToDriverMAP(
'token change',
'change device'.tr,
ptoken.toString(),
[],
'cancel.wav',
);
Get.offAll(() => HomeCaptain());
} else {
Get.snackbar('Verification Failed', 'OTP is incorrect or expired');
}
} catch (e) {
Get.snackbar('Error', e.toString());
} finally {
isVerifying.value = false;
}
}
}

View File

@@ -0,0 +1,142 @@
import 'package:get/get.dart';
import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/views/auth/captin/cards/syrian_card_a_i.dart';
import 'package:sefer_driver/views/home/on_boarding_page.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import '../../../constant/box_name.dart';
import '../../../constant/links.dart';
import '../../../main.dart';
import '../../../print.dart';
import '../../../views/auth/captin/otp_page.dart';
// --- Helper Class for Phone Authentication ---
class PhoneAuthHelper {
// Define your server URLs
static final String _baseUrl = '${AppLink.server}/auth/syria/driver/';
static final String _sendOtpUrl = '${_baseUrl}sendWhatsAppDriver.php';
static final String _verifyOtpUrl = '${_baseUrl}verifyOtp.php';
static final String _registerUrl = '${_baseUrl}register_driver.php';
/// Sends an OTP to the provided phone number.
static Future<bool> sendOtp(String phoneNumber) async {
try {
final response = await CRUD().post(
link: _sendOtpUrl,
payload: {'receiver': phoneNumber},
);
Log.print('response: ${response}');
if (response != 'failure') {
final data = (response);
// if (data['status'] == 'success') {
mySnackbarSuccess('An OTP has been sent to your WhatsApp number.'.tr);
return true;
// } else {
// mySnackeBarError(data['message'] ?? 'Failed to send OTP.');
// return false;
// }
} else {
mySnackeBarError('Server error. Please try again.'.tr);
return false;
}
} catch (e) {
Log.print('e: ${e}');
// mySnackeBarError('An error occurred: $e');
return false;
}
}
/// Verifies the OTP and logs the user in.
static Future<void> verifyOtp(String phoneNumber, String otp) async {
try {
final response = await CRUD().post(
link: _verifyOtpUrl,
payload: {'phone_number': phoneNumber, 'otp': otp},
);
if (response != 'failure') {
final data = response;
if (data['status'] == 'success') {
final isRegistered = data['message']['isRegistered'] ?? false;
Log.print('isRegistered: ${isRegistered}');
box.write(BoxName.phoneVerified, true);
box.write(BoxName.phoneDriver, phoneNumber);
box.write(BoxName.driverID, data['message']['driverID']);
Log.print('BoxName.driverID: ${box.read(BoxName.driverID)}');
if (isRegistered) {
// ✅ السائق مسجل مسبقًا - سجل دخوله واذهب إلى الصفحة الرئيسية
final driver = data['message']['driver'];
// mySnackbarSuccess('Welcome back, ${driver['first_name']}!');
Log.print('Welcome: }');
// حفظ بيانات السائق إذا أردت:
box.write(BoxName.driverID, driver['id']);
box.write(BoxName.emailDriver, driver['email']);
await Get.find<LoginDriverController>().loginWithGoogleCredential(
driver['id'].toString(), driver['email'].toString());
} else {
// ✅ رقم الهاتف تم التحقق منه لكن السائق غير مسجل
// mySnackbarSuccess('Phone verified. Please complete registration.');
Get.to(() => SyrianCardAI());
}
} else {
mySnackeBarError(data['message'] ?? 'Verification failed.');
}
} else {
mySnackeBarError('Server error. Please try again.');
}
} catch (e) {
mySnackeBarError('An error occurred: $e');
Log.print('e: ${e}');
}
}
static Future<void> registerUser({
required String phoneNumber,
required String firstName,
required String lastName,
String? email,
}) async {
try {
final response = await CRUD().post(
link: _registerUrl,
payload: {
'phone_number': phoneNumber,
'first_name': firstName,
'last_name': lastName,
'email': email ?? '', // Send empty string if null
},
);
final data = (response);
if (data != 'failure') {
// Registration successful, log user in
await _handleSuccessfulLogin(data['message']);
} else {
mySnackeBarError(
"User with this phone number or email already exists.".tr);
}
} catch (e) {
Log.print('e: ${e}');
mySnackeBarError('An error occurred: $e');
}
}
static Future<void> _handleSuccessfulLogin(
Map<String, dynamic> userData) async {
mySnackbarSuccess('Welcome, ${userData['first_name']}!');
// Save user data to local storage (Hive box) using new keys
box.write(BoxName.passengerID, userData['id']);
box.write(BoxName.nameDriver, userData['first_name']);
box.write(BoxName.lastNameDriver, userData['last_name']);
box.write(BoxName.emailDriver, userData['email']);
box.write(BoxName.phoneDriver, userData['phone']);
Get.offAll(() => OnBoardingPage()); // Navigate to home
}
}

View File

@@ -0,0 +1,420 @@
import 'dart:convert';
import 'dart:math';
import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
import 'package:sefer_driver/views/auth/captin/cards/syrian_card_a_i.dart';
import 'package:sefer_driver/views/auth/captin/register_captin.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:flutter/material.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/controller/functions/ocr_controller.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/auth/captin/login_captin.dart';
import 'package:sefer_driver/views/auth/captin/verify_email_captain.dart';
import '../../../constant/colors.dart';
import '../../../views/auth/captin/ai_page.dart';
import '../../../views/auth/captin/car_license_page.dart';
import '../../../views/home/Captin/home_captain/home_captin.dart';
import '../../functions/encrypt_decrypt.dart';
import '../../functions/sms_egypt_controller.dart';
class RegisterCaptainController extends GetxController {
final formKey = GlobalKey<FormState>();
final formKey3 = GlobalKey<FormState>();
TextEditingController emailController = TextEditingController();
TextEditingController phoneController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController verifyCode = TextEditingController();
String birthDate = 'Birth Date'.tr;
String gender = 'Male'.tr;
bool isLoading = false;
bool isSent = false;
late String name;
late String licenseClass;
late String documentNo;
late String address;
late String height;
late String postalCode;
late String sex;
late String stateCode;
late String expireDate;
late String dob;
getBirthDate() {
Get.defaultDialog(
title: 'Select Date'.tr,
content: SizedBox(
width: 300,
child: CalendarDatePicker(
initialDate: DateTime.now().subtract(const Duration(days: 18 * 365)),
firstDate: DateTime.parse('1940-06-01'),
lastDate: DateTime.now().subtract(const Duration(days: 18 * 365)),
onDateChanged: (date) {
// Get the selected date and convert it to a DateTime object
DateTime dateTime = date;
// Call the getOrders() function from the controller
birthDate = dateTime.toString().split(' ')[0];
update();
Get.back();
},
// onDateChanged: (DateTime value) {},
),
),
);
}
@override
void onInit() {
// Get.put(SmsEgyptController());
super.onInit();
}
void changeGender(String value) {
gender = value;
update();
}
bool isValidEgyptianPhoneNumber(String phoneNumber) {
// Remove any non-digit characters (spaces, dashes, etc.)
phoneNumber = phoneNumber.replaceAll(RegExp(r'\D+'), '');
// Check if the phone number has exactly 11 digits
if (phoneNumber.length != 11) {
return false;
}
// Check if the phone number starts with 010, 011, 012, or 015
RegExp validPrefixes = RegExp(r'^01[0125]\d{8}$');
return validPrefixes.hasMatch(phoneNumber);
}
sendOtpMessage() async {
SmsEgyptController smsEgyptController = Get.put(SmsEgyptController());
isLoading = true;
update();
isLoading = true;
update();
if (formKey3.currentState!.validate()) {
if (box.read(BoxName.countryCode) == 'Egypt') {
if (isValidEgyptianPhoneNumber(phoneController.text)) {
var responseCheker = await CRUD()
.post(link: AppLink.checkPhoneNumberISVerfiedDriver, payload: {
'phone_number': ('+2${phoneController.text}'),
});
if (responseCheker != 'failure') {
var d = jsonDecode(responseCheker);
if (d['message'][0]['is_verified'].toString() == '1') {
Get.snackbar('Phone number is verified before'.tr, '',
backgroundColor: AppColor.greenColor);
box.write(BoxName.phoneVerified, '1');
box.write(BoxName.phone, ('+2${phoneController.text}'));
await Get.put(LoginDriverController()).loginWithGoogleCredential(
box.read(BoxName.driverID).toString(),
(box.read(BoxName.emailDriver).toString()),
);
} else {
await CRUD().post(link: AppLink.sendVerifyOtpMessage, payload: {
'phone_number': ('+2${phoneController.text}'),
"driverId": box.read(BoxName.driverID),
"email": (box.read(BoxName.emailDriver)),
});
isSent = true;
isLoading = false;
update();
}
} else {
await CRUD().post(link: AppLink.sendVerifyOtpMessage, payload: {
'phone_number': ('+2${phoneController.text}'),
"driverId": box.read(BoxName.driverID),
"email": box.read(BoxName.emailDriver),
});
isSent = true;
isLoading = false;
update();
}
} else {
mySnackeBarError(
'Phone Number wrong'.tr,
);
}
}
}
isLoading = false;
update();
}
DateTime? lastOtpSentTime; // Store the last OTP sent time
int otpResendInterval = 300; // 5 minutes in seconds
// Main function to handle OTP sending
// sendOtpMessage() async {
// if (_isOtpResendAllowed()) {
// isLoading = true;
// update();
// if (formKey3.currentState!.validate()) {
// String countryCode = box.read(BoxName.countryCode);
// String phoneNumber = phoneController.text;
// if (countryCode == 'Egypt' && isValidEgyptianPhoneNumber(phoneNumber)) {
// await _checkAndSendOtp(phoneNumber);
// } else {
// _showErrorMessage('Phone Number is not Egypt phone '.tr);
// }
// }
// isLoading = false;
// update();
// } else {
// _showCooldownMessage();
// }
// }
// Check if the resend OTP request is allowed (5 minutes cooldown)
// bool _isOtpResendAllowed() {
// if (lastOtpSentTime == null) return true;
// final int elapsedTime =
// DateTime.now().difference(lastOtpSentTime!).inSeconds;
// return elapsedTime >= otpResendInterval;
// }
// // Show message when user tries to resend OTP too soon
// void _showCooldownMessage() {
// int remainingTime = otpResendInterval -
// DateTime.now().difference(lastOtpSentTime!).inSeconds;
// Get.snackbar(
// 'Please wait ${remainingTime ~/ 60}:${(remainingTime % 60).toString().padLeft(2, '0')} minutes before requesting again',
// '',
// backgroundColor: AppColor.redColor,
// );
// }
// // Check if the phone number has been verified, and send OTP if not verified
// _checkAndSendOtp(String phoneNumber) async {
// var responseChecker = await CRUD().post(
// link: AppLink.checkPhoneNumberISVerfiedDriver,
// payload: {
// 'phone_number': '+2$phoneNumber',
// },
// );
// if (responseChecker != 'failure') {
// var responseData = jsonDecode(responseChecker);
// if (_isPhoneVerified(responseData)) {
// _handleAlreadyVerified();
// } else {
// await _sendOtpAndSms(phoneNumber);
// }
// } else {
// await _sendOtpAndSms(phoneNumber);
// }
// }
// Check if the phone number is already verified
bool _isPhoneVerified(dynamic responseData) {
return responseData['message'][0]['is_verified'].toString() == '1';
}
// Handle case where phone number is already verified
_handleAlreadyVerified() {
mySnackbarSuccess('Phone number is already verified'.tr);
box.write(BoxName.phoneVerified, '1');
box.write(BoxName.phone, ('+2${phoneController.text}'));
Get.put(LoginDriverController()).loginWithGoogleCredential(
box.read(BoxName.driverID).toString(),
box.read(BoxName.emailDriver).toString(),
);
}
// Send OTP and SMS
_sendOtpAndSms(String phoneNumber) async {
SmsEgyptController smsEgyptController = Get.put(SmsEgyptController());
int randomNumber = Random().nextInt(100000) + 1;
await CRUD().post(
link: AppLink.sendVerifyOtpMessage,
payload: {
'phone_number': ('+2$phoneNumber'),
'token_code': (randomNumber.toString()),
'driverId': box.read(BoxName.driverID),
'email': box.read(BoxName.emailDriver),
},
);
await smsEgyptController.sendSmsEgypt(phoneNumber);
lastOtpSentTime = DateTime.now(); // Update the last OTP sent time
isSent = true;
isLoading = false;
update();
}
verifySMSCode() async {
// var loginDriverController = Get.put(LoginDriverController());
if (formKey3.currentState!.validate()) {
var res = await CRUD().post(link: AppLink.verifyOtpDriver, payload: {
'phone_number': ('+2${phoneController.text}'),
'token_code': (verifyCode.text.toString()),
});
if (res != 'failure') {
// var dec = jsonDecode(res);
box.write(BoxName.phoneDriver, ('+2${phoneController.text}'));
box.write(BoxName.phoneVerified, '1');
// loginDriverController.isGoogleLogin == true
// ? await loginDriverController.loginUsingCredentialsWithoutGoogle(
// loginDriverController.passwordController.text.toString(),
// box.read(BoxName.emailDriver).toString(),
// )
// : await loginDriverController.loginUsingCredentials(
// box.read(BoxName.driverID).toString(),
// box.read(BoxName.emailDriver).toString(),
// );
Get.to(SyrianCardAI());
// } else {
// Get.snackbar('title', 'message');
// }
}
} else {
mySnackeBarError('you must insert token code '.tr);
}
}
sendVerifications() async {
var res = await CRUD().post(link: AppLink.verifyEmail, payload: {
'email': emailController.text.isEmpty
? (Get.find<LoginDriverController>().emailController.text.toString())
: (emailController.text),
'token': (verifyCode.text),
});
if (res != 'failure') {
if (Get.find<LoginDriverController>().emailController.text.toString() !=
'') {
Get.offAll(() => HomeCaptain());
} else {
// Get.to(() => CarLicensePage());
}
}
}
void nextToAIDetection() async {
//Todo dont forget this
if (formKey.currentState!.validate()) {
isLoading = true;
update();
Get.to(() => AiPage());
}
}
Map<String, dynamic> payloadLisence = {};
void getFromController() {
name = Get.find<ScanDocumentsByApi>().name;
licenseClass = Get.find<ScanDocumentsByApi>().licenseClass.toString();
documentNo = Get.find<ScanDocumentsByApi>().documentNo.toString();
address = Get.find<ScanDocumentsByApi>().address.toString();
height = Get.find<ScanDocumentsByApi>().height.toString();
postalCode = Get.find<ScanDocumentsByApi>().address.toString();
sex = Get.find<ScanDocumentsByApi>().sex.toString();
stateCode = Get.find<ScanDocumentsByApi>().postalCode.toString();
expireDate = Get.find<ScanDocumentsByApi>().expireDate.toString();
dob = Get.find<ScanDocumentsByApi>().dob.toString();
update();
}
Future addLisence() async {
getFromController();
var res = await CRUD().post(link: AppLink.addLicense, payload: {
'name': name,
'licenseClass': licenseClass,
'documentNo': documentNo,
'address': address,
'height': height,
'postalCode': postalCode,
'sex': sex,
'stateCode': stateCode,
'expireDate': expireDate,
'dateOfBirth': dob,
});
isLoading = false;
update();
if (jsonDecode(res)['status'] == 'success') {
// Get.to(() => AiPage()); //todo rplace this
}
}
void addRegisrationCarForDriver(String vin, make, model, year, color, owner,
expirationDate, registrationDate) async {
getFromController();
var res = await CRUD().post(link: AppLink.addRegisrationCar, payload: {
'vin': vin,
'make': make,
'model': model,
'year': year,
'expirationDate': expirationDate,
'color': color,
'owner': owner,
'registrationDate': registrationDate,
});
box.write(BoxName.vin, vin);
box.write(BoxName.make, make);
box.write(BoxName.model, model);
box.write(BoxName.year, year);
box.write(BoxName.expirationDate, expirationDate);
box.write(BoxName.color, color);
box.write(BoxName.owner, owner);
box.write(BoxName.registrationDate, registrationDate);
isLoading = false;
update();
if (jsonDecode(res)['status'] == 'success') {
Get.offAll(() => LoginCaptin()); //todo replace this
}
}
Future register() async {
getFromController();
if (formKey.currentState!.validate()) {
isLoading = true;
update();
var res = await CRUD().post(link: AppLink.signUpCaptin, payload: {
'first_name': name.split(' ')[1],
'last_name': name.split(' ')[0],
'email': emailController.text,
'phone': phoneController.text,
'password': passwordController.text,
'gender': sex,
'site': address,
'birthdate': dob,
});
isLoading = false;
update();
if (jsonDecode(res)['status'] == 'success') {
box.write(BoxName.driverID, jsonDecode(res)['message']);
box.write(BoxName.dobDriver, dob);
box.write(BoxName.sexDriver, sex);
box.write(BoxName.phoneDriver, phoneController.text);
box.write(BoxName.lastNameDriver, name.split(' ')[0]);
int randomNumber = Random().nextInt(100000) + 1;
await CRUD().post(link: AppLink.sendVerifyEmail, payload: {
'email': emailController.text,
'token': randomNumber.toString(),
});
Get.to(() => VerifyEmailCaptainPage());
}
}
}
}

View File

@@ -0,0 +1,30 @@
// import 'package:firebase_auth/firebase_auth.dart';
// import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
// class FacebookSignIn {
// Future<UserCredential?> signInWithFacebook() async {
// final LoginResult result = await FacebookAuth.instance.login();
// if (result.status == LoginStatus.success) {
// // Create a credential from the access token
// final OAuthCredential credential =
// FacebookAuthProvider.credential(result.accessToken!.tokenString);
// // Once signed in, return the UserCredential
// return await FirebaseAuth.instance.signInWithCredential(credential);
// }
// return null;
// }
// Future<void> signOut() async {
// try {
// await FacebookAuth.instance.logOut();
// print('Facebook Sign Out Successful');
// } catch (e) {
// print('Error during Facebook Sign Out: $e');
// }
// }
// Future<bool> isSignedIn() async {
// final accessToken = await FacebookAuth.instance.accessToken;
// return accessToken != null;
// }
// }

View File

@@ -0,0 +1,293 @@
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/auth/captin/cards/sms_signup.dart';
import 'package:sefer_driver/views/home/on_boarding_page.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';
import '../../views/auth/captin/ai_page.dart';
import '../functions/add_error.dart';
import '../functions/encrypt_decrypt.dart';
class GoogleSignInHelper {
static final GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'profile',
],
);
// Method to handle Google Sign-In
static Future<GoogleSignInAccount?> signIn() async {
try {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser != null) {
await _handleSignUp(googleUser);
if (box.read(BoxName.countryCode) == 'Egypt') {
Get.to(() => SmsSignupEgypt());
} else if (box.read(BoxName.countryCode) == 'Jordan') {
Get.to(() => AiPage());
}
}
return googleUser;
} catch (error) {
return null;
}
}
Future<GoogleSignInAccount?> signInFromLogin() async {
try {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser != null) {
// Handle sign-up and store user information
await _handleSignUp(googleUser);
// Retrieve driverID and emailDriver with added validation
final driverID =
(box.read(BoxName.driverID)!.toString()) ?? 'Unknown ID';
final emailDriver =
(box.read(BoxName.emailDriver)!.toString()) ?? 'Unknown Email';
// Debug print statements
print('Driver ID: $driverID');
print('Driver Email: $emailDriver');
// Check if driverID is a valid numeric string
// if (driverID != 'Unknown ID' && int.tryParse(driverID) != null) {
await Get.find<LoginDriverController>()
.loginWithGoogleCredential(driverID, emailDriver);
// }
// else {
// print('Invalid driverID format: $driverID');
// Get.snackbar('Login Error', 'Invalid driver ID format.',
// backgroundColor: AppColor.redColor);
// }
}
return googleUser;
} catch (error) {
mySnackeBarError('$error');
addError(error.toString(), 'GoogleSignInAccount?> signInFromLogin()');
return null;
}
}
static Future<void> _handleSignUp(GoogleSignInAccount user) async {
// Store driver information
box.write(BoxName.driverID,
(user.id) ?? 'Unknown ID'); // Ensure there's a fallback value
box.write(BoxName.emailDriver, (user.email) ?? 'Unknown Email');
}
// Method to handle Google Sign-Out
static Future<void> signOut() async {
try {
await _googleSignIn.signOut();
await _handleSignOut();
} catch (error) {}
}
static Future<void> _handleSignOut() async {
// Clear stored driver information
box.remove(BoxName.driverID);
box.remove(BoxName.emailDriver);
box.remove(BoxName.lang);
box.remove(BoxName.nameDriver);
box.remove(BoxName.passengerID);
box.remove(BoxName.phoneDriver);
box.remove(BoxName.tokenFCM);
box.remove(BoxName.tokens);
box.remove(BoxName.carPlate);
box.remove(BoxName.lastNameDriver);
box.remove(BoxName.agreeTerms);
box.remove(BoxName.tokenDriver);
box.remove(BoxName.countryCode);
box.remove(BoxName.accountIdStripeConnect);
box.remove(BoxName.phoneVerified);
Get.offAll(OnBoardingPage());
// Perform any additional sign-out tasks or API calls here
// For example, you can notify your server about the user sign-out
}
// Method to get the current signed-in user
static GoogleSignInAccount? getCurrentUser() {
return _googleSignIn.currentUser;
}
}
// import 'dart:async';
// import 'dart:async';
// import 'dart:convert';
// import 'package:flutter/material.dart';
// import 'package:get/get.dart';
// import 'package:http/http.dart' as http;
// import 'package:sefer_driver/constant/box_name.dart';
// import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
// import 'package:sefer_driver/main.dart';
// import 'package:sefer_driver/views/auth/captin/ai_page.dart';
// import 'package:sefer_driver/views/auth/captin/cards/sms_signup.dart';
// import 'package:sefer_driver/views/home/on_boarding_page.dart';
// import 'package:sefer_driver/views/widgets/error_snakbar.dart';
// import 'package:url_launcher/url_launcher.dart';
// import '../functions/add_error.dart';
// /// Helper class to manage Google Sign-In via an external browser and polling.
// class GoogleSignInHelper {
// // URLs for your server endpoints
// static const String _startLoginUrl =
// 'https://api.tripz-egypt.com/tripz/auth/google_auth/login.php';
// static const String _checkStatusUrl =
// 'https://api.tripz-egypt.com/tripz/auth/google_auth/check_status.php';
// static Future<void> _initiateSignIn(
// Function(Map<String, dynamic> userData) onSignInSuccess) async {
// try {
// // Show a loading dialog to the user
// Get.dialog(
// const Center(
// child: Material(
// color: Colors.transparent,
// child: Column(
// mainAxisSize: MainAxisSize.min,
// children: [
// CircularProgressIndicator(),
// SizedBox(height: 16),
// Text(
// "Waiting for browser sign-in...",
// style: TextStyle(color: Colors.white, fontSize: 16),
// ),
// ],
// ),
// ),
// ),
// barrierDismissible: false,
// );
// // 1. Get the auth URL and login token from the server
// final startResponse = await http.get(Uri.parse(_startLoginUrl));
// if (startResponse.statusCode != 200) {
// throw Exception('Failed to start login process.');
// }
// final startData = jsonDecode(startResponse.body);
// final String authUrl = startData['authUrl'];
// final String loginToken = startData['loginToken'];
// // 2. Launch the URL in an external browser
// if (!await launchUrl(Uri.parse(authUrl),
// mode: LaunchMode.externalApplication)) {
// throw Exception('Could not launch browser.');
// }
// // 3. Start polling the server for status
// await _startPolling(loginToken, onSignInSuccess);
// } catch (e) {
// addError(e.toString(), '_initiateSignIn');
// mySnackeBarError('Sign-in failed: ${e.toString()}');
// // Close the loading dialog on error
// if (Get.isDialogOpen ?? false) {
// Get.back();
// }
// }
// }
// static Future<void> _startPolling(String loginToken,
// Function(Map<String, dynamic> userData) onSignInSuccess) async {
// Timer? poller;
// const int maxAttempts = 30; // Poll for 60 seconds (30 attempts * 2s)
// int attempts = 0;
// poller = Timer.periodic(const Duration(seconds: 2), (timer) async {
// if (attempts >= maxAttempts) {
// timer.cancel();
// if (Get.isDialogOpen ?? false) Get.back();
// mySnackeBarError('Sign-in timed out. Please try again.');
// return;
// }
// attempts++;
// try {
// final statusResponse = await http.post(
// Uri.parse(_checkStatusUrl),
// headers: {'Content-Type': 'application/json'},
// body: jsonEncode({'loginToken': loginToken}),
// );
// if (statusResponse.statusCode == 200) {
// final statusData = jsonDecode(statusResponse.body);
// if (statusData['status'] == 'success') {
// timer.cancel();
// if (Get.isDialogOpen ?? false) Get.back();
// // Success!
// onSignInSuccess(statusData['userData']);
// }
// // If status is 'pending', do nothing and wait for the next poll.
// }
// } catch (e) {
// // Handle polling errors silently or log them
// debugPrint("Polling error: $e");
// }
// });
// }
// /// Triggers the sign-in process for a new user.
// static Future<void> signIn() async {
// await _initiateSignIn((userData) async {
// debugPrint('Sign-in success data: $userData');
// await _handleSignUp(userData);
// if (box.read(BoxName.countryCode) == 'Egypt') {
// Get.offAll(() => SmsSignupEgypt());
// } else if (box.read(BoxName.countryCode) == 'Jordan') {
// Get.offAll(() => AiPage());
// }
// });
// }
// /// Triggers the sign-in process for an existing user.
// static Future<void> signInFromLogin() async {
// await _initiateSignIn((userData) async {
// debugPrint('Sign-in from login success data: $userData');
// await _handleSignUp(userData);
// final driverID = userData['id']?.toString() ?? 'Unknown ID';
// final emailDriver = userData['email']?.toString() ?? 'Unknown Email';
// debugPrint('Driver ID from server: $driverID');
// debugPrint('Driver Email from server: $emailDriver');
// await Get.find<LoginDriverController>()
// .loginWithGoogleCredential(driverID, emailDriver);
// });
// }
// /// Stores user information received from the server.
// static Future<void> _handleSignUp(Map<String, dynamic> userData) async {
// box.write(BoxName.driverID, userData['id'] ?? 'Unknown ID');
// box.write(BoxName.emailDriver, userData['email'] ?? 'Unknown Email');
// }
// /// Clears local data.
// static Future<void> signOut() async {
// box.remove(BoxName.driverID);
// box.remove(BoxName.emailDriver);
// box.remove(BoxName.lang);
// box.remove(BoxName.nameDriver);
// box.remove(BoxName.passengerID);
// box.remove(BoxName.phoneDriver);
// box.remove(BoxName.tokenFCM);
// box.remove(BoxName.tokens);
// box.remove(BoxName.carPlate);
// box.remove(BoxName.lastNameDriver);
// box.remove(BoxName.agreeTerms);
// box.remove(BoxName.tokenDriver);
// box.remove(BoxName.countryCode);
// box.remove(BoxName.accountIdStripeConnect);
// box.remove(BoxName.phoneVerified);
// Get.offAll(() => OnBoardingPage());
// }
// }

View File

@@ -0,0 +1,117 @@
import 'dart:convert';
import 'dart:math';
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/controller/functions/secure_storage.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/auth/verify_email_page.dart';
import '../functions/encrypt_decrypt.dart';
class LoginController extends GetxController {
final formKey = GlobalKey<FormState>();
final formKeyAdmin = GlobalKey<FormState>();
TextEditingController emailController = TextEditingController();
TextEditingController phoneController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController adminPasswordController = TextEditingController();
TextEditingController adminNameController = TextEditingController();
bool isAgreeTerms = false;
bool isloading = false;
final FlutterSecureStorage _storage = const FlutterSecureStorage();
void changeAgreeTerm() {
isAgreeTerms = !isAgreeTerms;
update();
}
void saveAgreementTerms() {
box.write(BoxName.agreeTerms, 'agreed');
update();
}
void saveCountryCode(String countryCode) {
box.write(BoxName.countryCode, countryCode);
update();
}
void login() async {
isloading = true;
update();
var res = await CRUD().get(link: AppLink.login, payload: {
'email': emailController.text,
'phone': phoneController.text,
'password': passwordController.text
});
isloading = false;
update();
if (res == 'failure') {
//Failure
mySnackeBarError('');
} else {
var jsonDecoeded = jsonDecode(res);
if (jsonDecoeded.isNotEmpty) {
if (jsonDecoeded['status'] == 'success') {
if (jsonDecoeded['data'][0]['verified'] == 1) {
box.write(BoxName.driverID, jsonDecoeded['data'][0]['id']);
box.write(BoxName.emailDriver, (jsonDecoeded['data'][0]['email']));
box.write(
BoxName.nameDriver,
jsonDecoeded['data'][0]['first_name'] +
' ' +
jsonDecoeded['data'][0]['last_name']);
box.write(BoxName.phone, jsonDecoeded['data'][0]['phone']);
SecureStorage().saveData(BoxName.password, passwordController.text);
// Get.offAll(() => const MapPagePassenger());
isloading = false;
update();
await CRUD().post(link: AppLink.addTokens, payload: {
'token': box.read(BoxName.tokenFCM),
'passengerID': box.read(BoxName.passengerID).toString()
});
} else {
isloading = false;
update();
Get.defaultDialog(
title: 'You must Verify email !.'.tr,
middleText: '',
backgroundColor: Colors.yellow[300],
onConfirm: () async {
int randomNumber = Random().nextInt(100000) + 1;
await CRUD().post(link: AppLink.sendVerifyEmail, payload: {
'email': emailController.text,
'token': randomNumber.toString(),
});
Get.to(() => const VerifyEmailPage());
},
);
}
} else if (jsonDecoeded['status'] == 'Failure') {
mySnackeBarError(jsonDecoeded['data']);
isloading = false;
update();
}
} else {
isloading = false;
update();
}
}
}
goToMapPage() {
if (box.read(BoxName.email) != null) {
// Get.offAll(() => const MapPagePassenger());
}
}
@override
void onInit() {
super.onInit();
}
}

View File

@@ -0,0 +1,43 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/main.dart';
import '../../models/model/onboarding_model.dart';
import '../../views/auth/captin/login_captin.dart';
abstract class OnBoardingController extends GetxController {
next();
onPageChanged(int index);
}
class OnBoardingControllerImp extends OnBoardingController {
late PageController pageController;
int currentPage = 0;
@override
next() {
currentPage++;
if (currentPage > onBoardingList.length - 1) {
box.write(BoxName.onBoarding, 'yes');
Get.offAll(() => LoginCaptin());
} else {
pageController.animateToPage(currentPage,
duration: const Duration(milliseconds: 900), curve: Curves.easeInOut);
}
}
@override
onPageChanged(int index) {
currentPage = index;
update();
}
@override
void onInit() {
pageController = PageController();
super.onInit();
}
}

View File

@@ -0,0 +1,95 @@
import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/constant/style.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
import '../../views/auth/captin/login_captin.dart';
import '../../views/auth/verify_email_page.dart';
class RegisterController extends GetxController {
final formKey = GlobalKey<FormState>();
TextEditingController firstNameController = TextEditingController();
TextEditingController lastNameController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController phoneController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController siteController = TextEditingController();
TextEditingController verfyCode = TextEditingController();
String birthDate = 'Birth Date'.tr;
String gender = 'Male'.tr;
@override
void onInit() {
super.onInit();
}
getBirthDate() {
Get.defaultDialog(
title: 'Select Date'.tr,
titleStyle: AppStyle.title,
content: SizedBox(
width: 300,
child: CalendarDatePicker(
initialDate:
DateTime.now().subtract(const Duration(days: 14 * 365)),
firstDate: DateTime.parse('1940-06-01'),
lastDate: DateTime.now().subtract(const Duration(days: 14 * 365)),
onDateChanged: (date) {
// Get the selected date and convert it to a DateTime object
DateTime dateTime = date;
// Call the getOrders() function from the controller
birthDate = dateTime.toString().split(' ')[0];
update();
},
// onDateChanged: (DateTime value) {},
),
),
confirm: MyElevatedButton(title: 'Ok'.tr, onPressed: () => Get.back()));
}
void changeGender(String value) {
gender = value;
update();
}
sendVerifications() async {
var res = await CRUD().post(link: AppLink.verifyEmail, payload: {
'email': emailController.text,
'token': verfyCode.text,
});
var dec = jsonDecode(res);
if (dec['status'] == 'success') {
Get.offAll(() => LoginCaptin());
}
}
void register() async {
if (formKey.currentState!.validate()) {
var res = await CRUD().post(link: AppLink.signUp, payload: {
'first_name': firstNameController.text.toString(),
'last_name': lastNameController.text.toString(),
'email': emailController.text.toString(),
'phone': phoneController.text.toString(),
'password': passwordController.text.toString(),
'gender': 'yet',
'site': siteController.text,
'birthdate': birthDate,
});
if (jsonDecode(res)['status'] == 'success') {
int randomNumber = Random().nextInt(100000) + 1;
await CRUD().post(link: AppLink.sendVerifyEmail, payload: {
'email': emailController.text,
'token': randomNumber.toString(),
});
Get.to(() => const VerifyEmailPage());
}
}
}
}

View File

@@ -0,0 +1,38 @@
import 'dart:convert';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../main.dart';
class TokenController extends GetxController {
bool isloading = false;
Future addToken() async {
String? basicAuthCredentials =
await storage.read(key: BoxName.basicAuthCredentials);
isloading = true;
update();
var res = await http.post(
Uri.parse(AppLink.addTokens),
headers: {
'Authorization':
'Basic ${base64Encode(utf8.encode(basicAuthCredentials.toString()))}',
},
body: {
'token': box.read(BoxName.tokenFCM.toString()),
'passengerID': box.read(BoxName.passengerID).toString()
},
);
isloading = false;
update();
var jsonToken = jsonDecode(res.body);
if (jsonToken['status'] == 'The token has been updated successfully.') {
mySnackbarSuccess('token updated'.tr);
}
}
}

View File

@@ -0,0 +1,16 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
class VerifyEmailController extends GetxController {
TextEditingController verfyCode = TextEditingController();
@override
void onInit() async {
super.onInit();
}
sendverfications() async {
await CRUD().post(link: AppLink.sendVerifyEmail);
}
}