25-10-2/1

This commit is contained in:
Hamza-Ayed
2025-10-02 01:20:16 +03:00
parent 7595be8067
commit c48627a175
342 changed files with 15825 additions and 14862 deletions

View File

@@ -263,6 +263,8 @@ class AppLink {
static String getCarsLocationByPassengerSpeed = "$location/getSpeed.php";
static String getCarsLocationByPassengerComfort = "$location/getComfort.php";
static String getCarsLocationByPassengerBalash = "$location/getBalash.php";
static String getCarsLocationByPassengerElectric =
"$location/getElectric.php";
static String getCarsLocationByPassengerPinkBike =
"$location/getPinkBike.php";
static String getCarsLocationByPassengerDelivery =

View File

@@ -1,22 +1,31 @@
List<String> messages = [
"🚗 عروض مميزة: استمتع بأقل الأسعار وأفضل العروض! افتح تطبيق انطلق الآن لتحصل على المزيد من الخيارات. 🌟",
"💸 وفر الآن: وفر مع تطبيق انطلق! عروض مستمرة وخيارات متعددة تناسب احتياجاتك. 🔥",
"🔒 أمان وراحة: مع تطبيق انطلق، احصل على أمان وراحة بأفضل الأسعار! 🚕",
"💼 خيارات متنوعة: استفد من خيارات متنوعة وأسعار تنافسية على تطبيق انطلق، الأفضل دائماً. 🌐",
"💵 توفير مضمون: حافظ على ميزانيتك وسافر بأمان مع تطبيق انطلق العروض لا تتوقف! 🎉",
"🌍 وجهات مميزة: أفضل وجهات الانطلق، بأقل الأسعار مع تطبيق انطلق تابعنا الآن! 🛤️",
"🛣️ سهولة وراحة: رحلاتك أصبحت أسهل وأرخص سافر معنا وتمتع بأفضل التجارب. 🎊",
"📲 حجز سهل: احجز رحلتك بسهولة وأمان مع انطلق المزيد من الخصومات في انتظارك! 🎁",
"👑 فئة مميزة: خليك من الفئة المميزة واستفد بأفضل الأسعار مع تطبيق انطلق. 💯",
"💡 خيارات متعددة: نوفر لك خيارات متعددة وسعر مناسب جرب تطبيق انطلق الآن! 🚖",
"✨ عروض متجددة: العروض لا تتوقف على تطبيق انطلق احجز رحلتك الآن وتمتع بالمزيد! 📅",
"🚀 سهولة الوصول: الانطلق أصبح أسهل وأسرع مع تطبيق انطلق كن مستعدًا لأفضل التجارب! 🌠",
"🧳 راحة وأمان: تطبيق انطلق يقدم لك أمان وراحة بأقل الأسعار! 📉",
"🔥 عروض فورية: احجز الآن واستمتع بعروض لا تُفوّت على تطبيق انطلق! 🚘",
"🚖 أسعار تنافسية: اختر رحلتك الآن بأسعار تنافسية وتمتع بالراحة والأمان مع تطبيق انطلق. ✅",
"💥 أسعار خاصة: أسعار خاصة بانتظارك على تطبيق انطلق! افتح التطبيق الآن واحجز رحلتك. 🌐",
"🌟 راحة البال: انطلق بأمان وراحة مع تطبيق انطلق استمتع بأفضل الأسعار. 💸",
"📍 خصومات حصرية: استفد من الخصومات الحصرية والعروض المستمرة على تطبيق انطلق! 🛤️",
"🛫 تجربة سهلة: رحلاتك أصبحت أفضل وأسهل مع تطبيق انطلق افتح التطبيق واستمتع بالتجربة. ✨",
"🔔 عروض لا مثيل لها: كن جاهزًا لعروض لا مثيل لها! تطبيق انطلق يقدم لك أفضل الخيارات بأقل الأسعار. 🎉",
List<String> passengerMessages = [
// --- رسائل العروض والتوفير ---
"مشاويرك علينا بأحلى الأسعار! 🚗 فوت على تطبيق انطلق وشوف العروض الجديدة اللي ناطرتك. 🌟",
"بدك توفّر بمشاويرك؟ 🤔 افتح تطبيق انطلق هلأ! أسعارنا ما بتلاقي متلها.",
"خصم خاص الك اليوم! 🎁 افتح تطبيق انطلق واحجز مشوارك الجاي بسعر أقل.",
"لا تحمل هم المصاريف! 💸 مع انطلق، كل مشاويرك اقتصادية ومريحة.",
// --- رسائل السهولة والراحة ---
"كبسة زر ومشوارك صار عندك! 📲 افتح تطبيق انطلق واحجز بسهولة.",
"ليش معجوق بالمواصلات؟ 🤔 انطلق بيوصلك وين ما بدك براحة وسرعة.",
"سيارتك ناطرتك! 🚕 وين ما كنت، اطلب من انطلق وبنوصلك بأسرع وقت.",
"مشوارك الجاي مع انطلق! 🛣️ استرخي واستمتع بالطريق، نحنا بنهتم بالتفاصيل.",
// --- رسائل الأمان والثقة ---
"مشوارك آمن ومريح مع انطلق. 🙏 كباتنّا محترفين و بيهمنا توصل بالسلامة.",
"انطلق بقلب مطمن! 🔒 سلامتك أولويتنا بكل رحلة بتطلعها معنا.",
"مع انطلق، فيك تشارك تفاصيل رحلتك مع اللي بتحبن ليضل بالك مرتاح. ❤️",
"كل رحلاتنا مسجّلة لضمان أمانك. سافر بثقة مع انطلق. ",
// --- رسائل تفاعلية ومناسبات خاصة ---
"الويكند بلّش! 🥳 مشاويرك مع الصحبة صارت أسهل وأوفر. اطلب انطلق.",
"رايح عالشغل؟ 💼 خلي انطلق يوصلك بلا عجقة السير وخليك مرتاح.",
"الدنيا شوب؟ ☀️ اطلب من انطلق والكابتن بيوصل لعندك.",
"تأخرت؟ لا تاكل هم! 🏃‍♂️ تطبيق انطلق هو أسرع طريق لتوصل عبكير.",
// --- رسائل تشجيعية عامة ---
"وين وجهتك اليوم؟ 🗺️ مدينة كاملة بانتظارك، وخلي مشوارك على انطلق.",
"جرّبت فئات سيارات انطلق الجديدة؟ 🚘 دلّل حالك بتجربة مميزة اليوم.",
"شكراً لاختيارك انطلق! ⭐ منتمنى الك دايماً رحلات سعيدة ومريحة.",
"عند انطلق كل شي جديد! ✨ فوت عالبرنامج وضلّك على اطلاع بآخر خدماتنا وعروضنا."
];

View File

@@ -1,204 +1,149 @@
import 'dart:io';
import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/controller/auth/login_controller.dart';
import 'package:Intaleq/controller/functions/encrypt_decrypt.dart';
import 'package:Intaleq/main.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 '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../onbording_page.dart';
import '../../print.dart';
import '../../main.dart';
import '../functions/crud.dart';
import '../../onbording_page.dart';
import 'login_controller.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:
'594687661098-2u640akrb3k7sak5t0nqki6f4v6hq1bq.apps.googleusercontent.com',
);
// 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.erase();
// 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);
// box.remove(BoxName.firstTimeLoadKey);
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

@@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:Intaleq/constant/api_key.dart';
import 'package:Intaleq/views/auth/otp_page.dart';
import 'package:http/http.dart' as http;
import 'package:Intaleq/constant/info.dart';
@@ -173,149 +174,161 @@ class LoginController extends GetxController {
await AppInitializer().getKey();
final refreshToken = decodedResponse1['refresh_token'];
await storage.write(key: BoxName.refreshToken, value: refreshToken);
} else {}
// final refreshToken = decodedResponse1['refresh_token'];
// await storage.write(key: BoxName.refreshToken, value: refreshToken);
}
}
}
loginUsingCredentials(String passengerID, email) async {
Future<void> loginUsingCredentials(String passengerID, String email) async {
isloading = true;
update();
// bool isTokenExpired = JwtDecoder.isExpired(
// r(box.read(BoxName.jwt)).toString().split(AppInformation.addd)[0]);
await getJWT();
// if (isTokenExpired) {
// // Log.print('isTokenExpired loginUsingCredentials: ${isTokenExpired}');
// 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,
},
);
var res =
await CRUD().get(link: AppLink.loginFromGooglePassenger, payload: {
'email': email.toString(),
'id': passengerID.toString(),
"platform": Platform.isAndroid ? 'android' : 'ios',
"appName": AppInformation.appName,
});
if (res == 'Failure') {
// Get.offAll(SmsSignupEgypt());
if (res == 'Failure') {
Get.snackbar("User does not exist.".tr, '',
backgroundColor: Colors.red);
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@intaleqapp.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();
Get.snackbar("User does not exist.".tr, '', backgroundColor: Colors.red);
} else {
// Log.print('res: ${res}');
var jsonDecoeded = jsonDecode(res);
if (jsonDecoeded.isNotEmpty) {
var d = jsonDecoeded['data'][0];
if (jsonDecoeded['status'] == 'success' &&
d['verified'].toString() == '1') {
//
box.write(BoxName.isVerified, '1');
box.write(BoxName.email, d['email']);
box.write(BoxName.phone, d['phone']);
box.write(BoxName.name, d['first_name']);
box.write(BoxName.isTest, '1');
box.write(BoxName.package, d['package']);
box.write(BoxName.promo, d['promo']);
box.write(BoxName.discount, d['discount']);
box.write(BoxName.validity, d['validity']);
box.write(BoxName.isInstall, d['isInstall'] ?? 'none');
box.write(BoxName.isGiftToken, d['isGiftToken'] ?? 'none');
box.write(BoxName.firstTimeLoadKey, 'false');
d['inviteCode'] != null
? box.write(
BoxName.inviteCode, (d['inviteCode'].toString()) ?? 'none')
: null;
var token = await CRUD().get(link: AppLink.getTokens, payload: {
'passengerID': box.read(BoxName.passengerID).toString()
});
var fingerPrint = await DeviceHelper.getDeviceFingerprint();
Log.print('fingerPrint 0: ${fingerPrint}');
await storage.write(key: BoxName.fingerPrint, value: fingerPrint);
if (email == '962798583052@intaleqapp.com') {
} else {
if (token != 'failure') {
if ((jsonDecode(token)['message']['token'].toString()) !=
box.read(BoxName.tokenFCM)) {
await Get.defaultDialog(
barrierDismissible: false,
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)['message']['token'].toString(),
),
);
},
);
}
}
} // Logging to check if inviteCode is written correctly
if (d['inviteCode'] != 'none' &&
d['inviteCode'] != null &&
// box.read(BoxName.inviteCode).toString() != 'none' &&
box.read(BoxName.isInstall).toString() != '1') {
await CRUD()
.post(link: AppLink.updatePassengersInvitation, payload: {
"inviteCode": (box.read(BoxName.inviteCode).toString()),
"passengerID": box.read(BoxName.passengerID).toString(),
});
Get.defaultDialog(
title: 'Invitation Used'
.tr, // Automatically translates based on the current locale
middleText: "Your invite code was successfully applied!"
.tr, // Automatically translates based on the current locale
onConfirm: () {
try {
CRUD().post(link: AppLink.addPassengersPromo, payload: {
"promoCode":
'S-${(box.read(BoxName.name)).toString().split(' ')[0]}',
"amount": '25',
"passengerID": box.read(BoxName.passengerID).toString(),
"description": 'promo first'
});
} catch (e) {
addError(e.toString(),
'passenger Invitation Used dialogu as promo line 185 login_controller');
} finally {
// Continue with the rest of your flow, regardless of errors
// For example, navigate to the next page
Get.offAll(() => const MapPagePassenger());
}
},
textConfirm: "OK".tr, // Confirm button text
);
} else {
Get.offAll(() => const MapPagePassenger());
}
} else {
Get.offAll(() => SmsSignupEgypt());
// Get.snackbar(jsonDecoeded['status'], jsonDecoeded['data'],
// backgroundColor: Colors.redAccent);
isloading = false;
update();
}
} else {
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();

View File

@@ -7,6 +7,7 @@ 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 ---
@@ -83,6 +84,24 @@ class PhoneAuthHelper {
}
}
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.seferPaymentServer}/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,
@@ -102,6 +121,7 @@ class PhoneAuthHelper {
final data = (response);
if (data != 'failure') {
// Registration successful, log user in
await _addTokens();
await _handleSuccessfulLogin(data['message']['data']);
} else {
mySnackeBarError(

View File

@@ -9,6 +9,7 @@ import 'package:get/get.dart';
import '../../print.dart';
import '../../views/home/map_page_passenger.dart';
import '../firebase/firbase_messge.dart';
import '../functions/package_info.dart';
class OtpVerificationController extends GetxController {
final String phone;
@@ -49,6 +50,7 @@ class OtpVerificationController extends GetxController {
}
Future<void> sendOtp() async {
if (isLoading.value) return;
isLoading.value = true;
try {
final response = await CRUD().post(
@@ -60,48 +62,60 @@ class OtpVerificationController extends GetxController {
);
if (response != 'failure') {
isLoading.value = true;
// بإمكانك عرض رسالة نجاح هنا
} else {
// Get.snackbar('Error', 'Failed to send OTP');
Get.snackbar('Error'.tr, 'Failed to send OTP'.tr);
}
} catch (e) {
Get.snackbar('Error', e.toString());
} finally {
isLoading.value = false;
// isLoading.value = false;
}
}
Future<void> verifyOtp(String ptoken) async {
isVerifying.value = true;
var finger = await storage.read(key: BoxName.fingerPrint);
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': finger.toString(),
'fingerPrint': fingerPrint.toString(),
},
);
if (response != 'failure' && response['status'] == 'success') {
Get.back(); // توجه إلى الصفحة التالية
await Get.put(FirebaseMessagesController()).sendNotificationToDriverMAP(
final fcm = Get.isRegistered<FirebaseMessagesController>()
? Get.find<FirebaseMessagesController>()
: Get.put(FirebaseMessagesController());
await fcm.sendNotificationToDriverMAP(
'token change',
'change device'.tr,
ptoken.toString(),
[],
'cancel.wav',
);
CRUD().post(
link:
'${AppLink.seferPaymentServer}/auth/token/update_passenger_token.php',
await CRUD().post(
link: "${AppLink.seferPaymentServer}/ride/firebase/add.php",
payload: {
'token': box.read(BoxName.tokenDriver).toString(),
'fingerPrint': finger.toString(),
'token': (box.read(BoxName.tokenFCM.toString())),
'passengerID': box.read(BoxName.passengerID).toString(),
"fingerPrint": fingerPrint.toString(),
});
// CRUD().post(
// link:
// '${AppLink.seferPaymentServer}/auth/token/update_passenger_token.php',
// payload: {
// 'token': box.read(BoxName.tokenFCM).toString(),
// 'fingerPrint': fingerPrint.toString(),
// 'passengerID': box.read(BoxName.passengerID).toString(),
// });
Get.offAll(() => const MapPagePassenger());
} else {
Get.snackbar('Verification Failed', 'OTP is incorrect or expired');

View File

@@ -134,7 +134,7 @@ class FirebaseMessagesController extends GetxController {
notificationController.showNotification(
'Accepted Ride'.tr, 'Driver Accepted the Ride for You'.tr, 'ding');
}
var passengerList = message.data['passengerList'];
var passengerList = message.data['DriverList'];
var myList = jsonDecode(passengerList) as List<dynamic>;
Log.print('myList: ${myList}');
@@ -161,7 +161,7 @@ class FirebaseMessagesController extends GetxController {
notificationController.showNotification(
'Trip Monitoring'.tr, '', 'iphone_ringtone');
}
var myListString = message.data['passengerList'];
var myListString = message.data['DriverList'];
var myList = jsonDecode(myListString) as List<dynamic>;
Get.toNamed('/tripmonitor', arguments: {
'rideId': myList[0].toString(),
@@ -296,7 +296,7 @@ class FirebaseMessagesController extends GetxController {
// }
else if (message.notification!.title! == 'Call Income') {
try {
var myListString = message.data['passengerList'];
var myListString = message.data['DriverList'];
var driverList = jsonDecode(myListString) as List<dynamic>;
// if (Platform.isAndroid) {
if (Platform.isAndroid) {
@@ -316,7 +316,7 @@ class FirebaseMessagesController extends GetxController {
} catch (e) {}
} else if (message.notification!.title! == 'Call Income from Driver'.tr) {
try {
var myListString = message.data['passengerList'];
var myListString = message.data['DriverList'];
var driverList = jsonDecode(myListString) as List<dynamic>;
// if (Platform.isAndroid) {
if (Platform.isAndroid) {
@@ -335,7 +335,7 @@ class FirebaseMessagesController extends GetxController {
} catch (e) {}
} else if (message.notification!.title! == 'Call End'.tr) {
try {
var myListString = message.data['passengerList'];
var myListString = message.data['DriverList'];
var driverList = jsonDecode(myListString) as List<dynamic>;
if (Platform.isAndroid) {
notificationController.showNotification(

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

@@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:convert';
import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/constant/links.dart';
@@ -9,6 +10,7 @@ import 'package:Intaleq/env/env.dart';
import '../../constant/api_key.dart';
import '../../print.dart';
import '../../views/widgets/elevated_btn.dart';
import '../../views/widgets/error_snakbar.dart';
import 'encrypt_decrypt.dart';
@@ -22,6 +24,7 @@ import 'network/net_guard.dart';
class CRUD {
final NetGuard _netGuard = NetGuard();
final _client = http.Client();
/// Stores the signature of the last logged error to prevent duplicates.
static String _lastErrorSignature = '';
@@ -41,7 +44,6 @@ class CRUD {
if (currentErrorSignature == _lastErrorSignature &&
now.difference(_lastErrorTimestamp) < _errorLogDebounceDuration) {
print("Debounced a duplicate error: $error");
return;
}
@@ -66,9 +68,7 @@ class CRUD {
'details': details,
},
);
} catch (e) {
print("CRITICAL: Failed to log error to server: $e");
}
} catch (e) {}
}
/// Centralized private method to handle all API requests.
@@ -78,80 +78,72 @@ class CRUD {
Map<String, dynamic>? payload,
required Map<String, String> headers,
}) async {
// timeouts أقصر
const connectTimeout = Duration(seconds: 6);
const receiveTimeout = Duration(seconds: 10);
Future<http.Response> doPost() {
final url = Uri.parse(link);
// استخدم _client بدل http.post
return _client
.post(url, body: payload, headers: headers)
.timeout(connectTimeout + receiveTimeout);
}
http.Response response;
try {
var response = await HttpRetry.sendWithRetry(
() {
var url = Uri.parse(link);
return http.post(
url,
body: payload,
headers: headers,
);
},
maxRetries: 3,
timeout: const Duration(seconds: 15),
);
// retry ذكي: محاولة واحدة إضافية فقط لأخطاء شبكة/5xx
try {
response = await doPost();
} on SocketException catch (_) {
// محاولة ثانية واحدة فقط
response = await doPost();
} on TimeoutException catch (_) {
response = await doPost();
}
if (response.statusCode == 200) {
final sc = response.statusCode;
Log.print('sc: ${sc}');
Log.print('request: ${response.request}');
final body = response.body;
Log.print('body: ${body}');
// 2xx
if (sc >= 200 && sc < 300) {
try {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return jsonData;
} else {
// Log API logical errors (e.g., "Customer not found")
if (jsonData['status'] == 'failure') {
// return 'failure';
} else {
addError(
'API Logic Error: ${jsonData['status']}',
'Response: ${response.body}',
'CRUD._makeRequest - $link',
);
}
final jsonData = jsonDecode(body);
return jsonData; // لا تعيد 'success' فقط؛ أعِد الجسم كله
} catch (e, st) {
// لا تسجّل كخطأ شبكي لكل حالة؛ فقط معلومات
addError('JSON Decode Error', 'Body: $body\n$st',
'CRUD._makeRequest $link');
return 'failure';
}
}
return jsonData['status'];
}
} catch (e, stackTrace) {
addError(
'JSON Decode Error: $e',
'Response Body: ${response.body}\nStack Trace: $stackTrace',
'CRUD._makeRequest - $link',
);
return 'failure';
}
} else if (response.statusCode == 401) {
var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
await Get.put(LoginController()).getJWT();
// mySnackbarSuccess('please order now'.tr);
return 'token_expired';
} else {
addError(
'Unauthorized Error: ${jsonData['error']}',
'Status Code: 401',
'CRUD._makeRequest - $link',
);
return 'failure';
}
} else {
// 401 → دع الطبقة العليا تتعامل مع التجديد
if (sc == 401) {
// لا تستدع getJWT هنا كي لا نضاعف الرحلات
return 'token_expired';
}
// 5xx: لا تعِد المحاولة هنا (حاولنا مرة ثانية فوق)
if (sc >= 500) {
addError(
'HTTP Error',
'Status Code: ${response.statusCode}\nResponse Body: ${response.body}',
'CRUD._makeRequest - $link',
);
'Server 5xx', 'SC: $sc\nBody: $body', 'CRUD._makeRequest $link');
return 'failure';
}
// 4xx أخرى: أعد الخطأ بدون تسجيل مكرر
return 'failure';
} on SocketException {
_netGuard.notifyOnce((title, msg) {
mySnackeBarError(msg);
});
_netGuard.notifyOnce((title, msg) => mySnackeBarError(msg));
return 'no_internet';
} catch (e, stackTrace) {
addError(
'HTTP Request Exception: $e',
'Stack Trace: $stackTrace',
'CRUD._makeRequest - $link',
);
} on TimeoutException {
return 'failure';
} catch (e, st) {
addError('HTTP Request Exception: $e', 'Stack: $st',
'CRUD._makeRequest $link');
return 'failure';
}
}
@@ -186,28 +178,45 @@ class CRUD {
required String link,
Map<String, dynamic>? payload,
}) async {
String token = r(box.read(BoxName.jwt)).toString().split(Env.addd)[0];
// if (JwtDecoder.isExpired(token)) {
// await Get.put(LoginController()).getJWT();
// token = r(box.read(BoxName.jwt)).toString().split(Env.addd)[0];
// }
final headers = {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer $token'
};
var result = await _makeRequest(
link: link,
payload: payload,
headers: headers,
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization':
'Bearer ${r(box.read(BoxName.jwt)).toString().split(Env.addd)[0]}'
},
);
if (response.statusCode == 200) {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return response.body;
}
// The original 'get' method returned the raw body on success, maintaining that behavior.
if (result is Map && result['status'] == 'success') {
return jsonEncode(result);
return jsonData['status'];
} else if (response.statusCode == 401) {
// Specifically handle 401 Unauthorized
var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
// Show snackbar prompting to re-login
await Get.put(LoginController()).getJWT();
// 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',
// url.toString());
return 'failure';
}
} else {
addError('Non-200 response code: ${response.statusCode}',
'crud().post - Other', url.toString());
return 'failure';
}
return result;
}
/// Performs an authenticated POST request to wallet endpoints.
@@ -236,27 +245,48 @@ class CRUD {
required String link,
Map<String, dynamic>? payload,
}) async {
var jwt = await LoginController().getJwtWallet();
var s = await LoginController().getJwtWallet();
final hmac = box.read(BoxName.hmac);
final headers = {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer $jwt',
'X-HMAC-Auth': hmac.toString(),
};
var result = await _makeRequest(
link: link,
payload: payload,
headers: headers,
var url = Uri.parse(
link,
);
var response = await http.post(
url,
body: payload,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
'Authorization': 'Bearer $s',
'X-HMAC-Auth': hmac.toString(),
},
);
if (response.statusCode == 200) {
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'success') {
return response.body;
}
if (result is Map && result['status'] == 'success') {
return jsonEncode(result);
return jsonData['status'];
} else if (response.statusCode == 401) {
// Specifically handle 401 Unauthorized
var jsonData = jsonDecode(response.body);
if (jsonData['error'] == 'Token expired') {
// Show snackbar prompting to re-login
await Get.put(LoginController()).getJwtWallet();
return 'token_expired'; // Return a specific value for token expiration
} else {
// Other 401 errors
addError('Unauthorized: ${jsonData['error']}', 'crud().post - 401',
url.toString());
return 'failure';
}
} else {
addError('Non-200 response code: ${response.statusCode}',
'crud().post - Other', url.toString());
return 'failure';
}
return result;
}
// =======================================================================
// All other specialized methods remain below.
// They are kept separate because they interact with external third-party APIs
@@ -282,11 +312,6 @@ class CRUD {
},
);
print('req: ${response.request}');
print('status: ${response.statusCode}');
print('body: ${response.body}');
print('payload: $payload');
Map<String, dynamic> wrap(String status, {Object? message, int? code}) {
return {
'status': status,
@@ -728,9 +753,6 @@ class CRUD {
url,
body: payload,
);
// Log.print('req: ${response.request}');
// Log.print('response: ${response.body}');
// Log.print('payload: ${payload}');
var jsonData = jsonDecode(response.body);
if (jsonData['status'] == 'OK') {
return jsonData;

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

@@ -1,12 +1,9 @@
import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/env/env.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter/foundation.dart';
import 'package:secure_string_operations/secure_string_operations.dart';
import '../../constant/char_map.dart';
import '../../main.dart';
import '../../print.dart';
class EncryptionHelper {
static EncryptionHelper? _instance;

View File

@@ -330,7 +330,7 @@ class DeviceHelper {
// Extract relevant device information
final String deviceId = Platform.isAndroid
? deviceData['androidId'] ?? deviceData['serialNumber'] ?? 'unknown'
? deviceData['androidId'] ?? deviceData['fingerprint'] ?? 'unknown'
: deviceData['identifierForVendor'] ?? 'unknown';
final String deviceModel = deviceData['model'] ?? 'unknown';

View File

@@ -26,10 +26,10 @@ class SecureStorage {
const List<String> keysToFetch = [
'serverPHP',
'seferAlexandriaServer',
'seferPaymentServer',
'seferCairoServer',
'seferGizaServer',
// 'seferAlexandriaServer',
// 'seferPaymentServer',
// 'seferCairoServer',
// 'seferGizaServer',
];
class AppInitializer {
@@ -39,10 +39,9 @@ class AppInitializer {
if (box.read(BoxName.jwt) == null) {
await LoginController().getJWT();
} else {
bool isTokenExpired = JwtDecoder.isExpired(X
.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
.toString()
.split(AppInformation.addd)[0]);
bool isTokenExpired = JwtDecoder.isExpired(
r(box.read(BoxName.jwt)).toString().split(AppInformation.addd)[0]);
if (isTokenExpired) {
await LoginController().getJWT();
}

View File

@@ -174,9 +174,9 @@ class MapPassengerController extends GetxController {
bool rideConfirm = false;
bool isMarkersShown = false;
bool isMainBottomMenuMap = true;
late Timer markerReloadingTimer2;
late Timer markerReloadingTimer1;
late int durationToPassenger = 0;
Timer? markerReloadingTimer2 = Timer(Duration.zero, () {});
Timer? markerReloadingTimer1 = Timer(Duration.zero, () {});
int durationToPassenger = 0;
bool isWayPointSheet = false;
bool isWayPointStopsSheet = false;
bool isWayPointStopsSheetUtilGetMap = false;
@@ -192,7 +192,7 @@ class MapPassengerController extends GetxController {
var dataCarsLocationByPassenger;
var datadriverCarsLocationToPassengerAfterApplied;
CarLocation? nearestCar;
late Timer markerReloadingTimer;
late Timer? markerReloadingTimer = Timer(Duration.zero, () {});
bool shouldFetch = true; // Flag to determine if fetch should be executed
int selectedPassengerCount = 1;
double progress = 0;
@@ -245,7 +245,7 @@ class MapPassengerController extends GetxController {
late String driverToken = '';
int carsOrder = 0;
int wayPointIndex = 0;
late double kazan;
late double kazan = 8;
String? mapAPIKEY;
late double totalME = 0;
late double tax = 0;
@@ -273,7 +273,10 @@ class MapPassengerController extends GetxController {
int minutes = 0;
// --- إضافة جديدة: للوصول إلى وحدة التحكم بالروابط ---
final DeepLinkController _deepLinkController = Get.find();
final DeepLinkController _deepLinkController =
Get.isRegistered<DeepLinkController>()
? Get.find<DeepLinkController>()
: Get.put(DeepLinkController());
// ------------------------------------------------
void onChangedPassengerCount(int newValue) {
@@ -2640,6 +2643,15 @@ class MapPassengerController extends GetxController {
'northeastLon': bounds.northeast.longitude.toString(),
});
break;
case 'Electric':
res = await CRUD()
.get(link: AppLink.getCarsLocationByPassengerElectric, payload: {
'southwestLat': bounds.southwest.latitude.toString(),
'southwestLon': bounds.southwest.longitude.toString(),
'northeastLat': bounds.northeast.latitude.toString(),
'northeastLon': bounds.northeast.longitude.toString(),
});
break;
case 'Pink Bike':
res = await CRUD()
.get(link: AppLink.getCarsLocationByPassengerPinkBike, payload: {
@@ -3198,9 +3210,9 @@ class MapPassengerController extends GetxController {
// 1. إلغاء المؤقتات الفردية
// Using ?.cancel() is safe even if the timer is null
markerReloadingTimer.cancel();
markerReloadingTimer1.cancel();
markerReloadingTimer2.cancel();
markerReloadingTimer!.cancel();
markerReloadingTimer1!.cancel();
markerReloadingTimer2!.cancel();
timerToPassengerFromDriverAfterApplied?.cancel();
_timer?.cancel();
@@ -3302,11 +3314,6 @@ class MapPassengerController extends GetxController {
}
Future cancelRide() async {
// if (rideConfirm == true ||
// statusRide == 'Apply' ||
// statusRide == 'Applied' ||
// statusRide == 'wait' ||
// statusRide == 'waiting') {
clearPlacesDestination();
clearPolyline();
// clearPolylineAll();
@@ -3315,7 +3322,7 @@ class MapPassengerController extends GetxController {
if (rideId != 'yet') {
Log.print('cancelRide: 1');
await firebaseMessagesController.sendNotificationToDriverMAP(
'Cancel Trip'.tr,
'Cancel Trip',
'Trip Cancelled'.tr,
driverToken.toString(),
[],
@@ -3336,31 +3343,8 @@ class MapPassengerController extends GetxController {
"status": 'Cancel'
}),
]);
if (AppLink.endPoint != AppLink.IntaleqCairoServer) {
CRUD().post(
link: "${AppLink.endPoint}/ride/driver_order/update.php",
payload: {
"order_id": rideId.toString(), // Convert to String
"status": 'Cancel'
});
CRUD()
.post(link: "${AppLink.endPoint}/ride/rides/update.php", payload: {
"id": rideId.toString(), // Convert to String
"status": 'Cancel'
});
CRUD().post(
link:
"${AppLink.endPoint}/ride/notificationCaptain/updateWaitingTrip.php",
payload: {
"id": rideId.toString(), // Convert to String
"status": 'Cancel'
});
}
print('Cancel');
// }
}
Future.delayed(const Duration(seconds: 1));
// Future.delayed(const Duration(seconds: 1));
Get.offAll(() => const MapPagePassenger());
}
@@ -4560,6 +4544,7 @@ class MapPassengerController extends GetxController {
url += '&waypoints=$formattedWaypoints';
}
var response = await CRUD().getGoogleApi(link: url, payload: {});
data = response['routes'][0]['legs'];
box.remove(BoxName.tripData);
box.write(BoxName.tripData, response);
@@ -4642,10 +4627,17 @@ class MapPassengerController extends GetxController {
if (polyLines.isNotEmpty) {
clearPolyline();
} else {
// الآن بإمكانك قراءة القيمة من الـBox في أي مكان:
bool lowEndMode = box.read(BoxName.lowEndMode) ?? true;
// الآن نقرأ القيمة ونحدد عدد النقاط بناءً عليها
bool lowEndMode = box.read(BoxName.lowEndMode) ??
false; // الأفضل أن يكون الافتراضي هو الجودة العالية
// نمرر عدد النقاط المناسب هنا
animatePolylineLayered(
polylineCoordinates,
maxPoints:
lowEndMode ? 30 : 150, // 30 نقطة لوضع الأداء، 150 للوضع العادي
);
animatePolylineLayered(polylineCoordinates);
rideConfirm = false;
isMarkersShown = true;
@@ -4680,12 +4672,13 @@ class MapPassengerController extends GetxController {
// 2) رسم متدرّج بطبقات متراكبة (بدون حذف)، برونزي ↔ أخضر، مع zIndex وعرض مختلف
Future<void> animatePolylineLayered(List<LatLng> coordinates,
{int layersCount = 8, int stepDelayMs = 10}) async {
{int layersCount = 1, int stepDelayMs = 10, int maxPoints = 150}) async {
// امسح أي طبقات قديمة فقط الخاصة بالطريق
polyLines.removeWhere((p) => p.polylineId.value.startsWith('route_layer_'));
update();
final List<LatLng> coords = _downsampleEven(coordinates, maxPoints: 20);
final List<LatLng> coords =
_downsampleEven(coordinates, maxPoints: maxPoints);
if (coords.length < 2) return;
// ألوان مع شفافية خفيفة للتمييز
@@ -4816,6 +4809,7 @@ class MapPassengerController extends GetxController {
var url =
('${AppLink.googleMapsLink}directions/json?&language=${box.read(BoxName.lang)}&avoid=tolls|ferries&destination=$destinationSteps&origin=$originSteps&key=${AK.mapAPIKEY}');
var response = await CRUD().getGoogleApi(link: url, payload: {});
data = response['routes'][0]['legs'];
// isLoading = false;
@@ -5300,30 +5294,23 @@ class MapPassengerController extends GetxController {
changeBottomSheetShown();
}
addToken() async {
String fingerPrint = await DeviceHelper.getDeviceFingerprint();
// addToken() 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
});
CRUD().postWallet(
link: "${AppLink.seferPaymentServer}/ride/firebase/add.php",
payload: {
'token': (box.read(BoxName.tokenFCM.toString())),
'passengerID': box.read(BoxName.passengerID).toString(),
"fingerPrint": fingerPrint
});
// CRUD().post(
// link: "${AppLink.IntaleqGizaServer}/ride/firebase/add.php",
// payload: {
// 'token': (box.read(BoxName.tokenFCM.toString())),
// 'passengerID': box.read(BoxName.passengerID).toString(),
// "fingerPrint": fingerPrint
// });
}
// 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
// });
// CRUD().postWallet(
// link: "${AppLink.seferPaymentServer}/ride/firebase/add.php",
// payload: {
// 'token': (box.read(BoxName.tokenFCM.toString())),
// 'passengerID': box.read(BoxName.passengerID).toString(),
// "fingerPrint": fingerPrint
// });
// }
List<LatLng> polylineCoordinate = [];
String? cardNumber;
@@ -5794,13 +5781,13 @@ class MapPassengerController extends GetxController {
void onInit() async {
super.onInit();
// // --- إضافة جديدة: تهيئة وحدة التحكم في الروابط العميقة ---
// Get.put(DeepLinkController(), permanent: true);
Get.put(DeepLinkController(), permanent: true);
// // ----------------------------------------------------
// مرحلة 0: الضروري جداً لعرض الخريطة سريعاً
mapAPIKEY = await storage.read(key: BoxName.mapAPIKEY);
// mapAPIKEY = await storage.read(key: BoxName.mapAPIKEY);
await initilizeGetStorage(); // إعداد سريع
await _initMinimalIcons(); // start/end فقط
await addToken(); // لو لازم للمصادقة
// await addToken(); // لو لازم للمصادقة
_listenForDeepLink();
await getLocation(); // لتحديد الكاميرا
box.write(BoxName.carType, 'yet');

View File

@@ -1,110 +1,140 @@
import 'dart:async';
import 'package:Intaleq/constant/style.dart';
import 'package:Intaleq/controller/functions/secure_storage.dart';
import 'package:Intaleq/views/widgets/my_scafold.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:Intaleq/views/auth/login_page.dart';
import 'package:package_info_plus/package_info_plus.dart';
// import 'package:uni_links/uni_links.dart';
import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/onbording_page.dart';
import 'package:Intaleq/views/auth/login_page.dart';
import 'package:Intaleq/controller/auth/login_controller.dart';
import 'package:Intaleq/controller/functions/secure_storage.dart';
import 'package:Intaleq/views/widgets/my_scafold.dart';
import 'package:Intaleq/constant/style.dart';
import '../../constant/box_name.dart';
import '../../main.dart';
import '../../onbording_page.dart';
import '../../views/auth/otp_page.dart';
import '../auth/login_controller.dart';
// كنترولر مع منطق تحميل محسن ينتظر العمليات غير المتزامنة
class SplashScreenController extends GetxController
with GetTickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> animation;
// الحركات الخاصة بكل عنصر من عناصر الواجهة
late Animation<double> titleFadeAnimation;
late Animation<double> titleScaleAnimation;
late Animation<double> taglineFadeAnimation;
late Animation<Offset> taglineSlideAnimation;
late Animation<double> footerFadeAnimation;
final progress = 0.0.obs;
Timer? _progressTimer;
String packageInfo = '';
Future<void> _getPackageInfo() async {
final info = await PackageInfo.fromPlatform();
packageInfo = info.version;
box.write(BoxName.packagInfo, packageInfo);
update();
}
String iss = '';
@override
Future<void> onInit() async {
void onInit() {
super.onInit();
// storage.read(key: 'iss').then((s) {
// // print(s);
// iss = s!;
// });
// if (iss == null) {
SecureStorage().saveData('iss', 'mobile-app:');
// }
_getPackageInfo();
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1500), // Reduced duration
)..forward();
duration: const Duration(milliseconds: 2000),
);
animation =
CurvedAnimation(parent: _animationController, curve: Curves.easeOut);
// --- تعريف الحركات المتتالية ---
titleFadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: _animationController,
curve: const Interval(0.0, 0.5, curve: Curves.easeOut),
),
);
titleScaleAnimation = Tween<double>(begin: 0.8, end: 1.0).animate(
CurvedAnimation(
parent: _animationController,
curve: const Interval(0.0, 0.5, curve: Curves.easeOut),
),
);
taglineFadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: _animationController,
curve: const Interval(0.3, 0.8, curve: Curves.easeOut),
),
);
taglineSlideAnimation =
Tween<Offset>(begin: const Offset(0, 0.5), end: Offset.zero).animate(
CurvedAnimation(
parent: _animationController,
curve: const Interval(0.3, 0.8, curve: Curves.easeOut),
),
);
footerFadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: _animationController,
curve: const Interval(0.5, 1.0, curve: Curves.easeOut),
),
);
startTimer();
_startProgressTimer();
_animationController.forward();
// بدء عملية التهيئة والتحميل
_initializeApp();
}
void _startProgressTimer() {
const totalTime = 2000; // 5 seconds in milliseconds
const interval = 50; // Update every 50ms
/// تهيئة التطبيق وانتظار انتهاء التحميل قبل الانتقال
Future<void> _initializeApp() async {
// تشغيل مؤقت شريط التقدم ليعطي انطباعاً مرئياً فقط
_startProgressAnimation();
// تعريف مهمتين: منطق التحميل، والحد الأدنى لوقت عرض الشاشة
final logicFuture = _performNavigationLogic();
final minTimeFuture = Future.delayed(const Duration(seconds: 3));
// الانتظار حتى انتهاء المهمتين معاً
await Future.wait([logicFuture, minTimeFuture]);
// بعد انتهاء الانتظار، سيتم الانتقال تلقائياً من داخل a_performNavigationLogic
}
/// تشغيل حركة شريط التقدم بشكل مرئي ومنفصل عن منطق التحميل
void _startProgressAnimation() {
const totalTime = 2800; // مدة ملء الشريط
const interval = 50;
int elapsed = 0;
_progressTimer =
Timer.periodic(const Duration(milliseconds: interval), (timer) async {
Timer.periodic(const Duration(milliseconds: interval), (timer) {
elapsed += interval;
progress.value = (elapsed / totalTime).clamp(0.0, 1.0);
if (elapsed >= totalTime) {
timer.cancel();
// await SecurityHelper.performSecurityChecks();
// if (box.read('isNotTrust') ||
// box.read('isJailBroken') ||
// box.read('isTampered')) {
// Get.to(() => SecurityPage());
// } else {
box.read(BoxName.onBoarding) == null
? Get.off(() => OnBoardingPage())
: box.read(BoxName.email) != null &&
box.read(BoxName.phone) != null &&
box.read(BoxName.isVerified) == '1'
// ? Get.off(() => const MapPagePassenger())
? await Get.put(LoginController()).loginUsingCredentials(
box.read(BoxName.passengerID).toString(),
box.read(BoxName.email).toString(),
)
: Get.off(() => LoginPage());
}
// }
});
}
void startTimer() async {
Timer(const Duration(seconds: 5), () async {
// box.read(BoxName.onBoarding) == null
// ? Get.off(() => OnBoardingPage())
// : box.read(BoxName.email) != null &&
// box.read(BoxName.phone) != null &&
// box.read(BoxName.isVerified) == '1'
// // ? Get.off(() => const MapPagePassenger())
// ? await Get.put(LoginController()).loginUsingCredentials(
// box.read(BoxName.passengerID).toString(),
// box.read(BoxName.email).toString(),
// )
// : Get.off(() => LoginPage());
});
/// تنفيذ منطق التحميل الفعلي وتسجيل الدخول وتحديد وجهة الانتقال
Future<void> _performNavigationLogic() async {
// تنفيذ المهام الأولية
await _getPackageInfo();
SecureStorage().saveData('iss', 'mobile-app:');
// تحديد الشاشة التالية
if (box.read(BoxName.onBoarding) == null) {
Get.off(() => OnBoardingPage());
} else if (box.read(BoxName.email) != null &&
box.read(BoxName.phone) != null &&
box.read(BoxName.isVerified) == '1') {
// -- النقطة الأهم --
// هنا ننتظر انتهاء عملية تسجيل الدخول قبل الانتقال
await Get.put(LoginController()).loginUsingCredentials(
box.read(BoxName.passengerID).toString(),
box.read(BoxName.email).toString(),
);
// بعد هذه العملية، سيتولى LoginController بنفسه الانتقال للصفحة الرئيسية أو صفحة الدخول
} else {
Get.off(() => LoginPage());
}
}
/// جلب معلومات الحزمة لعرض إصدار التطبيق
Future<void> _getPackageInfo() async {
final info = await PackageInfo.fromPlatform();
box.write(BoxName.packagInfo, info.version);
update();
}
@override
@@ -115,6 +145,7 @@ class SplashScreenController extends GetxController
}
}
// يمكن الإبقاء على هذه الفئة لواجهة المستخدم المتعلقة بالأمان كما في الملف الأصلي
class SecurityPage extends StatelessWidget {
const SecurityPage({
super.key,

View File

@@ -5,7 +5,7 @@ class MyTranslation extends Translations {
Map<String, Map<String, String>> get keys => {
"ar": {
"Syria": "سوريا",
"SYP": "ليرة سورية",
"SYP": "ل",
"Order": "طلب",
"OrderVIP": "طلب VIP",
"Hi ,I Arrive your site": "أنا وصلت لموقعك",
@@ -141,10 +141,15 @@ class MyTranslation extends Translations {
"Order for myself": "اطلب لنفسي",
"Are you want to go this site": "هل تريد الذهاب إلى هذا الموقع؟",
"No": "لا",
'Pay by Sham Cash': 'الدفع عبر شام كاش',
"Intaleq Wallet": "محفظة انطلق",
"Have a promo code?": "هل لديك رمز خصم؟",
"Your Wallet balance is ": "رصيد محفظتك هو ",
"Cash": "كاش",
'Phone Number': 'رقم الموبايل',
'Search country': 'ابحث عن دولة',
'Payment Successful!': 'تم الدفع بنجاح!',
'Your payment was successful.': 'تم الدفع بنجاح.',
"Pay directly to the captain": "ادفع للكابتن مباشرة",
"Top up Wallet to continue": "اشحن المحفظة للمتابعة",
"Or pay with Cash instead": "أو ادفع كاش بدلاً من ذلك",

26108
lib/env/env.g.dart vendored

File diff suppressed because it is too large Load Diff

View File

@@ -36,8 +36,8 @@ import 'splash_screen_page.dart';
final box = GetStorage();
final storage = FlutterSecureStorage();
// final PaymobPayment paymobPayment = PaymobPayment();
final PaymobPayment paymobPayment = PaymobPayment();
final PaymobPaymentWallet paymobPaymentWallet = PaymobPaymentWallet();
// final PaymobPayment paymobPayment = PaymobPayment();
// final PaymobPaymentWallet paymobPaymentWallet = PaymobPaymentWallet();
DbSql sql = DbSql.instance;
// EncryptionHelper encryptionHelper = EncryptionHelper.instance;
@@ -48,121 +48,246 @@ Future<void> backgroundMessageHandler(RemoteMessage message) async {
FirebaseMessagesController().fireBaseTitles(message);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
WakelockPlus.enable();
void main() {
// ⚠️ لا تستدعِ ensureInitialized هنا خارج الزون
await GetStorage.init();
// --- إضافة جديدة: تهيئة وحدة التحكم في الروابط العميقة ---
Get.put(DeepLinkController(), permanent: true);
// ----------------------------------------------------
final AppInitializer initializer = AppInitializer();
runZonedGuarded(() async {
// 1) أنشئ الـ Binding في نفس الـ Zone
WidgetsFlutterBinding.ensureInitialized();
await initializer.initializeApp();
await EncryptionHelper.initialize();
NotificationController notificationController =
Get.put(NotificationController());
Stripe.publishableKey = AK.publishableKey;
// if (box.read(BoxName.driverID) != null) {}
if (Platform.isAndroid || Platform.isIOS) {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await FirebaseMessagesController().requestFirebaseMessagingPermission();
FirebaseMessaging.onBackgroundMessage(backgroundMessageHandler);
List<Future> initializationTasks = [
FirebaseMessagesController().getNotificationSettings(),
FirebaseMessagesController().getToken(),
];
// cameras = await availableCameras();
await Future.wait(initializationTasks);
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
await notificationController.initNotifications();
// Generate a random index to pick a message
final random = Random();
final randomMessage = messages[random.nextInt(messages.length)];
// Schedule the notification with the random message
notificationController.scheduleNotificationsForSevenDays(
randomMessage.split(':')[0],
randomMessage.split(':')[1],
"tone1",
);
// final encryptionHelper = await EncryptionHelper.initialize();
final QuickActions quickActions = QuickActions();
quickActions.initialize((String shortcutType) {
// print('Activated shortcut: $shortcutType');
if (shortcutType == 'share_app') {
Get.toNamed('/shareApp');
} else if (shortcutType == 'wallet') {
Get.toNamed('/wallet');
} else if (shortcutType == 'profile') {
Get.toNamed('/profile');
} else if (shortcutType == 'contact_support') {
Get.toNamed('/contactSupport');
// 2) تهيئات خفيفة فقط قبل runApp
await GetStorage.init();
if (Platform.isAndroid || Platform.isIOS) {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform);
FirebaseMessaging.onBackgroundMessage(backgroundMessageHandler);
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
});
quickActions.setShortcutItems(<ShortcutItem>[
ShortcutItem(
type: 'share_app',
localizedTitle: 'Share App'.tr,
icon: 'icon_share',
),
ShortcutItem(
type: 'wallet',
localizedTitle: 'Wallet'.tr,
icon: 'icon_wallet',
),
ShortcutItem(
type: 'profile',
localizedTitle: 'Profile'.tr,
icon: 'icon_user',
),
ShortcutItem(
type: 'contact_support',
localizedTitle: 'Contact Support'.tr,
icon: 'icon_support',
),
]);
Stripe.publishableKey = AK.publishableKey;
Get.put(DeepLinkController(), permanent: true);
runZonedGuarded<Future<void>>(() async {
// 3) شغّل التطبيق فوراً
runApp(const MyApp());
// 4) بعد أول إطار: التهيئات الثقيلة
WidgetsBinding.instance.addPostFrameCallback((_) async {
// لا Wakelock عالمي — فعّله فقط أثناء الرحلة
await WakelockPlus.enable();
final AppInitializer initializer = AppInitializer();
await initializer.initializeApp();
await EncryptionHelper.initialize();
final notificationController = Get.put(NotificationController());
await notificationController.initNotifications();
// أجّل طلب صلاحيات/توكن FCM
final fcm = FirebaseMessagesController();
await fcm.requestFirebaseMessagingPermission();
await fcm.getNotificationSettings();
await fcm.getToken();
// Generate a random index to pick a message
// Generate and schedule passenger daily notifications safely
try {
// 1) تأكد أن القائمة موجودة وغير فارغة
final List<String> msgs = passengerMessages ?? const [];
if (msgs.isEmpty) {
// fallback افتراضي إذا ما في رسائل
const fallbackTitle = 'Intaleq';
const fallbackBody = 'مرحباً بك! تابع رحلاتك بأمان مع انطلق.';
notificationController.scheduleNotificationsForSevenDays(
fallbackTitle,
fallbackBody,
"tone1",
);
} else {
// 2) اختَر عنصرًا عشوائيًا بأمان
final rnd = Random();
final idx = rnd.nextInt(msgs.length); // msgs.length > 0 أكيد
final raw = msgs[idx];
// 3) افصل العنوان/النص بأمان حتى لو ما في ':'
final parts = raw.split(':');
final title = parts.isNotEmpty ? parts.first.trim() : 'Intaleq';
final body = parts.length > 1
? parts.sublist(1).join(':').trim() // يحافظ على أي ':' إضافية
: 'مرحباً بك! تابع رحلاتك بأمان مع انطلق.';
// 4) جدولة الإشعارات
notificationController.scheduleNotificationsForSevenDays(
title.isEmpty ? 'Intaleq' : title,
body.isEmpty ? 'مرحباً بك! تابع رحلاتك بأمان مع انطلق.' : body,
"tone1",
);
}
} catch (e, st) {
// لا تعطل التشغيل بسبب إشعار اختياري
CRUD.addError('notif_init: $e', st.toString(), 'main');
}
final QuickActions quickActions = QuickActions();
quickActions.initialize((String shortcutType) {
// print('Activated shortcut: $shortcutType');
if (shortcutType == 'share_app') {
Get.toNamed('/shareApp');
} else if (shortcutType == 'wallet') {
Get.toNamed('/wallet');
} else if (shortcutType == 'profile') {
Get.toNamed('/profile');
} else if (shortcutType == 'contact_support') {
Get.toNamed('/contactSupport');
}
});
quickActions.setShortcutItems(<ShortcutItem>[
ShortcutItem(
type: 'share_app',
localizedTitle: 'Share App'.tr,
icon: 'icon_share',
),
ShortcutItem(
type: 'wallet',
localizedTitle: 'Wallet'.tr,
icon: 'icon_wallet',
),
ShortcutItem(
type: 'profile',
localizedTitle: 'Profile'.tr,
icon: 'icon_user',
),
ShortcutItem(
type: 'contact_support',
localizedTitle: 'Contact Support'.tr,
icon: 'icon_support',
),
]);
});
}, (error, stack) {
// ==== START: ERROR FILTER ====
String errorString = error.toString();
// Print all errors to the local debug console for development
print("Caught Dart error: $error");
print(stack);
// We will check if the error contains keywords for errors we want to ignore.
// If it's one of them, we will NOT send it to the server.
bool isIgnoredError = errorString.contains('PERMISSION_DENIED') ||
errorString.contains('FormatException') ||
errorString.contains('Null check operator used on a null value');
if (!isIgnoredError) {
// Only send the error to the server if it's not in our ignore list.
CRUD.addError(error.toString(), stack.toString(), 'main');
} else {
print("Ignoring error and not sending to server: $errorString");
}
// ==== END: ERROR FILTER ====
// بديل آمن للتجميع
final s = error.toString();
final ignored = s.contains('PERMISSION_DENIED') ||
s.contains('FormatException') ||
s.contains('Null check operator used on a null value');
if (!ignored) CRUD.addError(s, stack.toString(), 'main');
});
}
} // void main() async {
// WidgetsFlutterBinding.ensureInitialized();
// WakelockPlus.enable();
// await GetStorage.init();
// // --- إضافة جديدة: تهيئة وحدة التحكم في الروابط العميقة ---
// Get.put(DeepLinkController(), permanent: true);
// // ----------------------------------------------------
// final AppInitializer initializer = AppInitializer();
// await initializer.initializeApp();
// await EncryptionHelper.initialize();
// NotificationController notificationController =
// Get.put(NotificationController());
// // Stripe.publishableKey = AK.publishableKey;
// // if (box.read(BoxName.driverID) != null) {}
// if (Platform.isAndroid || Platform.isIOS) {
// await Firebase.initializeApp(
// options: DefaultFirebaseOptions.currentPlatform,
// );
// await FirebaseMessagesController().requestFirebaseMessagingPermission();
// FirebaseMessaging.onBackgroundMessage(backgroundMessageHandler);
// List<Future> initializationTasks = [
// FirebaseMessagesController().getNotificationSettings(),
// FirebaseMessagesController().getToken(),
// ];
// // cameras = await availableCameras();
// await Future.wait(initializationTasks);
// SystemChrome.setPreferredOrientations([
// DeviceOrientation.portraitUp,
// DeviceOrientation.portraitDown,
// ]);
// }
// await notificationController.initNotifications();
// // Generate a random index to pick a message
// final random = Random();
// final randomMessage = messages[random.nextInt(messages.length)];
// // Schedule the notification with the random message
// notificationController.scheduleNotificationsForSevenDays(
// randomMessage.split(':')[0],
// randomMessage.split(':')[1],
// "tone1",
// );
// final QuickActions quickActions = QuickActions();
// quickActions.initialize((String shortcutType) {
// // print('Activated shortcut: $shortcutType');
// if (shortcutType == 'share_app') {
// Get.toNamed('/shareApp');
// } else if (shortcutType == 'wallet') {
// Get.toNamed('/wallet');
// } else if (shortcutType == 'profile') {
// Get.toNamed('/profile');
// } else if (shortcutType == 'contact_support') {
// Get.toNamed('/contactSupport');
// }
// });
// quickActions.setShortcutItems(<ShortcutItem>[
// ShortcutItem(
// type: 'share_app',
// localizedTitle: 'Share App'.tr,
// icon: 'icon_share',
// ),
// ShortcutItem(
// type: 'wallet',
// localizedTitle: 'Wallet'.tr,
// icon: 'icon_wallet',
// ),
// ShortcutItem(
// type: 'profile',
// localizedTitle: 'Profile'.tr,
// icon: 'icon_user',
// ),
// ShortcutItem(
// type: 'contact_support',
// localizedTitle: 'Contact Support'.tr,
// icon: 'icon_support',
// ),
// ]);
// runZonedGuarded<Future<void>>(() async {
// runApp(const MyApp());
// }, (error, stack) {
// // ==== START: ERROR FILTER ====
// String errorString = error.toString();
// // Print all errors to the local debug console for development
// print("Caught Dart error: $error");
// print(stack);
// // We will check if the error contains keywords for errors we want to ignore.
// // If it's one of them, we will NOT send it to the server.
// bool isIgnoredError = errorString.contains('PERMISSION_DENIED') ||
// errorString.contains('FormatException') ||
// errorString.contains('Null check operator used on a null value');
// if (!isIgnoredError) {
// // Only send the error to the server if it's not in our ignore list.
// CRUD.addError(error.toString(), stack.toString(), 'main');
// } else {
// print("Ignoring error and not sending to server: $errorString");
// }
// // ==== END: ERROR FILTER ====
// });
// }
class MyApp extends StatelessWidget {
const MyApp({super.key});

View File

@@ -1,133 +1,136 @@
import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shimmer/shimmer.dart'; // Added for a premium shimmer effect
import 'package:Intaleq/constant/colors.dart';
import 'package:Intaleq/constant/info.dart';
import 'package:Intaleq/constant/style.dart';
import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/main.dart';
import 'constant/box_name.dart';
import 'controller/home/splash_screen_controlle.dart';
import 'main.dart';
// شاشة بداية بتصميم جديد وحركات وألوان محسّنة
class SplashScreen extends StatelessWidget {
final SplashScreenController splashScreenController =
Get.put(SplashScreenController());
SplashScreen({super.key});
const SplashScreen({super.key});
@override
Widget build(BuildContext context) {
// Using SafeArea to prevent UI overlap with system notches or bars
// تهيئة الكنترولر
final SplashScreenController controller = Get.put(SplashScreenController());
// تعريف الألوان المستخدمة في حركة اسم التطبيق
const colorizeColors = [
Colors.white,
Color(0xFF89D4CF), // لون تركواز فاتح
Color(0xFF734AE8), // لون بنفسجي مشرق
Colors.white,
];
return SafeArea(
child: Scaffold(
body: Container(
// The gradient background is maintained from your original design.
// --- تحسين الألوان ---
// تم استخدام تدرج لوني جديد أكثر حيوية وعصرية
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
AppColor.primaryColor,
AppColor.secondaryColor,
Color(0xFF2E3192), // أزرق داكن
Color(0xFF1BFFFF), // سماوي ساطع
],
),
),
// Using a Stack to layer the main content and the footer.
child: Stack(
children: [
// Main animated content (logo and titles) centered on the screen.
// دوائر زخرفية لإضافة عمق للتصميم
_buildDecorativeCircles(),
// المحتوى الرئيسي مع الحركات المتتالية
Center(
child: GetBuilder<SplashScreenController>(
builder: (_) {
// The initial animation is preserved for the overall entrance
return ScaleTransition(
scale: splashScreenController.animation,
child: FadeTransition(
opacity: splashScreenController.animation,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Logo remains the same
Image.asset(
'assets/images/logo.gif',
width: Get.width * 0.35,
),
const SizedBox(height: 24),
// IMPROVEMENT: Added a Shimmer effect for a more dynamic title
Shimmer.fromColors(
baseColor: AppColor.writeColor,
highlightColor: Colors.grey.shade400,
child: Text(
AppInformation.appName,
style: AppStyle.headTitle.copyWith(
color: AppColor.writeColor,
fontSize: 48,
fontWeight: FontWeight.bold,
shadows: [
const Shadow(
blurRadius: 10.0,
color: Colors.black26,
offset: Offset(2.0, 2.0),
),
],
),
),
),
const SizedBox(height: 12),
// IMPROVEMENT: Using AnimatedTextKit for an engaging tagline
AnimatedTextKit(
animatedTexts: [
TyperAnimatedText(
'Your Journey Begins Here'.tr,
textStyle: AppStyle.title.copyWith(
color: AppColor.writeColor.withOpacity(0.8),
fontSize: 18,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// --- حركة اسم التطبيق ---
// تم إلغاء الشعار واستبداله بحركة نصية ملونة لكلمة "Intaleq"
FadeTransition(
opacity: controller.titleFadeAnimation,
child: ScaleTransition(
scale: controller.titleScaleAnimation,
child: AnimatedTextKit(
animatedTexts: [
ColorizeAnimatedText(
'Intaleq',
textStyle: AppStyle.headTitle.copyWith(
fontSize: 65.0, // تكبير حجم الخط
fontWeight: FontWeight.bold,
shadows: [
const Shadow(
blurRadius: 15.0,
color: Colors.black38,
offset: Offset(0, 3.0),
),
speed: const Duration(milliseconds: 100),
),
],
isRepeatingAnimation: false,
],
),
colors: colorizeColors,
speed: const Duration(milliseconds: 300),
),
],
isRepeatingAnimation: false,
),
),
);
},
),
const SizedBox(height: 18),
// --- حركة الشعار النصي ---
FadeTransition(
opacity: controller.taglineFadeAnimation,
child: SlideTransition(
position: controller.taglineSlideAnimation,
child: Text(
'Your Journey Begins Here'.tr,
style: AppStyle.title.copyWith(
color: AppColor.writeColor.withOpacity(0.9),
fontSize: 18,
),
),
),
),
],
),
),
// Footer section for progress bar and version info.
// قسم سفلي لشريط التقدم ومعلومات الإصدار
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding:
const EdgeInsets.only(bottom: 40.0, left: 40, right: 40),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Using ClipRRect for cleaner rounded corners on the progress bar
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Obx(() => LinearProgressIndicator(
value: splashScreenController.progress.value,
backgroundColor:
AppColor.writeColor.withOpacity(0.2),
valueColor: const AlwaysStoppedAnimation<Color>(
AppColor.writeColor),
minHeight:
5, // Slightly thicker for better visibility
)),
),
const SizedBox(height: 20),
Text(
'Version: ${box.read(BoxName.packagInfo) ?? '1.0.0'}',
style: AppStyle.subtitle.copyWith(
color: AppColor.writeColor.withOpacity(0.7),
fontWeight: FontWeight.w600,
child: FadeTransition(
opacity: controller.footerFadeAnimation,
child: Padding(
padding: const EdgeInsets.only(
bottom: 40.0, left: 40, right: 40),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Obx(() => LinearProgressIndicator(
value: controller.progress.value,
backgroundColor:
AppColor.writeColor.withOpacity(0.2),
valueColor: const AlwaysStoppedAnimation<Color>(
AppColor.writeColor),
minHeight: 5,
)),
),
),
],
const SizedBox(height: 20),
Text(
'Version: ${box.read(BoxName.packagInfo) ?? '1.0.0'}',
style: AppStyle.subtitle.copyWith(
color: AppColor.writeColor.withOpacity(0.7),
fontWeight: FontWeight.w600,
),
),
],
),
),
),
),
@@ -137,4 +140,28 @@ class SplashScreen extends StatelessWidget {
),
);
}
/// بناء دوائر زخرفية لتحسين الخلفية
Widget _buildDecorativeCircles() {
return Stack(
children: [
Positioned(
top: -80,
left: -100,
child: CircleAvatar(
radius: 120,
backgroundColor: Colors.white.withOpacity(0.05),
),
),
Positioned(
bottom: -120,
right: -150,
child: CircleAvatar(
radius: 180,
backgroundColor: Colors.white.withOpacity(0.07),
),
),
],
);
}
}

View File

@@ -1,19 +1,24 @@
import 'package:Intaleq/controller/auth/login_controller.dart';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../constant/box_name.dart';
import '../../controller/auth/otp_controller.dart';
// --- placeholder imports ---
// These are assumed to exist from your original code.
// Make sure to have these files and controllers properly set up in your project.
import 'package:Intaleq/controller/auth/login_controller.dart';
import '../../controller/auth/otp_controller.dart'; // Assumed to be PhoneAuthHelper
import '../../controller/local/phone_intel/intl_phone_field.dart';
import '../../main.dart';
import '../../print.dart';
// --- end of placeholder imports ---
/// A visually revamped authentication screen with a glassmorphism effect.
/// It provides a consistent and beautiful UI for all authentication steps.
///
/// A hidden feature for testers is included: a long-press on the logo
/// will open a dialog for email/password login, suitable for app reviews.
class AuthScreen extends StatelessWidget {
final String title;
final String subtitle;
final Widget form;
// Using a more neutral, tech-themed animated logo
// final String logoUrl = 'https://i.gifer.com/ZZ5H.gif';
const AuthScreen({
super.key,
@@ -22,175 +27,269 @@ class AuthScreen extends StatelessWidget {
required this.form,
});
/// Shows a dialog for testers to log in using email and password.
/// This is triggered by a long-press on the logo or the explicit tester button.
void _showTesterLoginDialog(
BuildContext context, LoginController controller) {
final testerEmailController = TextEditingController();
final testerPasswordController = TextEditingController();
final testerFormKey = GlobalKey<FormState>();
showDialog(
context: context,
barrierDismissible: true,
builder: (BuildContext dialogContext) {
return BackdropFilter(
filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
child: AlertDialog(
backgroundColor: const Color(0xFF162232).withOpacity(0.85),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
title: const Text(
'App Tester Login',
textAlign: TextAlign.center,
style:
TextStyle(fontWeight: FontWeight.bold, color: Colors.white),
),
content: Form(
key: testerFormKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: testerEmailController,
keyboardType: TextInputType.emailAddress,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: 'Email',
labelStyle:
TextStyle(color: Colors.white.withOpacity(0.7)),
prefixIcon: Icon(Icons.email_outlined,
color: Colors.white.withOpacity(0.7)),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
BorderSide(color: Colors.white.withOpacity(0.3)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Color(0xFF00BFFF)),
),
),
validator: (value) => value == null || !value.contains('@')
? 'Enter a valid email'
: null,
),
const SizedBox(height: 16),
TextFormField(
controller: testerPasswordController,
obscureText: true,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: 'Password',
labelStyle:
TextStyle(color: Colors.white.withOpacity(0.7)),
prefixIcon: Icon(Icons.lock_outline,
color: Colors.white.withOpacity(0.7)),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
BorderSide(color: Colors.white.withOpacity(0.3)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Color(0xFF00BFFF)),
),
),
validator: (value) => value == null || value.isEmpty
? 'Enter a password'
: null,
),
],
),
),
actions: [
TextButton(
child: const Text('Cancel',
style: TextStyle(color: Colors.white70)),
onPressed: () => Navigator.of(dialogContext).pop(),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF00BFFF),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child:
const Text('Login', style: TextStyle(color: Colors.black)),
onPressed: () {
if (testerFormKey.currentState!.validate()) {
// Use the main controller to perform login
controller.emailController.text =
testerEmailController.text;
controller.passwordController.text =
testerPasswordController.text;
controller.login();
Navigator.of(dialogContext).pop();
}
},
),
],
),
);
},
);
}
@override
Widget build(BuildContext context) {
final controller = Get.find<LoginController>();
// We still need the controller for the hidden tester login
final loginController = Get.find<LoginController>();
return Scaffold(
body: Container(
// UPDATED: Changed gradient colors to a green theme
decoration: BoxDecoration(
// NEW: AI-inspired, brighter, and more dynamic color gradient
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Colors.teal.shade700, Colors.green.shade600],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFF00122E), Color(0xFF00285F)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/images/logo.gif', height: 120),
const SizedBox(height: 20),
// IconButton(
// onPressed: () {
// Get.find<LoginController>().getJWT();
// },
// icon: const Icon(Icons.add),
// ),
Text(
title,
style: const TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Colors.white),
child: Stack(
children: [
// Background shapes for a more dynamic feel
Positioned(
top: -100,
left: -100,
child: Container(
width: 250,
height: 250,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: const Color(0xFF00BFFF).withOpacity(0.15),
),
const SizedBox(height: 10),
Text(
subtitle,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16, color: Colors.white.withOpacity(0.8)),
),
),
Positioned(
bottom: -150,
right: -100,
child: Container(
width: 350,
height: 350,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: const Color(0xFF00BFFF).withOpacity(0.1),
),
const SizedBox(height: 30),
GetBuilder<LoginController>(builder: (context) {
return box.read(BoxName.isTest).toString() == '0'
? Container(
margin: const EdgeInsets.all(16),
padding: const EdgeInsets.symmetric(
horizontal: 24, vertical: 32),
),
),
Center(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// GestureDetector to handle long-press for tester login
GestureDetector(
onLongPress: () {
_showTesterLoginDialog(context, loginController);
},
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white.withOpacity(0.1),
border: Border.all(
color: Colors.white.withOpacity(0.2),
width: 2)),
child: ClipRRect(
borderRadius: BorderRadius.circular(50),
child: Image.asset('assets/images/logo.gif',
height: 100)),
),
),
const SizedBox(height: 20),
Text(
title,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Colors.white,
shadows: [
Shadow(
blurRadius: 10.0,
color: Colors.black26,
offset: Offset(2, 2)),
]),
),
const SizedBox(height: 10),
Text(
subtitle,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16,
color: Colors.white.withOpacity(0.8),
),
),
const SizedBox(height: 30),
// Glassmorphism Container for the form
ClipRRect(
borderRadius: BorderRadius.circular(25.0),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 15, sigmaY: 15),
child: Container(
padding: const EdgeInsets.all(24.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.black12,
blurRadius: 12,
offset: const Offset(0, 6),
color: Colors.white.withOpacity(0.1),
borderRadius: BorderRadius.circular(25.0),
border: Border.all(
color: Colors.white.withOpacity(0.2),
width: 1.5,
),
),
child:
form, // The form from the specific screen is placed here
),
),
),
const SizedBox(height: 20),
// A more distinct button for app testers
Material(
color: Colors.white.withOpacity(0.15),
borderRadius: BorderRadius.circular(12),
child: InkWell(
onTap: () =>
_showTesterLoginDialog(context, loginController),
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 10, horizontal: 16),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.admin_panel_settings_outlined,
color: Colors.white.withOpacity(0.8)),
const SizedBox(width: 8),
Text(
'For App Reviewers / Testers',
style: TextStyle(
color: Colors.white.withOpacity(0.8),
fontWeight: FontWeight.w600,
),
),
],
),
child: Form(
key: controller.formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Title
Text(
'Please login to continue',
style: TextStyle(
fontSize: 16,
color: Colors.grey[600],
),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
// Email Field
TextFormField(
keyboardType: TextInputType.emailAddress,
controller: controller.emailController,
decoration: InputDecoration(
labelText: 'Email'.tr,
hintText: 'Enter your email address'.tr,
prefixIcon:
const Icon(Icons.email_outlined),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
),
validator: (value) => value == null ||
value.isEmpty ||
!value.contains('@') ||
!value.contains('.')
? 'Enter a valid email'.tr
: null,
),
const SizedBox(height: 20),
// Password Field
TextFormField(
obscureText: true,
controller: controller.passwordController,
decoration: InputDecoration(
labelText: 'Password'.tr,
hintText: 'Enter your password'.tr,
prefixIcon: const Icon(Icons.lock_outline),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
),
validator: (value) =>
value == null || value.isEmpty
? 'Enter your password'.tr
: null,
),
const SizedBox(height: 24),
// Submit Button
GetBuilder<LoginController>(
builder: (controller) => controller.isloading
? const Center(
child: CircularProgressIndicator())
: SizedBox(
height: 50,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor:
Colors.blueAccent,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(12),
),
),
onPressed: () {
if (controller
.formKey.currentState!
.validate()) {
controller.login();
}
},
child: Text(
'Login'.tr,
style:
const TextStyle(fontSize: 16),
),
),
),
),
const SizedBox(height: 16),
// Optional: Forgot Password / Create Account
],
),
),
)
: Card(
elevation: 8,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)),
child: Padding(
padding: const EdgeInsets.all(24.0),
child: form,
),
);
}),
],
),
),
),
],
),
),
),
),
],
),
),
);
@@ -198,6 +297,8 @@ class AuthScreen extends StatelessWidget {
}
// --- UI Screens ---
// Note: These screens now use the new AuthScreen wrapper and have updated styling
// for their form elements to match the new design.
class PhoneNumberScreen extends StatefulWidget {
const PhoneNumberScreen({super.key});
@@ -213,16 +314,12 @@ class _PhoneNumberScreenState extends State<PhoneNumberScreen> {
void _submit() async {
if (_formKey.currentState!.validate()) {
setState(() => _isLoading = true);
// إزالة + من بداية الرقم
// PRODUCTION READY: Using the actual PhoneAuthHelper
final rawPhone = _phoneController.text.trim().replaceFirst('+', '');
final success = await PhoneAuthHelper.sendOtp(rawPhone);
if (success && mounted) {
Get.to(() => OtpVerificationScreen(phoneNumber: rawPhone));
}
if (mounted) setState(() => _isLoading = false);
}
}
@@ -237,74 +334,67 @@ class _PhoneNumberScreenState extends State<PhoneNumberScreen> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: IntlPhoneField(
// languageCode: 'ar',
showCountryFlag: false,
flagsButtonMargin: EdgeInsets.only(right: 8),
flagsButtonPadding: EdgeInsets.all(4),
dropdownDecoration:
BoxDecoration(borderRadius: BorderRadius.circular(8)),
// controller: _phoneController,
decoration: InputDecoration(
labelText: 'Phone Number'.tr,
border: const OutlineInputBorder(
borderSide: BorderSide(),
),
),
initialCountryCode: 'SY',
onChanged: (phone) {
// Properly concatenate country code and number
_phoneController.text = phone.completeNumber.toString();
Log.print(' phone.number: ${phone.number}');
print("Formatted phone number: ${_phoneController.text}");
},
validator: (phone) {
// Check if the phone number is not null and is valid
if (phone == null || phone.completeNumber.isEmpty) {
return 'Please enter your phone number';
}
// Extract the phone number (excluding the country code)
final number = phone.completeNumber.toString();
// Check if the number length is exactly 11 digits
if (number.length != 13) {
return 'Phone number must be exactly 11 digits long';
}
// If all validations pass, return null
return null;
},
),
Text(
'Enter your phone number'.tr,
style:
TextStyle(color: Colors.white.withOpacity(0.9), fontSize: 16),
textAlign: TextAlign.center,
),
const SizedBox(height: 20),
IntlPhoneField(
showCountryFlag: false,
searchText: 'Search country'.tr,
languageCode: 'ar',
style: const TextStyle(color: Colors.white),
dropdownTextStyle: const TextStyle(color: Colors.black87),
decoration: InputDecoration(
labelText: 'Phone Number'.tr,
labelStyle: TextStyle(color: Colors.white.withOpacity(0.7)),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.white.withOpacity(0.3)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Color(0xFF00BFFF)),
),
),
initialCountryCode: 'SY',
onChanged: (phone) {
_phoneController.text = phone.completeNumber;
},
validator: (phone) {
if (phone == null || phone.number.isEmpty) {
return 'Please enter your phone number';
}
if (phone.completeNumber.length < 10) {
// Example validation
return 'Phone number seems too short';
}
return null;
},
),
// TextFormField(
// controller: _phoneController,
// decoration: InputDecoration(
// labelText: 'phone number label'.tr,
// prefixIcon:
// Icon(Icons.phone_android, color: Colors.teal.shade400),
// border:
// OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
// ),
// keyboardType: TextInputType.phone,
// validator: (v) => v!.isEmpty ? 'phone number required'.tr : null,
// ),
const SizedBox(height: 24),
_isLoading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: _submit,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.teal,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
minimumSize: const Size(double.infinity, 50),
? const CircularProgressIndicator(color: Colors.white)
: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _submit,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF00BFFF),
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
),
child: Text(
'send otp button'.tr,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.black),
),
),
child: Text('send otp button'.tr),
),
],
),
@@ -322,61 +412,18 @@ class OtpVerificationScreen extends StatefulWidget {
class _OtpVerificationScreenState extends State<OtpVerificationScreen> {
final _formKey = GlobalKey<FormState>();
final TextEditingController _otpControllers = TextEditingController();
// final List<FocusNode> _focusNodes = List.generate(5, (_) => FocusNode());
final _otpController = TextEditingController();
bool _isLoading = false;
@override
void dispose() {
// for (var controller in _otpControllers) {
// controller.dispose();
// }
// for (var node in _focusNodes) {
// node.dispose();
// }
super.dispose();
}
void _submit() async {
if (_formKey.currentState!.validate()) {
setState(() => _isLoading = true);
final otp = _otpControllers.text;
await PhoneAuthHelper.verifyOtp(widget.phoneNumber, otp);
// PRODUCTION READY: Using the actual PhoneAuthHelper
await PhoneAuthHelper.verifyOtp(widget.phoneNumber, _otpController.text);
if (mounted) setState(() => _isLoading = false);
}
}
Widget _buildOtpInput() {
return Form(
key: _formKey,
child: Container(
width: 200,
height: 50,
decoration: BoxDecoration(
color: Colors.grey.shade200,
shape: BoxShape.circle,
),
child: Center(
child: TextFormField(
controller: _otpControllers,
// focusNode: _focusNodes[index],
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
maxLength: 5,
style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
decoration: const InputDecoration(
counterText: "",
border: InputBorder.none,
contentPadding: EdgeInsets.zero,
),
onChanged: (value) {},
validator: (v) => v!.isEmpty ? '' : null,
),
),
),
);
}
@override
Widget build(BuildContext context) {
return AuthScreen(
@@ -386,20 +433,60 @@ class _OtpVerificationScreenState extends State<OtpVerificationScreen> {
form: Column(
mainAxisSize: MainAxisSize.min,
children: [
_buildOtpInput(),
Text(
'Enter the 5-digit code'.tr,
style:
TextStyle(color: Colors.white.withOpacity(0.9), fontSize: 16),
textAlign: TextAlign.center,
),
const SizedBox(height: 20),
Form(
key: _formKey,
child: TextFormField(
controller: _otpController,
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
maxLength: 5,
style: const TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Colors.white,
letterSpacing: 18, // Visually separates the digits
),
decoration: InputDecoration(
counterText: "",
hintText: '-----',
hintStyle: TextStyle(
color: Colors.white.withOpacity(0.3),
letterSpacing: 18,
fontSize: 28),
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(vertical: 10),
),
validator: (v) => v == null || v.length < 5 ? '' : null,
),
),
const SizedBox(height: 30),
_isLoading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: _submit,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.teal,
foregroundColor: Colors.white,
minimumSize: const Size(double.infinity, 50),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
? const CircularProgressIndicator(color: Colors.white)
: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _submit,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF00BFFF),
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
),
child: Text(
'verify and continue button'.tr,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.black),
),
),
child: Text('verify and continue button'.tr),
),
],
),
@@ -424,6 +511,7 @@ class _RegistrationScreenState extends State<RegistrationScreen> {
void _submit() async {
if (_formKey.currentState!.validate()) {
setState(() => _isLoading = true);
// PRODUCTION READY: Using the actual PhoneAuthHelper
await PhoneAuthHelper.registerUser(
phoneNumber: widget.phoneNumber,
firstName: _firstNameController.text.trim(),
@@ -434,6 +522,33 @@ class _RegistrationScreenState extends State<RegistrationScreen> {
}
}
// Helper to create styled text form fields
Widget _buildTextFormField({
required TextEditingController controller,
required String label,
TextInputType keyboardType = TextInputType.text,
String? Function(String?)? validator,
}) {
return TextFormField(
controller: controller,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: label,
labelStyle: TextStyle(color: Colors.white.withOpacity(0.7)),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: Colors.white.withOpacity(0.3)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide(color: Color(0xFF00BFFF)),
),
),
keyboardType: keyboardType,
validator: validator,
);
}
@override
Widget build(BuildContext context) {
return AuthScreen(
@@ -444,45 +559,44 @@ class _RegistrationScreenState extends State<RegistrationScreen> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
_buildTextFormField(
controller: _firstNameController,
decoration: InputDecoration(
labelText: 'first name label'.tr,
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12)))),
label: 'first name label'.tr,
validator: (v) => v!.isEmpty ? 'first name required'.tr : null,
),
const SizedBox(height: 16),
TextFormField(
_buildTextFormField(
controller: _lastNameController,
decoration: InputDecoration(
labelText: 'last name label'.tr,
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12)))),
label: 'last name label'.tr,
validator: (v) => v!.isEmpty ? 'last name required'.tr : null,
),
const SizedBox(height: 16),
TextFormField(
_buildTextFormField(
controller: _emailController,
decoration: InputDecoration(
labelText: 'email optional label'.tr,
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12)))),
label: 'email optional label'.tr,
keyboardType: TextInputType.emailAddress,
),
const SizedBox(height: 24),
_isLoading
? const CircularProgressIndicator()
: ElevatedButton(
onPressed: _submit,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.teal,
foregroundColor: Colors.white,
minimumSize: const Size(double.infinity, 50),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
? const CircularProgressIndicator(color: Colors.white)
: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _submit,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF00BFFF),
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
),
child: Text(
'complete registration button'.tr,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.black),
),
),
child: Text('complete registration button'.tr),
),
],
),

