Initial commit for driver_tripz

This commit is contained in:
Hamza-Ayed
2026-01-20 23:45:40 +03:00
parent 322e4b9788
commit cb2a0f2493
400 changed files with 1450 additions and 49069 deletions

View File

@@ -1,203 +1,149 @@
import 'dart:io';
import 'package:Tripz/constant/box_name.dart';
import 'package:Tripz/controller/auth/login_controller.dart';
import 'package:Tripz/controller/functions/encrypt_decrypt.dart';
import 'package:Tripz/main.dart';
import 'package:Tripz/env/env.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:Tripz/constant/box_name.dart';
import 'package:Tripz/controller/auth/login_controller.dart';
import 'package:Tripz/main.dart';
import '../../constant/links.dart';
import '../../onbording_page.dart';
import '../../print.dart';
import '../functions/crud.dart';
import '../../onbording_page.dart';
class GoogleSignInHelper {
static final GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'profile',
],
);
// ✅ GoogleSignIn singleton
static final GoogleSignIn _signIn = GoogleSignIn.instance;
// Method to handle Google Sign-In
static GoogleSignInAccount? _lastUser;
/// 👇 استدعها في main() مرة واحدة
static Future<void> init() async {
await _signIn.initialize(
serverClientId: Env.serverClientId,
);
// Events listener
_signIn.authenticationEvents.listen((event) async {
if (event is GoogleSignInAuthenticationEventSignIn) {
_lastUser = event.user;
await _handleSignUp(event.user);
} else if (event is GoogleSignInAuthenticationEventSignOut) {
_lastUser = null;
}
});
// silent login if possible
try {
await _signIn.attemptLightweightAuthentication();
} catch (_) {}
}
/// ✅ تسجيل دخول عادي
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(() => EgyptCardAI());
// } else if (box.read(BoxName.countryCode) == 'Jordan') {
// Get.to(() => AiPage());
// }
final user =
await _signIn.authenticate(scopeHint: const ['email', 'profile']);
if (user != null) {
_lastUser = user;
await _handleSignUp(user);
// اطبع القيم (للتأكد)
print("Google ID: ${user.id}");
print("Email: ${user.email}");
print("Name: ${user.displayName}");
print("Photo: ${user.photoUrl}");
}
return googleUser;
} catch (error) {
return user;
} on PlatformException catch (e) {
if (e.code == 'sign_in_required') {
await showGooglePlayServicesError();
}
return null;
} catch (e) {
await addError("Google Sign-In error: $e", "signIn()");
return null;
}
}
Future<GoogleSignInAccount?> signInFromLogin() async {
try {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser != null) {
await _handleSignUp(googleUser);
await Get.put(LoginController()).loginUsingCredentials(
box.read(BoxName.passengerID).toString(),
box.read(BoxName.email).toString(),
);
}
return googleUser;
} catch (error) {
// if (error is GoogleSignInAuthenticationException) {
// // Handle authentication errors from Google Sign-In
// addError("Google sign-in authentication error: ${error.message}",
// '<GoogleSignInAccount?> signInFromLogin()');
// } else if (error is GoogleSignInAccountNotFoundException) {
// // Handle the case where the user is not found (if applicable)
// addError("Google sign-in account not found error: ${error.message}",
// '<GoogleSignInAccount?> signInFromLogin()');
// }
// else
if (error is SocketException) {
// Handle network issues, like SSL certificate issues
addError("Network error (SSL certificate issue): ${error.message}",
'<GoogleSignInAccount?> signInFromLogin()');
} else if (error is PlatformException) {
// Handle platform-specific errors, like Google Play Services issues
if (error.code == 'sign_in_required') {
// Google Play Services are required but not installed or outdated
showGooglePlayServicesError();
} else {
addError("Platform error: ${error.message}",
'<GoogleSignInAccount?> signInFromLogin()');
}
} else {
// Catch all other unknown errors
addError("Unknown error: ${error.toString()}",
'<GoogleSignInAccount?> signInFromLogin()');
}
return null;
}
}
void showGooglePlayServicesError() async {
const playStoreUrl =
'https://play.google.com/store/apps/details?id=com.google.android.gms&hl=en_US';
if (await canLaunchUrl(Uri.parse(playStoreUrl))) {
await launchUrl(Uri.parse(playStoreUrl));
} else {
// Fallback if the URL can't be opened
showDialog(
context: Get.context!,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Error'.tr),
content: Text(
'Could not open the Google Play Store. Please update Google Play Services manually.'
.tr),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('Close'.tr),
),
],
);
},
/// ✅ تسجيل دخول مخصص لشاشة Login (مع استدعاء الكنترولر)
static Future<GoogleSignInAccount?> signInFromLogin() async {
await init();
final user = await signIn();
if (user != null) {
await Get.put(LoginController()).loginUsingCredentials(
box.read(BoxName.passengerID).toString(),
box.read(BoxName.email).toString(),
);
}
return user;
}
// Future<GoogleSignInAccount?> signInFromLogin() async {
// try {
// final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
// if (googleUser != null) {
// await _handleSignUp(googleUser);
// // if (box.read(BoxName.countryCode) == 'Egypt') {
// await Get.put(LoginController()).loginUsingCredentials(
// box.read(BoxName.passengerID).toString(),
// box.read(BoxName.email).toString(),
// );
// // } else if (box.read(BoxName.countryCode) == 'Jordan') {
// // // Get.to(() => AiPage());
// // }
// }
// return googleUser;
// } catch (error) {
// addError(error.toString(), '<GoogleSignInAccount?> signInFromLogin()');
// return null;
// }
// }
/// ✅ طلب سكوبات إضافية (بديل withScopes القديم)
static Future<void> requestExtraScopes(List<String> scopes) async {
final user = _lastUser;
if (user == null) return;
await user.authorizationClient.authorizeScopes(scopes);
}
addError(String error, where) async {
CRUD().post(link: AppLink.addError, payload: {
'error': error.toString(), // Example error description
'userId': box.read(BoxName.driverID) ??
box.read(BoxName.passengerID), // Example user ID
'userType': box.read(BoxName.driverID) != null
? 'Driver'
: 'passenger', // Example user type
'phone': box.read(BoxName.phone) ??
box.read(BoxName.phoneDriver), // Example phone number
/// ✅ تسجيل خروج
static Future<void> signOut() async {
await _signIn.signOut();
await _handleSignOut();
}
'device': where
static GoogleSignInAccount? getCurrentUser() => _lastUser;
// ================= Helpers ==================
static Future<void> _handleSignUp(GoogleSignInAccount user) async {
box.write(BoxName.passengerID, user.id);
box.write(BoxName.email, user.email);
box.write(BoxName.name, user.displayName ?? '');
box.write(BoxName.passengerPhotoUrl, user.photoUrl ?? '');
}
static Future<void> _handleSignOut() async {
box.erase();
Get.offAll(OnBoardingPage());
}
static Future<void> addError(String error, String where) async {
await CRUD().post(link: AppLink.addError, payload: {
'error': error,
'userId': box.read(BoxName.driverID) ?? box.read(BoxName.passengerID),
'userType': box.read(BoxName.driverID) != null ? 'Driver' : 'Passenger',
'phone': box.read(BoxName.phone) ?? box.read(BoxName.phoneDriver),
'device': where,
});
}
// Method to handle Google Sign-Out
static Future<void> signOut() async {
try {
await _googleSignIn.signOut();
await _handleSignOut();
} catch (error) {}
}
// Method to get the current signed-in user
static GoogleSignInAccount? getCurrentUser() {
return _googleSignIn.currentUser;
}
// Method to handle sign-up process
static Future<void> _handleSignUp(GoogleSignInAccount user) async {
// Store driver information
box.write(BoxName.passengerID, user.id);
box.write(BoxName.email, (user.email));
box.write(BoxName.name, (user.displayName.toString()));
box.write(BoxName.passengerPhotoUrl, (user.photoUrl.toString()));
// Perform any additional sign-up tasks or API calls here
// For example, you can send the user data to your server for registration
}
// Method to handle sign-out process
static Future<void> _handleSignOut() async {
// Clear stored driver information
box.remove(BoxName.passengerPhotoUrl);
box.remove(BoxName.driverID);
box.remove(BoxName.email);
box.remove(BoxName.lang);
box.remove(BoxName.name);
box.remove(BoxName.passengerID);
box.remove(BoxName.phone);
box.remove(BoxName.tokenFCM);
box.remove(BoxName.tokens);
box.remove(BoxName.addHome);
box.remove(BoxName.addWork);
box.remove(BoxName.agreeTerms);
box.remove(BoxName.apiKeyRun);
box.remove(BoxName.countryCode);
box.remove(BoxName.accountIdStripeConnect);
box.remove(BoxName.passengerWalletTotal);
box.remove(BoxName.isVerified);
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
static Future<void> showGooglePlayServicesError() async {
const playStoreUrl =
'https://play.google.com/store/apps/details?id=com.google.android.gms&hl=en_US';
final uri = Uri.parse(playStoreUrl);
if (await canLaunchUrl(uri)) {
await launchUrl(uri);
} else {
showDialog(
context: Get.context!,
builder: (context) => AlertDialog(
title: Text('Error'.tr),
content: Text(
'Could not open the Google Play Store. Please update Google Play Services manually.'
.tr,
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('Close'.tr),
),
],
),
);
}
}
}

View File

@@ -5,80 +5,253 @@ import 'dart:math';
import 'package:Tripz/constant/colors.dart';
import 'package:Tripz/controller/auth/login_controller.dart';
import 'package:Tripz/controller/functions/add_error.dart';
import 'package:Tripz/controller/functions/encrypt_decrypt.dart';
import 'package:Tripz/views/home/map_page_passenger.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:Tripz/constant/links.dart';
import 'package:Tripz/constant/style.dart';
import 'package:Tripz/controller/functions/crud.dart';
import 'package:Tripz/views/auth/login_page.dart';
import 'package:Tripz/views/widgets/elevated_btn.dart';
import '../../constant/box_name.dart';
import '../../main.dart';
import '../../print.dart';
import '../../views/auth/verify_email_page.dart';
import '../../views/widgets/mydialoug.dart';
import '../functions/sms_controller.dart';
class RegisterController extends GetxController {
final formKey = GlobalKey<FormState>();
final formKey3 = GlobalKey<FormState>();
// --- Keys ---
final formKey = GlobalKey<FormState>(); // For main registration form
final formKey3 = GlobalKey<FormState>(); // For OTP verification form
// --- Text Controllers ---
TextEditingController firstNameController = TextEditingController();
TextEditingController lastNameController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController phoneController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController siteController = TextEditingController();
// TextEditingController verfyCode = TextEditingController();
TextEditingController verifyCode = TextEditingController();
int remainingTime = 300; // 5 minutes in seconds
bool isSent = false;
// --- State Management ---
bool isLoading = false;
bool isOtpSent = false;
int remainingTime = 300; // 5 minutes in seconds
Timer? _timer;
// --- User Data ---
String birthDate = 'Birth Date'.tr;
String gender = 'Male'.tr;
@override
void onInit() {
super.onInit();
}
void startTimer() {
@override
void onClose() {
_timer?.cancel();
super.onClose();
}
void _startTimer() {
_timer?.cancel(); // Cancel any existing timer
remainingTime = 300;
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (remainingTime > 0) {
remainingTime--;
update(); // Update UI to show countdown
} else {
timer.cancel();
isOtpSent = false;
update(); // Update UI to allow resend
}
});
}
/// STEP 1: Send OTP to the user's phone number via SMS or WhatsApp.
/// This function ONLY sends the OTP. It does NOT register the user.
Future<void> sendOtpMessage() async {
final String phoneNumber = phoneController.text.trim();
if (phoneNumber.isEmpty) {
Get.snackbar('Error'.tr, 'Please enter a phone number.'.tr,
backgroundColor: AppColor.redColor);
return;
}
// A simple check for general phone number validity (can be improved)
if (phoneNumber.length < 10) {
Get.snackbar('Error'.tr, 'The phone number seems too short.'.tr,
backgroundColor: AppColor.redColor);
return;
}
isLoading = true;
update();
try {
// Determine if the number is Egyptian to choose the sending method.
// International format: +20 followed by 10 digits (total 13 chars)
// Local format: 11 digits starting with 010, 011, 012, or 015.
final bool isEgyptian =
(phoneNumber.startsWith('+20') && phoneNumber.length == 13) ||
(RegExp(r'^01[0125]\d{8}$').hasMatch(phoneNumber));
final String method = isEgyptian ? 'sms' : 'whatsapp';
final String successMessage = isEgyptian
? 'An OTP has been sent to your phone via SMS.'.tr
: 'An OTP has been sent to your phone via WhatsApp.'.tr;
Log.print(
'Phone number identified as ${isEgyptian ? "Egyptian" : "International"}. Attempting to send OTP via $method.');
// API call to your backend to send the OTP.
// We assume the backend uses the 'method' parameter to decide how to send the OTP.
// If your backend uses different endpoints, you can change the 'link' parameter instead.
var response = await CRUD().post(
link: AppLink.sendVerifyOtpMessage,
payload: {
'phone_number': phoneNumber,
'method': method, // 'sms' or 'whatsapp'
},
);
Log.print('Send OTP Response: $response');
if (response != 'failure') {
isOtpSent = true;
_startTimer();
// After successfully sending the OTP, you should navigate to the
// OTP verification screen. Example:
// Get.to(() => OTPScreen());
Get.snackbar('Success'.tr, successMessage,
backgroundColor: AppColor.greenColor);
} else {
Get.snackbar('Error'.tr, 'Failed to send OTP. Please try again.'.tr,
backgroundColor: AppColor.redColor);
}
} catch (e) {
addError(e.toString(), 'passenger send OTP');
Get.snackbar('Error'.tr, 'An unexpected error occurred.'.tr,
backgroundColor: Colors.redAccent);
} finally {
isLoading = false;
update();
}
}
/// STEP 2: Verify the entered OTP and, if successful, register the user.
Future<void> verifyOtpAndRegister() async {
if (formKey3.currentState?.validate() != true) {
Get.snackbar('Error'.tr, "Please enter the verification code.".tr,
backgroundColor: AppColor.redColor);
return;
}
isLoading = true;
update();
try {
// First, verify the OTP with the backend
var verificationResponse = await CRUD().post(
link: AppLink.verifyOtpPassenger,
payload: {
'phone_number': phoneController.text.trim(),
'token': verifyCode.text.trim(),
},
);
if (verificationResponse != 'failure') {
// --- OTP VERIFICATION SUCCESSFUL ---
// Now, proceed with user registration.
Log.print("OTP Verified. Proceeding to registration.");
await _registerVerifiedUser();
} else {
// --- OTP VERIFICATION FAILED ---
Get.snackbar('Error'.tr, "Invalid verification code.".tr,
backgroundColor: Colors.redAccent);
}
} catch (e) {
addError(e.toString(), 'passenger verify OTP & sign up');
Get.snackbar('Error'.tr, "Something went wrong. Please try again.".tr,
backgroundColor: Colors.redAccent);
} finally {
isLoading = false;
update();
}
}
/// Private helper function to handle the actual registration logic.
/// This should ONLY be called after a successful OTP verification.
Future<void> _registerVerifiedUser() async {
try {
box.write(BoxName.phone, (phoneController.text.trim()));
var nameParts =
(box.read(BoxName.name) ?? "Unknown User").toString().split(' ');
var firstName = nameParts.isNotEmpty ? nameParts[0] : 'unknown';
var lastName =
nameParts.length > 1 ? nameParts.sublist(1).join(' ') : 'user';
var payload = {
'id': box.read(BoxName.passengerID),
'phone': (phoneController.text.trim()),
'email': box.read(BoxName.email),
'password': 'unknown', // This seems to be by design for social logins
'gender': 'unknown',
'birthdate': '2002-01-01',
'site': box.read(BoxName.passengerPhotoUrl) ?? 'unknown',
'first_name': firstName,
'last_name': lastName,
};
var registrationResponse = await CRUD().post(
link: AppLink.signUp,
payload: payload,
);
if (registrationResponse != 'failure') {
// --- REGISTRATION SUCCESSFUL ---
// This part for multi-server can be kept as is.
// Save user state
box.write(BoxName.isVerified, '1');
box.write(BoxName.isFirstTime, '0');
// Log the user in
Get.put(LoginController()).loginUsingCredentials(
box.read(BoxName.passengerID).toString(),
box.read(BoxName.email).toString(),
);
} else {
Get.snackbar(
'Error'.tr, "The email or phone number is already registered.".tr,
backgroundColor: Colors.redAccent);
}
} catch (e) {
addError(e.toString(), 'passenger _registerVerifiedUser');
Get.snackbar('Error'.tr, "An error occurred during registration.".tr,
backgroundColor: Colors.redAccent);
}
}
// --- Other existing functions (unchanged) ---
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) {},
),
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) {
birthDate = date.toString().split(' ')[0];
update();
Get.back();
},
),
confirm: MyElevatedButton(title: 'Ok'.tr, onPressed: () => Get.back()));
),
);
}
void changeGender(String value) {
@@ -86,271 +259,9 @@ class RegisterController extends GetxController {
update();
}
bool isValidEgyptianPhoneNumber(String phoneNumber) {
// Remove any whitespace from the phone number
phoneNumber = phoneNumber.replaceAll(RegExp(r'\s+'), '');
// 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);
}
bool isValidPhoneNumber(String phoneNumber) {
// Remove any whitespace from the phone number
phoneNumber = phoneNumber.replaceAll(RegExp(r'\s+'), '');
// Check if the phone number has at least 10 digits
if (phoneNumber.length < 10) {
return false;
}
// Check for valid prefixes (modify this to match your use case)
RegExp validPrefixes = RegExp(r'^[0-9]+$');
// Check if the phone number contains only digits
return validPrefixes.hasMatch(phoneNumber);
}
sendOtpMessage() async {
SmsEgyptController smsEgyptController;
isLoading = true;
update();
try {
// Initialize SmsEgyptController
smsEgyptController = Get.put(SmsEgyptController());
isLoading = true;
update();
// Get phone number from controller
String phoneNumber = phoneController.text;
// Check if the phone number is from Egypt (Assuming Egyptian numbers start with +20)
if (phoneController.text.isNotEmpty) {
bool isEgyptianNumber = phoneNumber.startsWith('+20');
if (isEgyptianNumber && phoneNumber.length == 13) {
// Check if the phone number is already verified
var responseChecker = await CRUD().post(
link: AppLink.checkPhoneNumberISVerfiedPassenger,
payload: {
'phone_number': (phoneNumber),
'email': box.read(BoxName.email),
},
);
if (responseChecker != 'failure') {
var data = jsonDecode(responseChecker);
// If the phone number is already verified
if (data['message'][0]['verified'].toString() == '1') {
Get.snackbar('Phone number is verified before'.tr, '',
backgroundColor: AppColor.greenColor);
box.write(BoxName.isVerified, '1');
box.write(BoxName.phone, (phoneNumber));
Get.offAll(const MapPagePassenger());
} else {
await sendOtp(phoneNumber, isEgyptianNumber, smsEgyptController);
}
} else {
await sendOtp(phoneNumber, isEgyptianNumber, smsEgyptController);
}
} else if (phoneNumber.length > 9) {
sendOtp(phoneNumber, isEgyptianNumber, smsEgyptController);
}
} else {
MyDialog().getDialog(
'Error'.tr, 'Phone number must be exactly 11 digits long'.tr, () {
Get.back();
});
// sendOtp(
// phoneNumber, randomNumber, isEgyptianNumber, smsEgyptController);
}
} catch (e) {
// Handle error
} finally {
isLoading = false;
update();
}
}
// Helper function to send OTP or WhatsApp message based on phone number location
Future<void> sendOtp(String phoneNumber, bool isEgyptian,
SmsEgyptController controller) async {
// Trim any leading or trailing whitespace from the phone number
phoneNumber = phoneNumber.trim();
var dd = await CRUD().post(link: AppLink.sendVerifyOtpMessage, payload: {
'phone_number': (phoneNumber),
});
Log.print('dd: ${dd}');
// Common Registration Logic (extracted for reuse)
Future<void> registerUser() async {
await CRUD().post(link: AppLink.updatePhoneInvalidSMSPassenger, payload: {
"phone_number": (Get.find<RegisterController>().phoneController.text)
});
box.write(BoxName.phone, (phoneController.text));
var nameParts = (box.read(BoxName.name)).toString().split(' ');
var firstName = nameParts.isNotEmpty ? nameParts[0] : 'unknown';
var lastName = nameParts.length > 1 ? nameParts[1] : 'unknown';
var payload = {
'id': box.read(BoxName.passengerID),
'phone': (phoneController.text),
'email': box.read(BoxName.email),
'password':
('unknown'), //Consider if you *really* want to store 'unknown' passwords
'gender': ('unknown'),
'birthdate': ('2002-01-01'),
'site': box.read(BoxName.passengerPhotoUrl) ?? 'unknown',
'first_name': (firstName),
'last_name': (lastName),
};
var res1 = await CRUD().post(
link: AppLink.signUp,
payload: payload,
);
if (res1 != 'failure') {
//Multi-server signup (moved inside the successful registration check)
if (AppLink.tripzAlexandriaServer != AppLink.tripzCairoServer) {
List<Future> signUp = [
CRUD().post(
link: '${AppLink.tripzAlexandriaServer}/auth/signup.php',
payload: payload,
),
CRUD().post(
link: '${AppLink.tripzGizaServer}/auth/signup.php',
payload: payload,
)
];
await Future.wait(signUp); // Wait for both sign-ups to complete.
}
box.write(BoxName.isVerified, '1');
box.write(
BoxName.isFirstTime, '0'); //Double-check the logic for isFirstTime
box.write(BoxName.phone, (phoneController.text));
Get.put(LoginController()).loginUsingCredentials(
box.read(BoxName.passengerID).toString(),
box.read(BoxName.email).toString(),
);
}
}
if (isEgyptian) {
// verifySMSCode();
// await registerUser(); // Use the common registration logic
// await controller.sendSmsEgypt(phoneNumber, otp.toString()); // Optional: Send SMS if Egyptian
} else if (phoneController.text.toString().length >= 10) {
await registerUser(); // Use the common registration logic for non-Egyptian users as well.
// this for whatsapp messsage // Optional: Send WhatsApp message
// await CRUD().sendWhatsAppAuth(phoneNumber, otp.toString());
}
isLoading = false;
isSent = true;
remainingTime = 300;
update(); // Reset to 5 minutes
// startTimer(); // Consider whether you need a timer here, or if it's handled elsewhere.
}
verifySMSCode() async {
try {
if (formKey3.currentState!.validate()) {
var res = await CRUD().post(link: AppLink.verifyOtpPassenger, payload: {
'phone_number': phoneController.text,
'token': verifyCode.text,
});
if (res != 'failure') {
box.write(BoxName.phone, (phoneController.text));
var nameParts = (box.read(BoxName.name)).toString().split(' ');
var firstName = nameParts.isNotEmpty ? nameParts[0] : 'unknown';
var lastName = nameParts.length > 1 ? nameParts[1] : 'unknown';
var payload = {
'id': box.read(BoxName.passengerID),
'phone': (phoneController.text),
'email': box.read(BoxName.email),
'password': 'unknown',
'gender': 'unknown',
'birthdate': '2002-01-01',
'site': box.read(BoxName.passengerPhotoUrl) ?? 'unknown',
'first_name': firstName,
'last_name': lastName,
};
var res1 = await CRUD().post(
link: AppLink.signUp,
payload: payload,
);
if (res1 != 'failure') {
if (AppLink.tripzAlexandriaServer != AppLink.tripzCairoServer) {
List<Future> signUp = [
CRUD().post(
link: '${AppLink.tripzAlexandriaServer}/auth/signup.php',
payload: payload,
),
CRUD().post(
link: '${AppLink.tripzGizaServer}/auth/signup.php',
payload: payload,
)
];
await Future.wait(signUp);
}
box.write(BoxName.isVerified, '1');
box.write(BoxName.isFirstTime, '0');
box.write(BoxName.phone, (phoneController.text));
Get.put(LoginController()).loginUsingCredentials(
box.read(BoxName.passengerID).toString(),
box.read(BoxName.email).toString(),
);
} else {
Get.snackbar('Error'.tr,
"The email or phone number is already registered.".tr,
backgroundColor: Colors.redAccent);
}
} else {
Get.snackbar('Error'.tr, "phone not verified".tr,
backgroundColor: Colors.redAccent);
}
} else {
Get.snackbar('Error'.tr, "you must insert token code".tr,
backgroundColor: AppColor.redColor);
}
} catch (e) {
addError(e.toString(), 'passenger sign up ');
Get.snackbar('Error'.tr, "Something went wrong. Please try again.".tr,
backgroundColor: Colors.redAccent);
}
}
sendVerifications() async {
var res = await CRUD().post(link: AppLink.verifyEmail, payload: {
'email': emailController.text,
'token': verifyCode.text,
});
var dec = jsonDecode(res);
if (dec['status'] == 'success') {
Get.offAll(() => LoginPage());
}
}
void register() async {
/// This is the old registration method, likely for a standard email/password form.
/// It seems separate from the OTP flow, so I'm leaving it as is.
void registerWithEmailPassword() async {
if (formKey.currentState!.validate()) {
var res = await CRUD().post(link: AppLink.signUp, payload: {
'first_name': firstNameController.text.toString(),
@@ -372,10 +283,4 @@ class RegisterController extends GetxController {
}
}
}
@override
void onClose() {
_timer?.cancel();
super.onClose();
}
}

View File

@@ -658,7 +658,7 @@ class FirebaseMessagesController extends GetxController {
// Obtain an OAuth 2.0 access token
final accessToken = await accessTokenManager.getAccessToken();
// Log.print('accessToken: ${accessToken}');
Log.print('accessToken: ${accessToken}');
// Send the notification
final response = await http.post(

View File

@@ -273,8 +273,8 @@ class NotificationController extends GetxController {
scheduledTZDateTime,
details,
androidScheduleMode: AndroidScheduleMode.exact,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
// uiLocalNotificationDateInterpretation:
// UILocalNotificationDateInterpretation.absoluteTime,
matchDateTimeComponents:
null, // Don't repeat automatically; we handle manually
);
@@ -320,8 +320,8 @@ class NotificationController extends GetxController {
scheduledDate,
details,
androidScheduleMode: AndroidScheduleMode.exact,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
// uiLocalNotificationDateInterpretation:
// UILocalNotificationDateInterpretation.absoluteTime,
matchDateTimeComponents:
null, // Don't repeat automatically; we handle 7 days manually
);

View File

@@ -38,6 +38,7 @@ class CRUD {
// print('req: ${response.request}');
// Log.print('response: ${response.body}');
// Log.print('payload: ${payload}');
if (response.statusCode == 200) {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
@@ -52,11 +53,11 @@ class CRUD {
if (jsonData['error'] == 'Token expired') {
// Show snackbar prompting to re-login
await Get.put(LoginController()).getJWT();
mySnackbarSuccess('please order now'.tr);
// mySnackbarSuccess('please order now'.tr);
return 'token_expired'; // Return a specific value for token expiration
} else {
// Other 401 errors
addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
// addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
return 'failure';
}
} else {
@@ -88,6 +89,7 @@ class CRUD {
// print('req: ${response.request}');
// Log.print('response: ${response.body}');
// Log.print('payload: ${payload}');
if (response.statusCode == 200) {
var jsonData = jsonDecode(response.body);
Log.print('jsonData: $jsonData');
@@ -107,7 +109,7 @@ class CRUD {
return 'token_expired'; // Return a specific value for token expiration
} else {
// Other 401 errors
addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
// addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401');
return 'failure';
}
} else {
@@ -134,6 +136,7 @@ class CRUD {
// Log.print('req: ${response.request}');
// Log.print('response: ${response.body}');
// Log.print('payload: ${payload}');
if (response.statusCode == 200) {
try {
var jsonData = jsonDecode(response.body);
@@ -175,7 +178,7 @@ class CRUD {
return 'failure';
}
} catch (e) {
// addError('HTTP request error: $e', 'crud().post - HTTP');
addError('HTTP request error: $e', 'crud().post - HTTP');
return 'failure';
}
}
@@ -200,6 +203,7 @@ class CRUD {
// print('req: ${response.request}');
// Log.print('response: ${response.body}');
// Log.print('payload: ${payload}');
if (response.statusCode == 200) {
try {
var jsonData = jsonDecode(response.body);
@@ -209,7 +213,7 @@ class CRUD {
return jsonData['status'];
}
} catch (e) {
addError(e.toString(), 'crud().post - JSON decoding');
// addError(e.toString(), 'crud().post - JSON decoding');
return 'failure';
}
} else if (response.statusCode == 401) {
@@ -217,18 +221,6 @@ class CRUD {
var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
// Show snackbar prompting to re-login
await Get.put(LoginController()).getJWT();
// MyDialog().getDialog(
// 'Session expired. Please log in again.'.tr,
// '',
// () {
// Get.put(LoginController()).loginUsingCredentials(
// box.read(BoxName.passengerID), box.read(BoxName.email));
// Get.back();
// },
// );
return 'token_expired'; // Return a specific value for token expiration
} else {
// Other 401 errors
@@ -241,7 +233,7 @@ class CRUD {
return 'failure';
}
} catch (e) {
// addError('HTTP request error: $e', 'crud().post - HTTP');
addError('HTTP request error: $e', 'crud().post - HTTP');
return 'failure';
}
}

View File

@@ -22,7 +22,7 @@ class DeviceInfoPlus {
'sdkVersion': androidInfo.version.sdkInt,
'manufacturer': androidInfo.manufacturer,
'isPhysicalDevice': androidInfo.isPhysicalDevice,
'serialNumber': androidInfo.serialNumber,
'serialNumber': androidInfo.fingerprint,
'fingerprint': androidInfo.fingerprint,
'type': androidInfo.type,
'data': androidInfo.data,

View File

@@ -9,7 +9,7 @@ import 'package:Tripz/controller/payment/payment_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:get/get.dart';
import 'package:share/share.dart';
import 'package:share_plus/share_plus.dart';
import '../../../main.dart';
import '../../../print.dart';

View File

@@ -14,7 +14,7 @@ ThemeData lightThemeEnglish = ThemeData(
bodyMedium: AppStyle.subtitle,
),
primarySwatch: Colors.blue,
dialogTheme: DialogTheme(
dialogTheme: DialogThemeData(
backgroundColor: AppColor.secondaryColor,
contentTextStyle: AppStyle.title,
titleTextStyle: AppStyle.headTitle2,
@@ -50,7 +50,7 @@ ThemeData darkThemeEnglish = ThemeData(
bodyMedium: AppStyle.subtitle,
),
primarySwatch: Colors.blue,
dialogTheme: DialogTheme(
dialogTheme: DialogThemeData(
backgroundColor: AppColor.secondaryColor,
contentTextStyle: AppStyle.title,
titleTextStyle: AppStyle.headTitle2,
@@ -86,7 +86,7 @@ ThemeData lightThemeArabic = ThemeData(
bodyMedium: AppStyle.subtitle,
),
primarySwatch: Colors.blue,
dialogTheme: DialogTheme(
dialogTheme: DialogThemeData(
backgroundColor: AppColor.secondaryColor,
contentTextStyle: AppStyle.title,
titleTextStyle: AppStyle.headTitle2,
@@ -122,7 +122,7 @@ ThemeData darkThemeArabic = ThemeData(
bodyMedium: AppStyle.subtitle,
),
primarySwatch: Colors.blue,
dialogTheme: DialogTheme(
dialogTheme: DialogThemeData(
backgroundColor: AppColor.secondaryColor,
contentTextStyle: AppStyle.title,
titleTextStyle: AppStyle.headTitle2,

View File

@@ -20,6 +20,7 @@ import 'package:wakelock_plus/wakelock_plus.dart';
import 'constant/api_key.dart';
import 'constant/info.dart';
import 'constant/notification.dart';
import 'controller/auth/google_sign.dart';
import 'controller/firebase/firbase_messge.dart';
import 'controller/firebase/local_notification.dart';
import 'controller/functions/encrypt_decrypt.dart';

View File

@@ -76,7 +76,15 @@ class LoginPage extends StatelessWidget {
),
),
InkWell(
onTap: () async => await GoogleSignInHelper().signInFromLogin(),
onTap: () async {
final user =
await GoogleSignInHelper.signInFromLogin(); // 👈 استخدم هذا
if (user != null) {
print("Login success: ${user.email}");
// روح على الصفحة الرئيسية بعد تسجيل الدخول
// Get.offAll(() => HomePage());
}
},
child: _buildSocialButton(
icon: FontAwesome.google,
text: 'Sign In with Google'.tr,

View File

@@ -279,9 +279,9 @@ class RegisterPage extends StatelessWidget {
// )
],
),
MyElevatedButton(
title: 'Register'.tr,
onPressed: () => controller.register())
// MyElevatedButton(
// title: 'Register'.tr,
// // onPressed: () => controller.register())
]),
),
),

View File

@@ -83,7 +83,7 @@ class SmsSignupEgypt extends StatelessWidget {
const SizedBox(
height: 10,
),
if (registerController.isSent)
if (registerController.isOtpSent)
Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
@@ -102,9 +102,9 @@ class SmsSignupEgypt extends StatelessWidget {
padding: const EdgeInsets.all(16.0),
child: MyElevatedButton(
onPressed: () async {
!registerController.isSent
!registerController.isOtpSent
? await registerController.sendOtpMessage()
: await registerController.verifySMSCode();
: await registerController.verifyOtpAndRegister();
},
title: 'Submit'.tr,
),

View File

@@ -51,9 +51,9 @@ class VerifyEmailPage extends StatelessWidget {
const SizedBox(
height: 30,
),
MyElevatedButton(
title: 'Send Verfication Code'.tr,
onPressed: () => controller.sendVerifications())
// MyElevatedButton(
// title: 'Send Verfication Code'.tr,
// onPressed: () => controller.sendVerifications())
],
),
),

View File

@@ -2,8 +2,8 @@ import 'package:Tripz/views/widgets/my_scafold.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:share/share.dart';
import 'package:path/path.dart' as path;
import 'package:share_plus/share_plus.dart';
import '../../../controller/functions/audio_record1.dart';
@@ -194,7 +194,8 @@ class TripsRecordedPage extends StatelessWidget {
padding: EdgeInsets.zero,
child: const Icon(CupertinoIcons.share),
onPressed: () {
Share.shareFiles([audio.selectedFilePath!]);
Share.shareXFiles(
[XFile(audio.selectedFilePath!)]);
},
),
],

View File

@@ -95,7 +95,9 @@ class TestPage extends StatelessWidget {
firebaseMessagesController.sendNotificationToDriverMAP(
'Order',
'body',
'c2tXiuBJQCSg4CU4IfqYOL:APA91bFA0f8R3QMnPQnPEEdNyjY-jcoKt4nLBHxcLLsmDSuJn5yd4jSvwq7qDIZpkkPkjfjdwdKsGL0-G0aHpPyjfiBvbCwFmlRMCUKftNMNT7MJx2Bp16Y',
'enYFlS8ART-JNfvxgqSqut:APA91bG2pCi6LQjEVeBr8fbaBBIwXfdFUIelznzhmb-77xWMn0F3sCvzrNSXdHkvKbrvGQcQf5RyP-KfAfHOK3Z0Giu7_iau8Zg5UJ9ZIXzSzAhr4qV9emY'
// 'c2tXiuBJQCSg4CU4IfqYOL:APA91bFA0f8R3QMnPQnPEEdNyjY-jcoKt4nLBHxcLLsmDSuJn5yd4jSvwq7qDIZpkkPkjfjdwdKsGL0-G0aHpPyjfiBvbCwFmlRMCUKftNMNT7MJx2Bp16Y',
,
[
"32.1117875",
"36.0669891",