flutter(rider): rebuild lib on Cubit/Bloc + Tripz backend (core + auth slice)

- keep store identity (com.mobileapp.store.ride, shorebird, firebase, fonts); old lib -> lib_old_getx
- core: config/di/router(go_router)/theme/api_client(dio+tenant+bearer)/token_store(secure)
- auth: repo + AuthCubit + OTP phone/otp screens; home: flutter_map (OSM placeholder, انطلق TODO)
- android usesCleartextTraffic=true for http API; maps=flutter_map (no Google), state=Cubit

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-16 20:47:55 +03:00
co-authored by Claude Opus 4.8
parent 6234e66471
commit 6116d23d0c
203 changed files with 573 additions and 83094 deletions
@@ -1,37 +0,0 @@
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;
}
}
Future<void> signOut() async {
try {
await _auth.signOut();
} catch (error) {}
}
}
@@ -1,40 +0,0 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
Future<bool> verifyCertificateManually(
String host, int port, String expectedPin) async {
try {
final socket = await SecureSocket.connect(host, port,
timeout: const Duration(seconds: 5));
final certificate = socket.peerCertificate;
if (certificate == null) {
print("❌ لا يوجد شهادة.");
return false;
}
final der = certificate.der;
final actualPin = base64.encode(sha256.convert(der).bytes);
print("📛 HOST: $host");
print("📜 Subject: ${certificate.subject}");
print("📜 Issuer: ${certificate.issuer}");
print("📅 Valid From: ${certificate.startValidity}");
print("📅 Valid To: ${certificate.endValidity}");
print(
"🔐 Server Pin: $actualPin → ${actualPin == expectedPin ? '✅ MATCH' : '❌ MISMATCH'}");
socket.destroy();
return actualPin == expectedPin;
} catch (e) {
print("❌ خطأ أثناء الاتصال أو الفحص: $e");
return false;
}
}
/// تحويل المفتاح العام إلى بصمة SHA-256
List<int> sha256Convert(Uint8List der) {
return sha256.convert(der).bytes;
}
@@ -1,149 +0,0 @@
import 'dart:io';
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 '../functions/crud.dart';
import '../../onbording_page.dart';
class GoogleSignInHelper {
// ✅ GoogleSignIn singleton
static final GoogleSignIn _signIn = GoogleSignIn.instance;
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 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 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;
}
}
/// ✅ تسجيل دخول مخصص لشاشة 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;
}
/// ✅ طلب سكوبات إضافية (بديل withScopes القديم)
static Future<void> requestExtraScopes(List<String> scopes) async {
final user = _lastUser;
if (user == null) return;
await user.authorizationClient.authorizeScopes(scopes);
}
/// ✅ تسجيل خروج
static Future<void> signOut() async {
await _signIn.signOut();
await _handleSignOut();
}
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,
});
}
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),
),
],
),
);
}
}
}
@@ -1,451 +0,0 @@
import 'dart:convert';
import 'dart:io';
import 'package:Tripz/constant/api_key.dart';
import 'package:Tripz/controller/firebase/firbase_messge.dart';
import 'package:Tripz/views/auth/otp_page.dart';
import 'package:http/http.dart' as http;
import 'package:Tripz/constant/info.dart';
import 'package:Tripz/controller/functions/add_error.dart';
import 'package:Tripz/views/auth/login_page.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:Tripz/constant/box_name.dart';
import 'package:Tripz/constant/links.dart';
import 'package:Tripz/controller/functions/crud.dart';
import 'package:Tripz/main.dart';
import 'package:Tripz/views/home/map_page_passenger.dart';
import 'package:location/location.dart';
import '../../print.dart';
import '../../views/auth/otp_token_page.dart';
import '../functions/encrypt_decrypt.dart';
import '../functions/package_info.dart';
import '../functions/secure_storage.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;
late int isTest = 1;
void changeAgreeTerm() {
isAgreeTerms = !isAgreeTerms;
update();
}
var dev = '';
@override
void onInit() async {
await getJWT();
// Log.print('box.read(BoxName.isTest): ${box.read(BoxName.isTest)}');
box.write(BoxName.countryCode, 'Syria');
FirebaseMessagesController().getToken();
super.onInit();
}
// getAppTester() async {
// var res = await CRUD().get(
// link: AppLink.getTesterApp,
// payload: {'appPlatform': AppInformation.appName});
// if (res != 'failure') {
// var d = jsonDecode(res);
// isTest = int.parse(d['message'][0]['isTest'].toString());
// box.write(BoxName.isTest, isTest);
// update();
// } else {
// box.write(BoxName.isTest, '1');
// update();
// return false;
// }
// }
// updateAppTester(String appPlatform) async {
// await CRUD().post(
// link: AppLink.updateTesterApp, payload: {'appPlatform': appPlatform});
// }
void saveAgreementTerms() {
box.write(BoxName.agreeTerms, 'agreed');
update();
}
void saveCountryCode(String countryCode) {
box.write(BoxName.countryCode, countryCode);
update();
}
getJwtWallet() async {
try {
if (box.read(BoxName.security_check).toString() != 'passed') {
Log.print('Security check failed');
return;
}
Log.print('Security check passed');
String fingerPrint = await DeviceHelper.getDeviceFingerprint();
final dev = GetPlatform.isAndroid ? 'android' : 'ios';
var payload = {
'id': box.read(BoxName.passengerID),
'password': AK.passnpassenger,
'aud': '${AK.allowed}$dev',
'fingerPrint': fingerPrint,
};
var response = await http.post(
Uri.parse(AppLink.loginJwtWalletRider),
body: payload,
);
// Handle bad responses
if (response.statusCode != 200) {
_showJwtErrorDialog(
"حدث خطأ أثناء الاتصال بالخادم. يرجى المحاولة مرة أخرى.");
throw Exception("JWT request failed");
}
var data = jsonDecode(response.body);
// Validate JWT response structure
if (!data.containsKey('jwt') || !data.containsKey('hmac')) {
_showJwtErrorDialog("تعذّر التحقق من الأمان. يرجى إعادة المحاولة.");
throw Exception("Invalid JWT response format");
}
// Save HMAC locally
await box.write(BoxName.hmac, data['hmac']);
return data['jwt'].toString();
} catch (e) {
_showJwtErrorDialog("حدث خلل غير متوقع. يرجى المحاولة مرة أخرى.");
rethrow;
}
}
void _showJwtErrorDialog(String message) {
if (Get.context == null) return;
Get.defaultDialog(
title: "خطأ في الاتصال",
middleText: message,
textConfirm: "إعادة المحاولة",
confirmTextColor: Colors.white,
onConfirm: () {
Get.back();
getJwtWallet();
},
);
}
getJWT() async {
// print(Pasenger.pasengerpas);
// await SecurityHelper.performSecurityChecks();
Log.print('firstTimeLoadKey: ${box.read(BoxName.firstTimeLoadKey)}');
dev = Platform.isAndroid ? 'android' : 'ios';
if (box.read(BoxName.firstTimeLoadKey).toString() != 'false') {
var payload = {
'id': box.read(BoxName.passengerID) ?? AK.newId,
'password': AK.passnpassenger,
'aud': '${AK.allowed}$dev',
};
// Log.print('payload: ${payload}');
var response0 = await http.post(
Uri.parse(AppLink.loginFirstTime),
body: payload,
);
if (response0.statusCode == 200) {
final decodedResponse1 = jsonDecode(response0.body);
final jwt = decodedResponse1['jwt'];
final refreshToken = decodedResponse1['refresh_token'];
box.write(BoxName.jwt, c(jwt));
// Sss.write(BoxName.jwt, jwt);
await storage.write(key: BoxName.refreshToken, value: refreshToken);
// await AppInitializer().getAIKey(Pasenger.keyOfApp);
// await AppInitializer().getAIKey(Pasenger.initializationVector);
// await Future.delayed(Duration.zero);
await EncryptionHelper.initialize();
await AppInitializer().getKey();
} else {}
} else {
await EncryptionHelper.initialize();
var payload = {
'id': box.read(BoxName.passengerID),
'password': box.read(BoxName.email),
'aud': '${AK.allowed}$dev',
};
// Log.print('payload: ${payload}');
var response1 = await http.post(
Uri.parse(AppLink.loginJwtRider),
body: payload,
);
Log.print('req: ${response1.request}');
Log.print('response: ${response1.body}');
Log.print('payload: ${payload}');
// Log.print('decodedResponse1: ${jsonDecode(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();
// final refreshToken = decodedResponse1['refresh_token'];
// await storage.write(key: BoxName.refreshToken, value: refreshToken);
}
}
}
Future<void> loginUsingCredentials(String passengerID, String email) async {
isloading = true;
update();
await getJWT();
try {
// 1) استعلام تسجيل الدخول
final res = await CRUD().get(
link: AppLink.loginFromGooglePassenger,
payload: {
'email': email,
'id': passengerID, // استخدم المعامل مباشرة
'platform': Platform.isAndroid ? 'android' : 'ios',
'appName': AppInformation.appName,
},
);
Log.print('res for loginFromGooglePassenger: ${res}');
if (res == 'failure') {
Get.snackbar("User does not exist.".tr, '',
backgroundColor: Colors.red);
Get.offAll(() => PhoneNumberScreen());
return;
}
// 2) فك JSON مرة واحدة
final decoded = jsonDecode(res);
if (decoded is! Map || decoded.isEmpty) return;
final status = (decoded['status'] ?? '').toString();
final data = (decoded['data'] as List?)?.firstOrNull as Map? ?? {};
if (status != 'success' || data['verified'].toString() != '1') {
// غير مُفعل -> أذهب للتسجيل بالـ SMS
Get.offAll(() => PhoneNumberScreen());
return;
}
// 3) كتابة القيم (خفيفة)
box.write(BoxName.isVerified, '1');
box.write(BoxName.email, data['email']);
box.write(BoxName.phone, data['phone']);
box.write(BoxName.name, data['first_name']);
box.write(BoxName.isTest, '1');
box.write(BoxName.package, data['package']);
box.write(BoxName.promo, data['promo']);
box.write(BoxName.discount, data['discount']);
box.write(BoxName.validity, data['validity']);
box.write(BoxName.isInstall, data['isInstall'] ?? 'none');
box.write(BoxName.isGiftToken, data['isGiftToken'] ?? 'none');
if (data['inviteCode'] != null) {
box.write(BoxName.inviteCode, data['inviteCode'].toString());
}
// مهم: تأكد من passengerID في الـ box
box.write(BoxName.passengerID, passengerID);
// 4) نفّذ عمليات مكلفة بالتوازي: getTokens + fingerprint
final results = await Future.wait([
CRUD().get(link: AppLink.getTokens, payload: {
'passengerID': passengerID, // FIX: لا تستخدم box هنا
}),
DeviceHelper.getDeviceFingerprint(),
]);
await box.write(BoxName.firstTimeLoadKey, 'false');
final tokenResp = results[0];
final fingerPrint = (results[1] ?? '').toString();
await storage.write(key: BoxName.fingerPrint, value: fingerPrint);
if (email != '962798583052@Tripzapp.com' && tokenResp != 'failure') {
final tokenJson = jsonDecode(tokenResp);
final serverToken = tokenJson['message']?['token']?.toString() ?? '';
// Log.print('serverToken: ${serverToken}');
final localFcm = (box.read(BoxName.tokenFCM) ?? '').toString();
// Log.print('localFcm: ${localFcm}');
// 5) اختلاف الجهاز -> تحقّق OTP
if (serverToken.isNotEmpty && serverToken != localFcm) {
final goVerify = await _confirmDeviceChangeDialog();
if (goVerify == true) {
await Get.to(() => OtpVerificationPage(
phone: data['phone'].toString(),
deviceToken: fingerPrint,
token: tokenResp.toString(),
ptoken: serverToken,
));
// بعد العودة من OTP (نجح/فشل)، أخرج من الميثود كي لا يحصل offAll مرتين
return;
}
}
}
// 6) منطق الدعوة (إن وُجد) ثم الانتقال
final invite = box.read(BoxName.inviteCode)?.toString() ?? 'none';
final isInstall = box.read(BoxName.isInstall)?.toString() ?? '0';
if (invite != 'none' && isInstall != '1') {
try {
await CRUD().post(link: AppLink.updatePassengersInvitation, payload: {
"inviteCode": invite,
"passengerID": passengerID,
});
await Get.defaultDialog(
title: 'Invitation Used'.tr,
middleText: "Your invite code was successfully applied!".tr,
textConfirm: "OK".tr,
confirmTextColor: Colors.white,
onConfirm: () async {
try {
await CRUD().post(link: AppLink.addPassengersPromo, payload: {
"promoCode":
'I-${(box.read(BoxName.name)).toString().split(' ').first}',
"amount": '25',
"passengerID": passengerID,
"description": 'promo first'
});
} catch (e) {
addError(
e.toString(), 'promo on invitation in login_controller');
} finally {
Get.offAll(() => const MapPagePassenger());
}
},
);
return;
} catch (_) {
// حتى لو فشل، كمل للصفحة الرئيسية
}
}
Get.offAll(() => const MapPagePassenger());
} catch (e, st) {
addError('$e', 'loginUsingCredentials');
Get.snackbar('Error', e.toString(), backgroundColor: Colors.redAccent);
} finally {
isloading = false;
update();
}
}
Future<bool?> _confirmDeviceChangeDialog() {
return Get.defaultDialog<bool>(
barrierDismissible: false,
title: 'Device Change Detected'.tr,
middleText: 'Please verify your identity'.tr,
textConfirm: 'Verify'.tr,
confirmTextColor: Colors.white,
onConfirm: () => Get.back(result: true),
textCancel: 'Cancel'.tr,
onCancel: () => Get.back(result: false),
);
}
void login() async {
isloading = true;
update();
var res =
await CRUD().get(link: AppLink.loginFromGooglePassenger, payload: {
'email': (emailController.text),
'id': passwordController.text,
"platform": Platform.isAndroid ? 'android' : 'ios',
"appName": AppInformation.appName,
});
isloading = false;
update();
if (res == 'Failure') {
//Failure
Get.offAll(() => LoginPage());
isloading = false;
update();
// Get.snackbar("User does not exist.".tr, '', backgroundColor: Colors.red);
} else {
var jsonDecoeded = jsonDecode(res);
if (jsonDecoeded.isNotEmpty) {
if (jsonDecoeded['status'] == 'success' &&
jsonDecoeded['data'][0]['verified'].toString() == '1') {
//
box.write(BoxName.isVerified, '1');
box.write(BoxName.email, jsonDecoeded['data'][0]['email']);
box.write(BoxName.name, jsonDecoeded['data'][0]['first_name']);
box.write(BoxName.phone, jsonDecoeded['data'][0]['phone']);
box.write(BoxName.passengerID, passwordController.text);
// var token = await CRUD().get(link: AppLink.getTokens, payload: {
// 'passengerID': box.read(BoxName.passengerID).toString()
// });
// await updateAppTester(AppInformation.appName);
Get.offAll(() => const MapPagePassenger());
} else {
// Get.offAll(() => SmsSignupEgypt());
// Get.snackbar(jsonDecoeded['status'], jsonDecoeded['data'],
// backgroundColor: Colors.redAccent);
isloading = false;
update();
}
} else {
isloading = false;
update();
}
}
}
goToMapPage() {
if (box.read(BoxName.email) != null) {
Get.offAll(() => const MapPagePassenger());
}
}
final location = Location();
// late PermissionStatus permissionGranted = PermissionStatus.denied;
Future<void> getLocationPermission() async {
bool serviceEnabled;
PermissionStatus permissionGranted;
// Check if location services are enabled
serviceEnabled = await location.serviceEnabled();
if (!serviceEnabled) {
serviceEnabled = await location.requestService();
if (!serviceEnabled) {
// Location services are still not enabled, handle the error
return;
}
}
// Check if the app has permission to access location
permissionGranted = await location.hasPermission();
if (permissionGranted == PermissionStatus.denied) {
permissionGranted = await location.requestPermission();
if (permissionGranted != PermissionStatus.granted) {
// Location permission is still not granted, handle the error
permissionGranted = await location.requestPermission();
return;
}
}
if (permissionGranted.toString() == 'PermissionStatus.granted') {
box.write(BoxName.locationPermission, 'true');
}
update();
}
}
@@ -1,43 +0,0 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:Tripz/constant/box_name.dart';
import 'package:Tripz/main.dart';
import 'package:Tripz/views/auth/login_page.dart';
import '../../models/model/onboarding_model.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(() => LoginPage());
} 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();
}
}
@@ -1,213 +0,0 @@
import 'package:Tripz/constant/links.dart';
import 'package:Tripz/views/home/map_page_passenger.dart';
import 'package:get/get.dart';
import '../../../constant/box_name.dart';
import '../../../main.dart';
import '../../../print.dart';
import '../../views/auth/otp_page.dart';
import '../../views/widgets/error_snakbar.dart';
import '../functions/crud.dart';
import '../functions/package_info.dart';
import 'login_controller.dart';
// --- Helper Class for Phone Authentication ---
class PhoneAuthHelper {
// Define your server URLs
static final String _baseUrl = '${AppLink.server}/auth/syria/';
static final String _sendOtpUrl = '${_baseUrl}sendWhatsOpt.php';
static final String _verifyOtpUrl = '${_baseUrl}verifyOtp.php';
static final String _registerUrl = '${_baseUrl}register_passenger.php';
static String formatSyrianPhone(String phone) {
// Remove spaces, symbols, +, -, ()
phone = phone.replaceAll(RegExp(r'[ \-\(\)\+]'), '').trim();
// Normalize 00963 → 963
if (phone.startsWith('00963')) {
phone = phone.replaceFirst('00963', '963');
}
// Normalize 0963 → 963
if (phone.startsWith('0963')) {
phone = phone.replaceFirst('0963', '963');
}
// NEW: Fix 96309xxxx → 9639xxxx
if (phone.startsWith('96309')) {
phone = '9639' + phone.substring(5); // remove the "0" after 963
}
// If starts with 9630 → correct to 9639
if (phone.startsWith('9630')) {
phone = '9639' + phone.substring(4);
}
// If already in correct format: 9639xxxxxxxx
if (phone.startsWith('9639') && phone.length == 12) {
return phone;
}
// If starts with 963 but missing the 9
if (phone.startsWith('963') && phone.length > 3) {
// Ensure it begins with 9639
if (!phone.startsWith('9639')) {
phone = '9639' + phone.substring(3);
}
return phone;
}
// If starts with 09xxxxxxxx → 9639xxxxxxxx
if (phone.startsWith('09')) {
return '963' + phone.substring(1);
}
// If 9xxxxxxxx (9 digits)
if (phone.startsWith('9') && phone.length == 9) {
return '963' + phone;
}
// If starts with incorrect 0xxxxxxx → assume Syrian and fix
if (phone.startsWith('0') && phone.length == 10) {
return '963' + phone.substring(1);
}
return phone;
}
/// Sends an OTP to the provided phone number.
static Future<bool> sendOtp(String phoneNumber) async {
try {
// إصلاح الرقم قبل الإرسال
final fixedPhone = formatSyrianPhone(phoneNumber);
final response = await CRUD().post(
link: _sendOtpUrl,
payload: {'receiver': fixedPhone}, // ← ← استخدام الرقم المُعدّل
);
if (response != 'failure') {
final data = response;
if (data['status'] == 'success') {
mySnackbarSuccess('An OTP has been sent to your 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) {
return false;
}
}
/// Verifies the OTP and logs the user in.
static Future<void> verifyOtp(String phoneNumber) async {
try {
final fixedPhone = formatSyrianPhone(phoneNumber);
final response = await CRUD().post(
link: _verifyOtpUrl,
payload: {
'phone_number': fixedPhone,
},
);
if (response != 'failure') {
final data = (response);
// Log.print('data: ${data}');
if (data['status'] == 'success') {
final isRegistered = data['message']['isRegistered'] ?? false;
// Log.print('isRegistered: ${isRegistered}');
if (isRegistered) {
// ✅ المستخدم موجود مسبقاً -> تسجيل دخول مباشر
await _handleSuccessfulLogin(data['message']['passenger']);
} else {
// ✅ مستخدم جديد -> الذهاب لصفحة التسجيل
mySnackbarSuccess(
'Phone verified. Please complete registration.'.tr);
Get.to(() => RegistrationScreen(phoneNumber: phoneNumber));
}
} else {
mySnackeBarError(data['message']);
}
} else {
mySnackeBarError('Server error. Please try again.'.tr);
}
} catch (e) {
mySnackeBarError('An error occurred: $e');
}
}
static Future<void> _addTokens() async {
String fingerPrint = await DeviceHelper.getDeviceFingerprint();
await CRUD()
.post(link: "${AppLink.server}/ride/firebase/add.php", payload: {
'token': (box.read(BoxName.tokenFCM.toString())),
'passengerID': box.read(BoxName.passengerID).toString(),
"fingerPrint": fingerPrint
});
await CRUD()
.post(link: "${AppLink.paymentServer}/ride/firebase/add.php", payload: {
'token': (box.read(BoxName.tokenFCM.toString())),
'passengerID': box.read(BoxName.passengerID).toString(),
"fingerPrint": fingerPrint
});
}
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']['data']);
} 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.name, userData['first_name']);
box.write(BoxName.lastName, userData['last_name']);
box.write(BoxName.email, userData['email']);
box.write(BoxName.phone, userData['phone']);
box.write(BoxName.isVerified, '1');
await _addTokens();
await Get.put(LoginController()).loginUsingCredentials(
box.read(BoxName.passengerID).toString(),
box.read(BoxName.email).toString(),
); // Navigate to home
}
}
@@ -1,281 +0,0 @@
import 'dart:async';
import 'dart:convert';
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: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 '../../constant/box_name.dart';
import '../../main.dart';
import '../../print.dart';
import '../../views/auth/verify_email_page.dart';
class RegisterController extends GetxController {
// --- 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 verifyCode = TextEditingController();
// --- 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 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) {
birthDate = date.toString().split(' ')[0];
update();
Get.back();
},
),
),
);
}
void changeGender(String value) {
gender = value;
update();
}
/// 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(),
'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());
}
}
}
}
@@ -1,114 +0,0 @@
import 'dart:async';
import 'package:Tripz/constant/box_name.dart';
import 'package:Tripz/constant/links.dart';
import 'package:Tripz/controller/functions/crud.dart';
import 'package:Tripz/main.dart';
import 'package:get/get.dart';
import '../../print.dart';
import '../../views/home/map_page_passenger.dart';
import '../firebase/firbase_messge.dart';
import '../firebase/notification_service.dart';
import '../functions/package_info.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 {
if (isLoading.value) return;
isLoading.value = true;
try {
final response = await CRUD().post(
link: '${AppLink.server}/auth/token_passenger/send_otp.php',
payload: {
'receiver': phone,
// 'device_token': deviceToken,
},
);
if (response != 'failure') {
isLoading.value = true;
// بإمكانك عرض رسالة نجاح هنا
} else {
Get.snackbar('Error'.tr, 'Failed to send OTP'.tr);
}
} catch (e) {
Get.snackbar('Error', e.toString());
} finally {
// isLoading.value = false;
}
}
Future<void> verifyOtp(String ptoken) async {
isVerifying.value = true;
try {
String fingerPrint = await DeviceHelper.getDeviceFingerprint();
final response = await CRUD().post(
link: '${AppLink.server}/auth/token_passenger/verify_otp.php',
payload: {
'phone_number': phone,
'otp': otpCode.value,
'token': box.read(BoxName.tokenFCM).toString(),
'fingerPrint': fingerPrint.toString(),
},
);
if (response != 'failure' && response['status'] == 'success') {
await NotificationService.sendNotification(
category: 'token change',
target: ptoken.toString(),
title: 'token change'.tr,
body: 'change device'.tr,
isTopic: false, // Important: this is a token
tone: 'cancel',
driverList: [],
);
Get.offAll(() => const MapPagePassenger());
} else {
Get.snackbar('Verification Failed', 'OTP is incorrect or expired');
}
} catch (e) {
Get.snackbar('Error', e.toString());
} finally {
isVerifying.value = false;
}
}
}
@@ -1,38 +0,0 @@
import 'dart:convert';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../functions/encrypt_decrypt.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.') {
Get.snackbar('token updated'.tr, '');
}
}
}
@@ -1,16 +0,0 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:Tripz/constant/links.dart';
import 'package:Tripz/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);
}
}