View File

@@ -25,7 +25,7 @@ class _OtpVerificationPageState extends State<OtpVerificationPage> {
late final OtpVerificationController controller;
final List<FocusNode> _focusNodes = List.generate(6, (index) => FocusNode());
final List<TextEditingController> _textControllers =
List.generate(6, (index) => TextEditingController());
List.generate(5, (index) => TextEditingController());
@override
void initState() {

View File

@@ -6,11 +6,9 @@ import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'dart:ui'; // مهم لإضافة تأثير الضبابية
import '../../../constant/colors.dart';
import '../../../controller/auth/login_controller.dart';
import '../../../controller/functions/tts.dart';
import '../../../controller/home/map_passenger_controller.dart';
import '../../../controller/home/vip_waitting_page.dart';
import '../../auth/otp_page.dart';
// --- الدالة الرئيسية بالتصميم الجديد ---
GetBuilder<MapPassengerController> leftMainMenuIcons() {
@@ -128,24 +126,7 @@ class TestPage extends StatelessWidget {
appBar: AppBar(),
body: Center(
child: TextButton(
onPressed: () async {
Get.put(LoginController());
Get.to(() => PhoneNumberScreen());
// firebaseMessagesController.sendNotificationToDriverMAP(
// 'title',
// DateTime.now().toString(),
// 'ffX7xVXpdE_Xq8JBH3lgS4:APA91bGBHp53E-ZuXdlLBpRZohzqR9sazqcn3pwpEDG7JxkVi9MBtFDlCipzLpPCvD6LHEtds88ugGyCty7pEJVyx6tQYvzHVDCh7l3_7axpyriTBs5iv9E',
// [],
// '');
// Get.to(
// () => OtpVerificationPage(
// phone: '963992952235',
// deviceToken: 'abcdefg123456789',
// token: 'passengerToken123',
// ptoken: 'passengerToken456',
// ),
// );
},
onPressed: () async {},
child: Text(
"Text Button",
),

View File

@@ -7,10 +7,12 @@ import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/constant/colors.dart';
import 'package:Intaleq/controller/functions/toast.dart';
import 'package:Intaleq/controller/payment/payment_controller.dart';
import 'package:local_auth/local_auth.dart';
import '../../../main.dart';
import '../../widgets/elevated_btn.dart';
import '../../widgets/my_textField.dart';
import 'payment_screen_sham.dart';
class PassengerWalletDialog extends StatelessWidget {
const PassengerWalletDialog({
@@ -32,52 +34,52 @@ class PassengerWalletDialog extends StatelessWidget {
CupertinoActionSheetAction(
onPressed: () {
controller.updateSelectedAmount(
box.read(BoxName.countryCode) == 'Syria' ? 1000 : 10,
box.read(BoxName.countryCode) == 'Syria' ? 10000 : 10,
);
showPaymentOptions(context, controller);
},
child: Text(
box.read(BoxName.countryCode) == 'Syria'
? '1000 ${'LE'.tr}'
? '10000 ${'LE'.tr}'
: '10 ${'SYP'.tr}',
),
),
CupertinoActionSheetAction(
onPressed: () {
controller.updateSelectedAmount(
box.read(BoxName.countryCode) == 'Syria' ? 2000 : 20,
box.read(BoxName.countryCode) == 'Syria' ? 20000 : 20,
);
showPaymentOptions(context, controller);
},
child: Text(
box.read(BoxName.countryCode) == 'Syria'
? '2000 ${'LE'.tr} = 2050 ${'LE'.tr}'
? '20000 ${'LE'.tr} = 2050 ${'LE'.tr}'
: '20 ${'SYP'.tr}',
),
),
CupertinoActionSheetAction(
onPressed: () {
controller.updateSelectedAmount(
box.read(BoxName.countryCode) == 'Syria' ? 4000 : 40,
box.read(BoxName.countryCode) == 'Syria' ? 40000 : 40,
);
showPaymentOptions(context, controller);
},
child: Text(
box.read(BoxName.countryCode) == 'Syria'
? '4000 ${'LE'.tr} = 4150 ${'LE'.tr}'
? '40000 ${'LE'.tr} = 4150 ${'LE'.tr}'
: '40 ${'SYP'.tr}',
),
),
CupertinoActionSheetAction(
onPressed: () {
controller.updateSelectedAmount(
box.read(BoxName.countryCode) == 'Syria' ? 1000 : 50,
box.read(BoxName.countryCode) == 'Syria' ? 100000 : 50,
);
showPaymentOptions(context, controller);
},
child: Text(
box.read(BoxName.countryCode) == 'Syria'
? '10000 ${'LE'.tr} = 11000 ${'LE'.tr}'
? '100000 ${'LE'.tr} = 11000 ${'LE'.tr}'
: '50 ${'SYP'.tr}',
),
),
@@ -149,7 +151,7 @@ void showPaymentBottomSheet(BuildContext context) {
_buildPaymentOption(
context: context,
controller: controller,
amount: 100000,
amount: 10000,
bonusAmount: 0,
currency: 'SYP'.tr,
),
@@ -158,8 +160,8 @@ void showPaymentBottomSheet(BuildContext context) {
_buildPaymentOption(
context: context,
controller: controller,
amount: 200000,
bonusAmount: 5000,
amount: 20000,
bonusAmount: 500,
currency: 'SYP'.tr,
),
@@ -167,8 +169,8 @@ void showPaymentBottomSheet(BuildContext context) {
_buildPaymentOption(
context: context,
controller: controller,
amount: 400000,
bonusAmount: 25000,
amount: 40000,
bonusAmount: 2500,
currency: 'SYP'.tr,
),
@@ -176,8 +178,8 @@ void showPaymentBottomSheet(BuildContext context) {
_buildPaymentOption(
context: context,
controller: controller,
amount: 1000000,
bonusAmount: 40000,
amount: 100000,
bonusAmount: 4000,
currency: 'SYP'.tr,
),
@@ -442,6 +444,67 @@ void showPaymentOptions(BuildContext context, PaymentController controller) {
],
),
)),
GestureDetector(
onTap: () async {
Get.back();
Get.defaultDialog(
barrierDismissible: false,
title: 'Insert Wallet phone number'.tr,
content: Form(
key: controller.formKey,
child: MyTextForm(
controller: controller.walletphoneController,
label: 'Insert Wallet phone number'.tr,
hint: '963941234567',
type: TextInputType.phone)),
confirm: MyElevatedButton(
title: 'OK'.tr,
onPressed: () async {
Get.back();
if (controller.formKey.currentState!.validate()) {
box.write(BoxName.phoneWallet,
controller.walletphoneController.text);
// await payWithSyriaTelWallet(
// context, pricePoint.toString(), 'SYP');
bool isAuthSupported =
await LocalAuthentication().isDeviceSupported();
if (isAuthSupported) {
bool didAuthenticate =
await LocalAuthentication().authenticate(
localizedReason:
'استخدم بصمة الإصبع أو الوجه لتأكيد الدفع',
);
if (!didAuthenticate) {
if (Get.isDialogOpen ?? false) Get.back();
print(
"❌ User did not authenticate with biometrics");
return;
}
}
Get.to(() => PaymentScreenSmsProvider(
amount: controller.selectedAmount!.toDouble()));
}
}));
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Pay by Sham Cash'.tr,
style: AppStyle.title,
),
const SizedBox(width: 10),
Image.asset(
'assets/images/shamCash.png',
width: 70,
height: 70,
fit: BoxFit.fill,
),
],
),
)),
],
cancelButton: CupertinoActionSheetAction(
child: Text('Cancel'.tr),

View File

@@ -0,0 +1,402 @@
import 'dart:async';
import 'package:Intaleq/views/widgets/mydialoug.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:intl/intl.dart';
import '../../../constant/box_name.dart';
import '../../../constant/links.dart';
import '../../../controller/functions/crud.dart';
import '../../../main.dart';
class PaymentService {
final String _baseUrl = "${AppLink.seferPaymentServer}/sms_webhook";
Future<String?> createInvoice({
required String userPhone,
required double amount,
}) async {
final url = "$_baseUrl/create_invoice_passenger.php";
try {
final response = await CRUD().postWallet(
link: url,
payload: {
'user_phone': userPhone.toString(),
'passengerID': box.read(BoxName.passengerID),
'amount': amount.toString(),
},
).timeout(const Duration(seconds: 15)); // إضافة مهلة للطلب
if (response != 'failure') {
final data = (response);
if (data['status'] == 'success' && data['invoice_number'] != null) {
debugPrint(
"تم إنشاء الفاتورة بنجاح. الرقم: ${data['invoice_number']}");
return data['invoice_number'].toString();
} else {
debugPrint("فشل في إنشاء الفاتورة من السيرفر: ${data['message']}");
return null;
}
} else {
debugPrint("خطأ في السيرفر عند إنشاء الفاتورة: ${response.statusCode}");
return null;
}
} catch (e) {
debugPrint("حدث استثناء عند إنشاء الفاتورة: $e");
return null;
}
}
/// دالة للتحقق من حالة فاتورة واحدة
Future<bool> checkInvoiceStatus(String invoiceNumber) async {
final url = "$_baseUrl/check_invoice_status_passenger.php";
try {
final response = await CRUD().postWallet(link: url, payload: {
'invoice_number': invoiceNumber,
}).timeout(const Duration(seconds: 10)); // مهلة للشبكة
if (response != 'failure') {
final data = (response);
return data['status'] == 'success' &&
data['invoice_status'] == 'completed';
}
return false;
} catch (e) {
debugPrint("خطأ أثناء التحقق من الفاتورة: $e");
return false;
}
}
}
enum PaymentStatus {
creatingInvoice,
waitingForPayment,
paymentSuccess,
paymentTimeout,
paymentError
}
class PaymentScreenSmsProvider extends StatefulWidget {
final double amount;
final String providerName;
final String providerLogo;
final String paymentPhoneNumber;
const PaymentScreenSmsProvider({
super.key,
required this.amount,
this.providerName = 'شام كاش',
this.providerLogo = 'assets/images/shamCash.png',
this.paymentPhoneNumber = '963942542053',
});
@override
_PaymentScreenSmsProviderState createState() =>
_PaymentScreenSmsProviderState();
}
class _PaymentScreenSmsProviderState extends State<PaymentScreenSmsProvider> {
final PaymentService _paymentService = PaymentService();
Timer? _pollingTimer;
PaymentStatus _status = PaymentStatus.creatingInvoice;
String? _invoiceNumber;
final String phone = box.read(BoxName.phoneWallet);
@override
void initState() {
super.initState();
_createAndPollInvoice();
}
@override
void dispose() {
_pollingTimer?.cancel(); // مهم جداً: إلغاء المؤقت عند الخروج من الشاشة
super.dispose();
}
void _createAndPollInvoice() async {
setState(() => _status = PaymentStatus.creatingInvoice);
final invoiceNumber = await _paymentService.createInvoice(
userPhone: phone,
amount: widget.amount,
);
if (invoiceNumber != null && mounted) {
setState(() {
_invoiceNumber = invoiceNumber;
_status = PaymentStatus.waitingForPayment;
});
_startPolling(invoiceNumber);
} else if (mounted) {
setState(() => _status = PaymentStatus.paymentError);
}
}
void _startPolling(String invoiceNumber) {
const timeoutDuration = Duration(minutes: 3);
var elapsed = Duration.zero;
_pollingTimer = Timer.periodic(const Duration(seconds: 5), (timer) async {
elapsed += const Duration(seconds: 5);
if (elapsed >= timeoutDuration) {
timer.cancel();
if (mounted) setState(() => _status = PaymentStatus.paymentTimeout);
return;
}
debugPrint("Polling... Checking invoice status for: $invoiceNumber");
final isCompleted =
await _paymentService.checkInvoiceStatus(invoiceNumber);
if (isCompleted && mounted) {
timer.cancel();
setState(() => _status = PaymentStatus.paymentSuccess);
// TODO: تحديث رصيد المستخدم أو تنفيذ الإجراءات اللازمة
MyDialog().getDialog(
'Payment Successful!'.tr,
''.tr,
() {
Get.back();
Get.back();
},
);
}
});
}
/// دالة جديدة لمعالجة محاولة الرجوع للخلف
void _onPopInvoked(bool didPop) async {
// إذا كان الرجوع قد تم بالفعل (مثلاً من خلال Navigator.pop)، لا تفعل شيئاً
if (didPop) return;
// إذا كان المستخدم ينتظر الدفع، أظهر له حوار التأكيد
if (_status == PaymentStatus.waitingForPayment) {
final shouldPop = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('هل أنت متأكد؟'),
content: const Text('إذا خرجت الآن، سيتم إلغاء عملية الدفع الحالية.'),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('البقاء'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('الخروج'),
),
],
),
);
// إذا وافق المستخدم على الخروج، قم بإغلاق الشاشة
if (shouldPop ?? false) {
Navigator.of(context).pop();
}
}
}
@override
Widget build(BuildContext context) {
// استخدام PopScope بدلاً من WillPopScope
return PopScope(
// منع الرجوع التلقائي فقط في حالة انتظار الدفع
canPop: _status != PaymentStatus.waitingForPayment,
// استدعاء دالة التحقق عند محاولة الرجوع
onPopInvoked: _onPopInvoked,
child: Scaffold(
appBar: AppBar(title: Text("الدفع عبر ${widget.providerName}")),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Center(
child: _buildContentByStatus(),
),
),
),
);
}
Widget _buildContentByStatus() {
switch (_status) {
case PaymentStatus.creatingInvoice:
return const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
SizedBox(height: 20),
Text("جاري إنشاء فاتورة الدفع...", style: TextStyle(fontSize: 16)),
],
);
case PaymentStatus.waitingForPayment:
return _buildWaitingForPaymentUI();
case PaymentStatus.paymentSuccess:
return _buildSuccessUI();
case PaymentStatus.paymentTimeout:
case PaymentStatus.paymentError:
return _buildErrorUI();
}
}
Widget _buildWaitingForPaymentUI() {
final currencyFormat = NumberFormat.decimalPattern('ar_SY');
final invoiceText = _invoiceNumber ?? '------';
return SingleChildScrollView(
child: Column(
children: [
Image.asset(widget.providerLogo, width: 96),
const SizedBox(height: 16),
Text("تعليمات الدفع", style: Theme.of(context).textTheme.titleLarge),
const SizedBox(height: 12),
Card(
elevation: 1.5,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_StepTile(number: 1, text: "افتح تطبيق محفظتك الإلكترونية."),
_StepTile(number: 2, text: "اختر خدمة تحويل الأموال."),
_StepTile(
number: 3,
text:
"أدخل المبلغ المطلوب: ${currencyFormat.format(widget.amount)} ل.س"),
_StepTile(number: 4, text: "حوّل إلى الرقم التالي:"),
// --- التعديل هنا ---
ListTile(
contentPadding: EdgeInsets.zero,
title: Text(
widget.paymentPhoneNumber,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
letterSpacing: 1.2),
),
trailing: OutlinedButton.icon(
onPressed: () async {
await Clipboard.setData(
ClipboardData(text: widget.paymentPhoneNumber));
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("تم نسخ رقم الهاتف")));
}
},
icon: const Icon(Icons.copy, size: 18),
label: const Text("نسخ"),
),
),
// --- نهاية التعديل ---
const SizedBox(height: 8),
_StepTile(
number: 5,
text: "هام: انسخ رقم القسيمة والصقه في خانة \"البيان\"."),
ListTile(
contentPadding: EdgeInsets.zero,
title: Text(invoiceText,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
letterSpacing: 1.5)),
trailing: OutlinedButton.icon(
onPressed: _invoiceNumber == null
? null
: () async {
await Clipboard.setData(
ClipboardData(text: invoiceText));
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("تم نسخ رقم القسيمة")));
}
},
icon: const Icon(Icons.copy, size: 18),
label: const Text("نسخ"),
),
),
],
),
),
),
const SizedBox(height: 20),
const LinearProgressIndicator(minHeight: 2),
const SizedBox(height: 12),
Text("بانتظار تأكيد الدفع...",
style: TextStyle(color: Colors.grey.shade700)),
const SizedBox(height: 4),
const Text("هذه الشاشة ستتحدث تلقائيًا",
style: TextStyle(color: Colors.grey)),
],
),
);
}
Widget _buildSuccessUI() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.check_circle, color: Colors.green, size: 80),
const SizedBox(height: 20),
const Text("تم الدفع بنجاح!",
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text("العودة"),
),
],
);
}
Widget _buildErrorUI() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error, color: Colors.red, size: 80),
const SizedBox(height: 20),
Text(
_status == PaymentStatus.paymentTimeout
? "انتهى الوقت المحدد للدفع"
: "حدث خطأ ما",
style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
const Text("يرجى المحاولة مرة أخرى.", style: TextStyle(fontSize: 16)),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _createAndPollInvoice,
child: const Text("المحاولة مرة أخرى"),
),
],
);
}
}
// ويدجت مساعد لعرض خطوات التعليمات بشكل أنيق
class _StepTile extends StatelessWidget {
final int number;
final String text;
const _StepTile({required this.number, required this.text});
@override
Widget build(BuildContext context) {
return ListTile(
contentPadding: EdgeInsets.zero,
leading: CircleAvatar(
radius: 12,
backgroundColor: Theme.of(context).primaryColor,
child: Text("$number",
style: const TextStyle(
fontSize: 12,
color: Colors.white,
fontWeight: FontWeight.bold)),
),
title: Text(text),
);
}
}