diff --git a/.env b/.env
index a5bc609..5443e66 100644
--- a/.env
+++ b/.env
@@ -5,6 +5,7 @@ accountSIDTwillo=QFx0qy456juj3839xuy2194q629q1fj0y7XrXlBl
serverAPI=QQQQobSrrFi:QVQ87xU7zwCvmZzZdaxuS2f23Y4mz7MzyOzr8od2br6KYyeFaTVLG3K3hx5ZaUyx7eYvAYpAVdKk-286NTRi3zs9iSOnXtXRIxswg3KecBmsl3VxJ9wO-vIpwu4Pv7dkHkXniuxMSDgWXrXlBl
mapAPIKEY=QOmqZsFsutLDCtZCRIUAZAkB5v6AMkKEPMbJGa3XrXlBl
twilloRecoveryCode=CAU79DHPH1BE9PUH4ETXTSXZXrXlBl
+apiKeyHere=g_WNUb5L-7-F8oHpUmgIzH7ETeH9xZ8RwGG9_G8zX9A
authTokenTwillo=70u98ju0214xx4q0u74028u021u4qu65XrXlBl
chatGPTkey=zg-4C26q4SYBKQeHZDqkWowC9XrxgUEfUy9JRw2rm6Q2adb3kjwXrXlBl
transactionCloude=Qhcwilomqcoib:QVO_JNYED2XWA26YXKC2TP:YK1DVH6SJB31N3PE1UXrXlBl
diff --git a/android/app/build.gradle b/android/app/build.gradle
index 2d432ec..de3907d 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -148,8 +148,8 @@ android {
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
minSdk = 23
targetSdk = flutter.targetSdkVersion
- versionCode = 99
- versionName = '1.5.99'
+ versionCode = 106
+ versionName = '1.6.106'
multiDexEnabled =true
// manifestPlaceholders can be specified here if needed
diff --git a/assets/images/car3.png b/assets/images/car3.png
new file mode 100644
index 0000000..41627ae
Binary files /dev/null and b/assets/images/car3.png differ
diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist
index 3513e88..6a85ad6 100644
--- a/ios/Runner/Info.plist
+++ b/ios/Runner/Info.plist
@@ -41,11 +41,11 @@
CFBundlePackageType
APPL
CFBundleShortVersionString
- 71
+ 77
CFBundleSignature
????
CFBundleVersion
- 4.3.71
+ 4.3.77
NSHumanReadableCopyright
FirebaseAppDelegateProxyEnabled
diff --git a/lib/constant/api_key.dart b/lib/constant/api_key.dart
index 6433459..f0e2f77 100644
--- a/lib/constant/api_key.dart
+++ b/lib/constant/api_key.dart
@@ -51,6 +51,7 @@ class AK {
X.r(X.r(X.r(Env.payMobApikey, cn), cC), cs);
static final String integrationIdPayMobWallet =
X.r(X.r(X.r(Env.integrationIdPayMobWallet, cn), cC), cs);
+ static final String apiKeyHere = Env.apiKeyHere;
static final String smsPasswordEgypt =
X.r(X.r(X.r(Env.smsPasswordEgypt, cn), cC), cs);
static final String ocpApimSubscriptionKey = Env.ocpApimSubscriptionKey;
diff --git a/lib/constant/box_name.dart b/lib/constant/box_name.dart
index 0113597..e2fbaa7 100644
--- a/lib/constant/box_name.dart
+++ b/lib/constant/box_name.dart
@@ -24,6 +24,7 @@ class BoxName {
static const String agreeTerms = "agreeTerms";
static const String addWork = 'addWork';
static const String addHome = 'addHome';
+ static const String placesDestination = 'placesDestination';
static const String tipPercentage = 'tipPercentage';
static const String accountIdStripeConnect = "accountIdStripeConnect";
static const String faceDetectTimes = "faceDetectTimes";
diff --git a/lib/constant/links.dart b/lib/constant/links.dart
index d823265..bb2c553 100644
--- a/lib/constant/links.dart
+++ b/lib/constant/links.dart
@@ -14,6 +14,8 @@ class AppLink {
// static final String server = Env.serverPHP;
static String googleMapsLink = 'https://maps.googleapis.com/maps/api/';
+ static String searcMaps =
+ 'https://autosuggest.search.hereapi.com/v1/autosuggest';
static String llama = 'https://api.llama-api.com/chat/completions';
static String gemini =
'https://generativelanguage.googleapis.com/v1beta3/models/text-bison-001:generateText';
@@ -185,6 +187,8 @@ class AppLink {
// =====================================
static String addRateToPassenger = "$ride/rate/add.php";
+ static String savePlacesServer = "$ride/places/add.php";
+ static String getapiKey = "$ride/apiKey/get.php";
static String addRateToDriver = "$ride/rate/addRateToDriver.php";
static String getDriverRate = "$ride/rate/getDriverRate.php";
static String getPassengerRate = "$ride/rate/getPassengerRate.php";
@@ -265,6 +269,8 @@ class AppLink {
static String getAccount = "$authCaptin/getAccount.php";
static String updatePassengersInvitation =
"$server/ride/invitor/updatePassengersInvitation.php";
+ static String updateDriverInvitationDirectly =
+ "$server/ride/invitor/updateDriverInvitationDirectly.php";
//===================Admin Captin============
static String getPassengerDetailsByPassengerID =
diff --git a/lib/constant/style.dart b/lib/constant/style.dart
index 10975c7..a0993aa 100644
--- a/lib/constant/style.dart
+++ b/lib/constant/style.dart
@@ -5,35 +5,39 @@ import 'package:google_fonts/google_fonts.dart';
import 'colors.dart';
class AppStyle {
- static TextStyle headTitle = TextStyle(
- fontWeight: FontWeight.bold,
- fontSize: 40,
- color: AppColor.accentColor,
- fontFamily: box.read(BoxName.lang) == 'ar'
- // ?GoogleFonts.notoNaskhArabic().fontFamily
- ? GoogleFonts.notoNaskhArabic().fontFamily
- : GoogleFonts.roboto().fontFamily);
- static TextStyle headTitle2 = TextStyle(
- fontWeight: FontWeight.bold,
- fontSize: 26,
- color: AppColor.writeColor,
- fontFamily: box.read(BoxName.lang) == 'ar'
- ? GoogleFonts.notoNaskhArabic().fontFamily
- : GoogleFonts.roboto().fontFamily);
+ static TextStyle headTitle = const TextStyle(
+ fontWeight: FontWeight.bold,
+ fontSize: 40,
+ color: AppColor.accentColor,
+ // fontFamily: box.read(BoxName.lang) == 'ar'
+ // // ?GoogleFonts.notoNaskhArabic().fontFamily
+ // ? GoogleFonts.notoNaskhArabic().fontFamily
+ // : GoogleFonts.roboto().fontFamily,
+ );
+ static TextStyle headTitle2 = const TextStyle(
+ fontWeight: FontWeight.bold,
+ fontSize: 22,
+ color: AppColor.writeColor,
+ // fontFamily: box.read(BoxName.lang) == 'ar'
+ // ? GoogleFonts.notoNaskhArabic().fontFamily
+ // : GoogleFonts.roboto().fontFamily
+ );
static TextStyle title = TextStyle(
- fontWeight: FontWeight.normal,
- fontSize: box.read(BoxName.lang) == 'ar' ? 14 : 16,
- color: AppColor.writeColor,
- fontFamily: box.read(BoxName.lang) == 'ar'
- ? GoogleFonts.notoNaskhArabic().fontFamily
- : GoogleFonts.roboto().fontFamily);
- static TextStyle subtitle = TextStyle(
- fontWeight: FontWeight.bold,
- fontSize: 13,
- color: AppColor.writeColor,
- fontFamily: box.read(BoxName.lang) == 'ar'
- ? GoogleFonts.notoNaskhArabic().fontFamily
- : GoogleFonts.roboto().fontFamily);
+ fontWeight: FontWeight.normal,
+ fontSize: box.read(BoxName.lang) == 'ar' ? 14 : 16,
+ color: AppColor.writeColor,
+ // fontFamily: box.read(BoxName.lang) == 'ar'
+ // ? GoogleFonts.notoNaskhArabic().fontFamily
+ // : GoogleFonts.roboto().fontFamily
+ );
+ static TextStyle subtitle = const TextStyle(
+ fontWeight: FontWeight.bold,
+ fontSize: 13,
+ color: AppColor.writeColor,
+ // fontFamily: box.read(BoxName.lang) == 'ar'
+ // ? GoogleFonts.notoNaskhArabic().fontFamily
+ // : GoogleFonts.roboto().fontFamily
+ );
static TextStyle number = const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14,
diff --git a/lib/controller/auth/register_controller.dart b/lib/controller/auth/register_controller.dart
index 2cd19d4..d01ceee 100644
--- a/lib/controller/auth/register_controller.dart
+++ b/lib/controller/auth/register_controller.dart
@@ -166,7 +166,7 @@ class RegisterController extends GetxController {
await sendOtp(phoneNumber, randomNumber, isEgyptianNumber,
smsEgyptController);
}
- } else {
+ } else if (phoneNumber.length > 9) {
sendOtp(
phoneNumber, randomNumber, isEgyptianNumber, smsEgyptController);
}
@@ -191,12 +191,57 @@ class RegisterController extends GetxController {
SmsEgyptController controller) async {
// Trim any leading or trailing whitespace from the phone number
phoneNumber = phoneNumber.trim();
- await CRUD().post(link: AppLink.sendVerifyOtpMessage, payload: {
+ var dd = await CRUD().post(link: AppLink.sendVerifyOtpMessage, payload: {
'phone_number': phoneNumber,
'token': otp.toString(),
});
+ Log.print('dd: ${dd}');
if (isEgyptian) {
- await controller.sendSmsEgypt(phoneNumber, otp.toString());
+ await CRUD().post(link: AppLink.updatePhoneInvalidSMSPassenger, payload: {
+ "phone_number": Get.find().phoneController.text
+ });
+ box.write(BoxName.phoneDriver, phoneController.text);
+ var nameParts = box.read(BoxName.name).toString().split(' ');
+ var firstName = nameParts.isNotEmpty ? nameParts[0] : 'unknown';
+ var lastName = nameParts.length > 1 ? nameParts[1] : 'unknown';
+
+ var payload = {
+ 'id': box.read(BoxName.passengerID),
+ 'phone': phoneController.text,
+ 'email': box.read(BoxName.email),
+ 'password': 'unknown',
+ 'gender': 'unknown',
+ 'birthdate': '2002-01-01',
+ 'site': box.read(BoxName.passengerPhotoUrl) ?? 'unknown',
+ 'first_name': firstName,
+ 'last_name': lastName,
+ };
+
+ var res1 = await CRUD().post(
+ link: AppLink.signUp,
+ payload: payload,
+ );
+
+ if (res1 != 'failure') {
+ await CRUD().post(
+ link: '${AppLink.seferAlexandriaServer}/auth/signup.php',
+ payload: payload,
+ );
+ await CRUD().post(
+ link: '${AppLink.seferGizaServer}/auth/signup.php',
+ payload: payload,
+ );
+
+ box.write(BoxName.isVerified, '1');
+ box.write(BoxName.isFirstTime, '0');
+ box.write(BoxName.phone, phoneController.text);
+
+ Get.put(LoginController()).loginUsingCredentials(
+ box.read(BoxName.passengerID).toString(),
+ box.read(BoxName.email).toString(),
+ );
+ }
+ // await controller.sendSmsEgypt(phoneNumber, otp.toString());
} else {
await CRUD().sendWhatsAppAuth(phoneNumber, otp.toString());
}
diff --git a/lib/controller/firebase/firbase_messge.dart b/lib/controller/firebase/firbase_messge.dart
index 814766d..334f19c 100644
--- a/lib/controller/firebase/firbase_messge.dart
+++ b/lib/controller/firebase/firbase_messge.dart
@@ -214,7 +214,7 @@ class FirebaseMessagesController extends GetxController {
driverArrivePassengerDialoge();
update();
- } else if (message.notification!.title! == "Cancel Trip from driver".tr) {
+ } else if (message.notification!.title! == "Cancel Trip from driver") {
Get.back();
if (Platform.isAndroid) {
notificationController.showNotification("Cancel Trip from driver".tr,
@@ -243,7 +243,7 @@ class FirebaseMessagesController extends GetxController {
// .searchNewDriverAfterRejectingFromDriver();
);
} else if (message.notification!.title! == 'Driver Finish Trip'.tr) {
- var myListString = message.data['passengerList'];
+ var myListString = message.data['DriverList'];
var driverList = jsonDecode(myListString) as List;
if (Platform.isAndroid) {
notificationController.showNotification(
@@ -262,6 +262,11 @@ class FirebaseMessagesController extends GetxController {
'rideId': driverList[1].toString(),
'price': driverList[3].toString()
});
+ notificationController.showNotification(
+ 'Don’t forget your personal belongings.'.tr,
+ 'Please make sure you have all your personal belongings and that any remaining fare, if applicable, has been added to your wallet before leaving. Thank you for choosing the Sefer app'
+ .tr,
+ 'ding');
// }
} else if (message.notification!.title! == "Finish Monitor".tr) {
Get.defaultDialog(
diff --git a/lib/controller/firebase/local_notification.dart b/lib/controller/firebase/local_notification.dart
index 73ba3ff..44f7b31 100644
--- a/lib/controller/firebase/local_notification.dart
+++ b/lib/controller/firebase/local_notification.dart
@@ -99,7 +99,7 @@ class NotificationController extends GetxController {
for (int day = 0; day < 7; day++) {
// Schedule for 8:00 AM
await _scheduleNotificationForTime(
- day, 8, 0, title, message, details, day * 1000 + 1); // Unique ID
+ day, 8, 0, title, message, details, day * 1000 + 1);
// Schedule for 3:00 PM
await _scheduleNotificationForTime(
diff --git a/lib/controller/functions/crud.dart b/lib/controller/functions/crud.dart
index 96995b0..91f3047 100644
--- a/lib/controller/functions/crud.dart
+++ b/lib/controller/functions/crud.dart
@@ -509,6 +509,26 @@ class CRUD {
return (jsonData['status']);
}
+ Future getHereMap({
+ required String link,
+ }) async {
+ var url = Uri.parse(link);
+ try {
+ var response = await http.get(url);
+
+ if (response.statusCode == 200) {
+ // Ensure the response body is decoded as UTF-8
+ var decodedBody = utf8.decode(response.bodyBytes);
+ var data = jsonDecode(decodedBody);
+ return data;
+ } else {
+ return null;
+ }
+ } catch (e) {
+ return null;
+ }
+ }
+
Future update({
required String endpoint,
required Map data,
diff --git a/lib/controller/functions/sms_controller.dart b/lib/controller/functions/sms_controller.dart
index 53e3422..09b0b63 100644
--- a/lib/controller/functions/sms_controller.dart
+++ b/lib/controller/functions/sms_controller.dart
@@ -11,6 +11,7 @@ import 'package:SEFER/views/widgets/elevated_btn.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
+import '../../print.dart';
import '../auth/register_controller.dart';
import 'crud.dart';
diff --git a/lib/controller/home/map_passenger_controller.dart b/lib/controller/home/map_passenger_controller.dart
index f786103..3f825d3 100644
--- a/lib/controller/home/map_passenger_controller.dart
+++ b/lib/controller/home/map_passenger_controller.dart
@@ -403,8 +403,10 @@ class MapPassengerController extends GetxController {
}
tick = 0;
}
- await getCarForFirstConfirm(box.read(BoxName.carType));
+ await getCarsLocationByPassengerAndReloadMarker(
+ box.read(BoxName.carType), 4000);
// confirmRideForAllDriverAvailable();
+
icreaseForSameRideAndDelay();
}
}
@@ -471,9 +473,12 @@ class MapPassengerController extends GetxController {
hintTextDestinationPoint = 'Search for your destination'.tr;
update();
} else {
- hintTextDestinationPoint = placesDestination[index]['name'];
- double lat = placesDestination[index]['geometry']['location']['lat'];
- double lng = placesDestination[index]['geometry']['location']['lng'];
+ hintTextDestinationPoint = placesDestination[index]['title'];
+ // hintTextDestinationPoint = placesDestination[index]['name'];
+ // double lat = placesDestination[index]['geometry']['location']['lat'];
+ double lat = placesDestination[index]['position']['lat'];
+ double lng = placesDestination[index]['position']['lng'];
+ // double lng = placesDestination[index]['geometry']['location']['lng'];
newMyLocation = LatLng(lat, lng);
update();
@@ -541,7 +546,7 @@ class MapPassengerController extends GetxController {
// Format the message.
String message =
- 'Hi! This is ${box.read(BoxName.name)}.\n I am using ${box.read(AppInformation.appName)} to ride with $firstName as the driver. $firstName \nis driving a $model\n with license plate $licensePlate.\n I am currently located at $passengerLocation.\n If you need to reach me, please contact the driver directly at\n\n $driverPhone.';
+ 'Hi! This is ${box.read(BoxName.name)}.\n I am using ${box.read(AppInformation.appName)} to ride with $passengerName as the driver. $passengerName \nis driving a $model\n with license plate $licensePlate.\n I am currently located at $passengerLocation.\n If you need to reach me, please contact the driver directly at\n\n $driverPhone.';
// Launch the URL to send the SMS.
launchCommunication('sms', to, message);
@@ -553,7 +558,7 @@ class MapPassengerController extends GetxController {
// Format the message.
String message =
- '${'${'Hi! This is'.tr} ${box.read(BoxName.name)}.\n${' I am using'.tr}'} ${AppInformation.appName}${' to ride with'.tr} $firstName${' as the driver.'.tr} $firstName \n${'is driving a '.tr}$model\n${' with license plate '.tr}$licensePlate.\n${' I am currently located at '.tr} https://www.google.com/maps/place/${passengerLocation.latitude},${passengerLocation.longitude}.\n${' If you need to reach me, please contact the driver directly at'.tr}\n\n $driverPhone.';
+ '${'${'Hi! This is'.tr} ${box.read(BoxName.name)}.\n${' I am using'.tr}'} ${AppInformation.appName}${' to ride with'.tr} $passengerName${' as the driver.'.tr} $passengerName \n${'is driving a '.tr}$model\n${' with license plate '.tr}$licensePlate.\n${' I am currently located at '.tr} https://www.google.com/maps/place/${passengerLocation.latitude},${passengerLocation.longitude}.\n${' If you need to reach me, please contact the driver directly at'.tr}\n\n $driverPhone.';
// Launch the URL to send the WhatsApp message.
launchCommunication('whatsapp', to, message);
@@ -585,44 +590,134 @@ class MapPassengerController extends GetxController {
return distance2;
}
+ // bool isTimerFromDriverToPassengerAfterAppliedRunning = true;
+ // int beginRideInterval = 4; // Interval in seconds for getBeginRideFromDriver
+
+ // void startTimerFromDriverToPassengerAfterApplied() async {
+ // int secondsElapsed = 0;
+
+ // while (secondsElapsed <= timeToPassengerFromDriverAfterApplied &&
+ // isTimerFromDriverToPassengerAfterAppliedRunning) {
+ // await Future.delayed(const Duration(seconds: 1));
+ // secondsElapsed++;
+
+ // progressTimerToPassengerFromDriverAfterApplied =
+ // secondsElapsed / timeToPassengerFromDriverAfterApplied;
+ // remainingTimeToPassengerFromDriverAfterApplied =
+ // timeToPassengerFromDriverAfterApplied - secondsElapsed;
+
+ // if (remainingTimeToPassengerFromDriverAfterApplied < 59) {
+ // if (rideTimerBegin == false) {
+ // rideTimerBegin = true;
+ // }
+ // }
+
+ // // Call getBeginRideFromDriver every 4 seconds
+ // if (secondsElapsed % beginRideInterval == 0) {
+ // getBeginRideFromDriver();
+ // uploadPassengerLocation();
+ // }
+
+ // int minutes =
+ // (remainingTimeToPassengerFromDriverAfterApplied / 60).floor();
+ // int seconds = remainingTimeToPassengerFromDriverAfterApplied % 60;
+ // stringRemainingTimeToPassenger =
+ // '$minutes:${seconds.toString().padLeft(2, '0')}';
+
+ // update();
+ // }
+ // }
+
+ StreamController _timerStreamController = StreamController();
+ Stream get timerStream => _timerStreamController.stream;
bool isTimerFromDriverToPassengerAfterAppliedRunning = true;
+ bool isTimerRunning = false; // Flag to track if the timer is running
int beginRideInterval = 4; // Interval in seconds for getBeginRideFromDriver
- void startTimerFromDriverToPassengerAfterApplied() async {
+ void startTimerFromDriverToPassengerAfterApplied() {
+ if (isTimerRunning) return; // Prevent duplicate streams
+ isTimerRunning = true;
+
int secondsElapsed = 0;
- while (secondsElapsed <= timeToPassengerFromDriverAfterApplied &&
- isTimerFromDriverToPassengerAfterAppliedRunning) {
- await Future.delayed(const Duration(seconds: 1));
- secondsElapsed++;
+ // Start the stream
+ Timer.periodic(const Duration(seconds: 1), (timer) {
+ if (secondsElapsed > timeToPassengerFromDriverAfterApplied ||
+ !isTimerFromDriverToPassengerAfterAppliedRunning) {
+ timer.cancel();
+ isTimerRunning = false;
+ _timerStreamController.close(); // Close the stream when done
+ return;
+ }
+ secondsElapsed++;
+ _timerStreamController.add(secondsElapsed); // Emit elapsed time
+
+ // Calculate progress and remaining time
progressTimerToPassengerFromDriverAfterApplied =
secondsElapsed / timeToPassengerFromDriverAfterApplied;
remainingTimeToPassengerFromDriverAfterApplied =
timeToPassengerFromDriverAfterApplied - secondsElapsed;
- if (remainingTimeToPassengerFromDriverAfterApplied < 59) {
- if (rideTimerBegin == false) {
- rideTimerBegin = true;
- }
- }
-
- // Call getBeginRideFromDriver every 4 seconds
- if (secondsElapsed % beginRideInterval == 0) {
- getBeginRideFromDriver();
- uploadPassengerLocation();
- }
-
+ // Update remaining time as string
int minutes =
(remainingTimeToPassengerFromDriverAfterApplied / 60).floor();
int seconds = remainingTimeToPassengerFromDriverAfterApplied % 60;
stringRemainingTimeToPassenger =
'$minutes:${seconds.toString().padLeft(2, '0')}';
- update();
- }
+ if (remainingTimeToPassengerFromDriverAfterApplied < 59 &&
+ !rideTimerBegin) {
+ rideTimerBegin = true;
+ }
+
+ // Call periodic functions
+ if (secondsElapsed % beginRideInterval == 0) {
+ getBeginRideFromDriver();
+ uploadPassengerLocation();
+ }
+
+ update(); // Notify listeners
+ });
}
+ // void startTimerFromDriverToPassengerAfterApplied() async {
+ // if (isTimerRunning) return; // Exit if timer is already running
+ // isTimerRunning = true; // Set the flag to true
+
+ // int secondsElapsed = 0;
+ // while (secondsElapsed <= timeToPassengerFromDriverAfterApplied &&
+ // isTimerFromDriverToPassengerAfterAppliedRunning) {
+ // await Future.delayed(const Duration(seconds: 1));
+ // secondsElapsed++;
+
+ // progressTimerToPassengerFromDriverAfterApplied =
+ // secondsElapsed / timeToPassengerFromDriverAfterApplied;
+ // remainingTimeToPassengerFromDriverAfterApplied =
+ // timeToPassengerFromDriverAfterApplied - secondsElapsed;
+
+ // if (remainingTimeToPassengerFromDriverAfterApplied < 59) {
+ // if (rideTimerBegin == false) {
+ // rideTimerBegin = true;
+ // }
+ // }
+
+ // // Call getBeginRideFromDriver every 4 seconds
+ // if (secondsElapsed % beginRideInterval == 0) {
+ // getBeginRideFromDriver();
+ // uploadPassengerLocation();
+ // }
+
+ // int minutes =
+ // (remainingTimeToPassengerFromDriverAfterApplied / 60).floor();
+ // int seconds = remainingTimeToPassengerFromDriverAfterApplied % 60;
+ // stringRemainingTimeToPassenger =
+ // '$minutes:${seconds.toString().padLeft(2, '0')}';
+
+ // update();
+ // }
+ // isTimerRunning = false; // Reset the flag when timer completes
+ // }
// Remove the getBeginRideFromDriverForDuration function as it's no longer needed
// Function to stop the timer
@@ -681,8 +776,16 @@ class MapPassengerController extends GetxController {
await Future.delayed(const Duration(seconds: 1));
progressTimerRideBegin = i / durationToRide;
remainingTimeTimerRideBegin = durationToRide - i;
+ if (i == (durationToRide / 4).round() && (statusRide == 'Begin')) {
+ NotificationController().showNotification("Record Your Trip".tr,
+ "You can call or record audio during this trip.".tr, 'tone1');
+ }
bool sendSOS = false;
if (speed > 100 && sendSOS == false) {
+ NotificationController().showNotification(
+ "Warning: Speeding detected!".tr,
+ 'You can call or record audio of this trip'.tr,
+ 'tone1');
Get.defaultDialog(
barrierDismissible: false,
title: "Warning: Speeding detected!".tr,
@@ -702,7 +805,7 @@ class MapPassengerController extends GetxController {
// Get trip details from GetX or relevant provider
String origin = passengerLocation.toString();
String destination = myDestination.toString();
- String driverName = firstName;
+ String driverName = passengerName;
String driverCarPlate = licensePlate;
// Add trip details to the message
@@ -790,7 +893,7 @@ class MapPassengerController extends GetxController {
// Get trip details from GetX or relevant provider
String origin = passengerLocation.toString();
String destination = myDestination.toString();
- String driverName = firstName;
+ String driverName = passengerName;
String driverCarPlate = licensePlate;
// Add trip details to the message
@@ -850,32 +953,96 @@ class MapPassengerController extends GetxController {
update();
}
- void getBeginRideFromDriver() async {
- try {
- var res = await CRUD()
- .get(link: AppLink.getRideStatusBegin, payload: {'ride_id': rideId});
- if (res != 'failure') {
- var decode = jsonDecode(res);
+ // bool isBeginRideFromDriver = false;
+ // void getBeginRideFromDriver() async {
+ // try {
+ // if (isBeginRideFromDriver) return; // Prevent duplicate streams
+ // isBeginRideFromDriver = true;
+ // var res = await CRUD()
+ // .get(link: AppLink.getRideStatusBegin, payload: {'ride_id': rideId});
+ // if (res != 'failure') {
+ // var decode = jsonDecode(res);
- // if (decode['data']['status'] != 'Apply') {
- if (decode['data']['status'] == 'Begin') {
- timeToPassengerFromDriverAfterApplied = 0;
- remainingTime = 0;
- remainingTimeToPassengerFromDriverAfterApplied = 0;
- remainingTimeDriverWaitPassenger5Minute = 0;
- rideTimerBegin = true;
- statusRide = 'Begin';
- isDriverInPassengerWay = false;
- isDriverArrivePassenger = false;
- update();
- // isCancelRidePageShown = true;
- rideIsBeginPassengerTimer();
- runWhenRideIsBegin();
- } else {}
+ // // if (decode['data']['status'] != 'Apply') {
+ // if (decode['data']['status'] == 'Begin') {
+ // timeToPassengerFromDriverAfterApplied = 0;
+ // remainingTime = 0;
+ // remainingTimeToPassengerFromDriverAfterApplied = 0;
+ // remainingTimeDriverWaitPassenger5Minute = 0;
+ // rideTimerBegin = true;
+ // statusRide = 'Begin';
+ // isDriverInPassengerWay = false;
+ // isDriverArrivePassenger = false;
+ // update();
+ // // isCancelRidePageShown = true;
+ // rideIsBeginPassengerTimer();
+ // runWhenRideIsBegin();
+ // } else {}
+ // }
+ // } catch (e) {
+ // // Handle the error or perform any necessary actions
+ // }
+ // }
+
+ StreamController _beginRideStreamController =
+ StreamController.broadcast();
+ Stream get beginRideStream => _beginRideStreamController.stream;
+
+ bool isBeginRideFromDriverRunning = false;
+
+ void getBeginRideFromDriver() {
+ if (isBeginRideFromDriverRunning) return; // Prevent duplicate streams
+ isBeginRideFromDriverRunning = true;
+
+ Timer.periodic(const Duration(seconds: 1), (timer) async {
+ try {
+ var res = await CRUD().get(
+ link: AppLink.getRideStatusBegin, payload: {'ride_id': rideId});
+ if (res != 'failure') {
+ var decode = jsonDecode(res);
+ _beginRideStreamController
+ .add(decode['data']['status']); // Emit the status
+
+ if (decode['data']['status'] == 'Begin') {
+ // Stop the periodic check
+ timer.cancel();
+ isBeginRideFromDriverRunning = false;
+
+ timeToPassengerFromDriverAfterApplied = 0;
+ remainingTime = 0;
+ remainingTimeToPassengerFromDriverAfterApplied = 0;
+ remainingTimeDriverWaitPassenger5Minute = 0;
+ rideTimerBegin = true;
+ statusRide = 'Begin';
+ isDriverInPassengerWay = false;
+ isDriverArrivePassenger = false;
+ update();
+
+ // Trigger additional actions
+ rideIsBeginPassengerTimer();
+ runWhenRideIsBegin();
+ NotificationController().showNotification(
+ 'Trip is begin'.tr,
+ 'The trip has started! Feel free to contact emergency numbers, share your trip, or activate voice recording for the journey'
+ .tr,
+ 'ding');
+ }
+ }
+ } catch (e) {
+ // Handle errors
+ _beginRideStreamController.addError(e);
}
- } catch (e) {
- // Handle the error or perform any necessary actions
- }
+ });
+ }
+
+// Call this method to listen to the stream
+ void listenToBeginRideStream() {
+ beginRideStream.listen((status) {
+ print("Ride status: $status");
+ // Perform additional actions based on the status
+ }, onError: (error) {
+ print("Error in Begin Ride Stream: $error");
+ });
}
begiVIPTripFromPassenger() async {
@@ -908,7 +1075,7 @@ class MapPassengerController extends GetxController {
if (rideStatusFromStartApp['data']['status'] == 'Begin') {
statusRide = 'Begin';
driverId = rideStatusFromStartApp['data']['driver_id'];
- firstName = rideStatusFromStartApp['data']['driverName'];
+ passengerName = rideStatusFromStartApp['data']['driverName'];
driverRate = rideStatusFromStartApp['data']['rateDriver'].toString();
statusRideFromStart = true;
// DateTime endTime =
@@ -1150,7 +1317,7 @@ class MapPassengerController extends GetxController {
int currentTimeSearchingCaptainWindow = 0;
late String driverPhone = '';
late String driverRate = '';
- late String firstName = '';
+ late String passengerName = '';
late String carColor = '';
late String colorHex = '';
late String carYear = '';
@@ -1158,500 +1325,249 @@ class MapPassengerController extends GetxController {
late String make = '';
late String licensePlate = '';
- confirmRideForFirstDriver() async {
- // startCarLocationSearch(box.read(BoxName.carType));
- // await getCarsLocationByPassengerAndReloadMarker(
- // box.read(BoxName.carType), 7000);
- // var nearestCar = await getNearestDriverByPassengerLocation();
-
- // if (nearestCar != null) {
- // // Find the corresponding driver data in dataCarsLocationByPassenger
- // var nearestDriverData = dataCarsLocationByPassenger['message'].firstWhere(
- // (car) => car['driver_id'] == nearestCar.id,
- // orElse: () => null,
- // );
-
- // // if (nearestDriverData != null) {
- // driverToken = nearestDriverData['token'].toString();
- // Log.print('driverToken: ${driverToken}');
- // driverPhone = nearestDriverData['phone'].toString();
- // firstName = nearestDriverData['first_name'].toString();
- // carColor = nearestDriverData['color'].toString();
- // driverRate = nearestDriverData['ratingDriver'].toString();
- // carYear = nearestDriverData['year'].toString();
- // model = '${nearestDriverData['model']} - ${nearestDriverData['make']}';
- // licensePlate = nearestDriverData['car_plate'].toString();
- // startCarLocationSearch(box.read(BoxName.carType));
- await getCarsLocationByPassengerAndReloadMarker(
- box.read(BoxName.carType), 3000);
- // await getCarsLocationByPassengerAndReloadMarker(
- // box.read(BoxName.carType), 7000);
- // await getNearestDriverByPassengerLocation();
- Log.print('dataCarsLocationByPassenger: $dataCarsLocationByPassenger');
- if (dataCarsLocationByPassenger != 'failure' ||
- dataCarsLocationByPassenger != null) {
- driverToken =
- dataCarsLocationByPassenger['data'][carsOrder]['token'].toString();
- driverPhone =
- dataCarsLocationByPassenger['data'][carsOrder]['phone'].toString();
- firstName = dataCarsLocationByPassenger['data'][carsOrder]
- ['first_name'] // driverName
- .toString();
- carColor =
- dataCarsLocationByPassenger['data'][carsOrder]['color'].toString();
- colorHex = dataCarsLocationByPassenger['data'][carsOrder]['color_hex'] ??
- '#A52A2A';
- driverRate = dataCarsLocationByPassenger['data'][carsOrder]
- ['ratingDriver']
- .toString();
- carYear =
- dataCarsLocationByPassenger['data'][carsOrder]['year'].toString();
- model =
- '${dataCarsLocationByPassenger['data'][carsOrder]['model']} - ${dataCarsLocationByPassenger['data'][carsOrder]['make']}';
- licensePlate = dataCarsLocationByPassenger['data'][carsOrder]['car_plate']
- .toString();
- PaymentController paymentController = Get.find();
- rideConfirm = true;
- shouldFetch = true;
- isBottomSheetShown = false;
- // timeToPassengerFromDriverAfterApplied = nearestCar.duration.toInt();
- timeToPassengerFromDriverAfterApplied =
- durationToPassenger; //60 todo durationToPassenger;/
- isDriversTokensSend = false;
-
- update();
- await CRUD().post(
- link: "${AppLink.seferCairoServer}/ride/rides/add.php",
- payload: {
- "start_location": //'${data[0]['start_address']}',
- '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
- "end_location": //'${data[0]['end_address']}',
- '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
- "date": DateTime.now().toString(),
- "time": DateTime.now().toString(),
- "endtime": durationToAdd.toString(),
- "price": totalPassenger.toStringAsFixed(2),
- "passenger_id": box.read(BoxName.passengerID).toString(),
- "driver_id": dataCarsLocationByPassenger['data'][carsOrder]
- ['driver_id']
- .toString(),
- "status": "waiting",
- 'carType': box.read(BoxName.carType),
- "price_for_driver": totalPassenger.toString(),
- "price_for_passenger": totalME.toString(),
- "distance": distance.toString(),
- "paymentMethod": paymentController.isWalletChecked.toString(),
- }).then((value) {
- // List body = [
- rideId = jsonDecode(value)['message'];
- List body = [
- '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
- '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
- totalPassenger.toStringAsFixed(2),
- totalDriver.toStringAsFixed(2),
- durationToRide.toString(),
- distance.toStringAsFixed(2),
- dataCarsLocationByPassenger['data'][carsOrder]['driver_id']
- .toString(),
- box.read(BoxName.passengerID).toString(),
- box.read(BoxName.name).toString(),
- box.read(BoxName.tokenFCM).toString(),
- box.read(BoxName.phone).toString(),
- durationByPassenger.toString(),
- distanceByPassenger.toString(),
- paymentController.isWalletChecked.toString(),
- dataCarsLocationByPassenger['data'][carsOrder]['token'].toString(),
- durationToPassenger.toString(),
- rideId,
- rideTimerBegin.toString(),
- dataCarsLocationByPassenger['data'][carsOrder]['driver_id']
- .toString(),
- durationToRide.toString(),
- Get.find().wayPoints.length > 1
- ? 'haveSteps'
- : 'startEnd',
- placesCoordinate[0],
- placesCoordinate[1],
- placesCoordinate[2],
- placesCoordinate[3],
- placesCoordinate[4],
- costForDriver.toStringAsFixed(2),
- double.parse(box.read(BoxName.passengerWalletTotal)) < 0
- ? double.parse(box.read(BoxName.passengerWalletTotal))
- .toStringAsFixed(2)
- : '0',
- box.read(BoxName.email).toString(),
- data[0]['start_address'],
- data[0]['end_address'],
- box.read(BoxName.carType),
- kazan.toStringAsFixed(0),
- passengerRate.toStringAsFixed(2),
- ];
- Log.print('bodyOf order: $body');
- FirebaseMessagesController().sendNotificationToDriverMAP(
- 'Order'.tr,
- 'from: $startNameAddress\nto: $startNameAddress\ndistanceFromMe: $distanceByPassenger\nDistance :$distance\nPrice ; $totalPassenger',
- // jsonDecode(value)['message'].toString(),
- driverToken.toString(),
- body,
- 'order.wav');
- Log.print(
- 'dataCarsLocationByPassenger[data]: ${dataCarsLocationByPassenger['data'][carsOrder]['token']}');
- });
-
- if (AppLink.endPoint != AppLink.seferCairoServer) {
- CRUD().post(link: "${AppLink.endPoint}/ride/rides/add.php", payload: {
- "start_location": //'${data[0]['start_address']}',
- '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
- "end_location": //'${data[0]['end_address']}',
- '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
- "date": DateTime.now().toString(),
- "time": DateTime.now().toString(),
- "endtime": durationToAdd.toString(),
- "price": totalPassenger.toStringAsFixed(2),
- "passenger_id": box.read(BoxName.passengerID).toString(),
- "driver_id": dataCarsLocationByPassenger['data'][carsOrder]
- ['driver_id']
- .toString(),
- "status": "waiting",
- 'carType': box.read(BoxName.carType),
- "price_for_driver": totalPassenger.toString(),
- "price_for_passenger": totalME.toString(),
- "distance": distance.toString(),
- "paymentMethod": paymentController.isWalletChecked.toString(),
- });
- }
- delayAndFetchRideStatus(rideId, box.read(BoxName.carType));
- if (shouldFetch == false) {
- startTimer();
- update();
- }
- update();
- } else {
- Get.defaultDialog(
- title: 'No Car or Driver Found in your area.'.tr,
- titleStyle: AppStyle.title,
- middleText: 'Please Try anther time '.tr,
- middleTextStyle: AppStyle.title.copyWith(color: AppColor.yellowColor),
- confirm: MyElevatedButton(
- title: 'Ok'.tr,
- onPressed: () {
- Get.back();
- isSearchingWindow = false;
- cancelRide();
- update();
- }));
- }
- }
-
String driverOrderStatus = 'yet';
bool isDriversTokensSend = false;
- confirmRideForAllDriverAvailable0() async {
- await getCarsLocationByPassengerAndReloadMarker(
- box.read(BoxName.carType), 3500);
- if (dataCarsLocationByPassenger != 'failure') {
- // driversToken.remove(driverToken);
- PaymentController paymentController = Get.find();
- rideConfirm = true;
- shouldFetch = true;
- isBottomSheetShown = false;
- timeToPassengerFromDriverAfterApplied = 60;
- await CRUD().post(
- link: "${AppLink.seferCairoServer}/ride/rides/add.php",
- payload: {
- "start_location": //'${data[0]['start_address']}',
- '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
- "end_location": //'${data[0]['end_address']}',
- '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
- "date": DateTime.now().toString(),
- "time": DateTime.now().toString(),
- "endtime": durationToAdd.toString(),
- "price": totalPassenger.toStringAsFixed(2),
- "passenger_id": box.read(BoxName.passengerID).toString(),
- "driver_id": dataCarsLocationByPassenger['data'][carsOrder]
- ['driver_id']
- .toString(),
- "status": "waiting",
- 'carType': box.read(BoxName.carType),
- "price_for_driver": totalPassenger.toString(),
- "price_for_passenger": totalME.toString(),
- "distance": distance.toString(),
- "paymentMethod": paymentController.isWalletChecked.toString(),
- }).then((value) {
- // List body = [
- rideId = jsonDecode(value)['message'];
- for (var i = 0; i < dataCarsLocationByPassenger['data'].length; i++) {
- List body = [
- '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
- '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
- totalPassenger.toStringAsFixed(2),
- totalDriver.toStringAsFixed(2),
- durationToRide.toString(),
- distance.toStringAsFixed(2),
- dataCarsLocationByPassenger['data'][i]['driver_id'].toString(),
- box.read(BoxName.passengerID).toString(),
- box.read(BoxName.name).toString(),
- box.read(BoxName.tokenFCM).toString(),
- box.read(BoxName.phone).toString(),
- durationByPassenger.toString(),
- distanceByPassenger.toString(),
- paymentController.isWalletChecked.toString(),
- dataCarsLocationByPassenger['data'][i]['token'].toString(),
- durationToPassenger.toString(),
- rideId,
- rideTimerBegin.toString(),
- dataCarsLocationByPassenger['data'][i]['driver_id'].toString(),
- durationToRide.toString(),
- Get.find().wayPoints.length > 1
- ? 'haveSteps'
- : 'startEnd',
- placesCoordinate[0],
- placesCoordinate[1],
- placesCoordinate[2],
- placesCoordinate[3],
- placesCoordinate[4],
- costForDriver.toStringAsFixed(2),
- double.parse(box.read(BoxName.passengerWalletTotal)) < 0
- ? double.parse(box.read(BoxName.passengerWalletTotal))
- .toStringAsFixed(2)
- : '0',
- box.read(BoxName.email).toString(),
- data[0]['start_address'],
- data[0]['end_address'],
- box.read(BoxName.carType),
- kazan.toStringAsFixed(0),
- passengerRate.toStringAsFixed(2),
- ];
- // Log.print('body: ${body}');
-
- FirebaseMessagesController().sendNotificationToDriverMAP(
- 'OrderSpeed',
- rideId.toString(),
- dataCarsLocationByPassenger['data'][i]['token'].toString(),
- body,
- 'order.wav',
- );
- driverOrderStatus = 'recive';
- }
- });
- (rideId); //
- if (AppLink.endPoint != AppLink.seferCairoServer) {
- CRUD().post(link: '${AppLink.endPoint}/ride/rides/add.php', payload: {
- "start_location": //'${data[0]['start_address']}',
- '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
- "end_location": //'${data[0]['end_address']}',
- '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
- "date": DateTime.now().toString(),
- "time": DateTime.now().toString(),
- "endtime": durationToAdd.toString(),
- "price": totalPassenger.toStringAsFixed(2),
- "passenger_id": box.read(BoxName.passengerID).toString(),
- "driver_id": dataCarsLocationByPassenger['data'][carsOrder]
- ['driver_id']
- .toString(),
- "status": "waiting",
- 'carType': box.read(BoxName.carType),
- "price_for_driver": totalPassenger.toString(),
- "price_for_passenger": totalME.toString(),
- "distance": distance.toString(),
- "paymentMethod": paymentController.isWalletChecked.toString(),
- });
- }
-
- delayAndFetchRideStatusForAllDriverAvailable(rideId);
- update();
- } else {
- MyDialog().getDialog("No Car or Driver Found in your area.".tr,
- "No Car or Driver Found in your area.".tr, () {
- Get.back();
- Get.offAll(const MapPagePassenger());
- });
- }
- }
Set notifiedDrivers = {};
- confirmRideForAllDriverAvailable11() async {
- // Fetch car locations
- await getCarsLocationByPassengerAndReloadMarker(
- box.read(BoxName.carType), 3000);
-
- // Ensure dataCarsLocationByPassenger is not 'failure' or null
- if (dataCarsLocationByPassenger != 'failure' &&
- dataCarsLocationByPassenger != null) {
- // Check if 'data' key exists and is not null
- if (dataCarsLocationByPassenger.containsKey('data') &&
- dataCarsLocationByPassenger['data'] != null) {
- PaymentController paymentController = Get.find();
- rideConfirm = true;
- shouldFetch = true;
- isBottomSheetShown = false;
- timeToPassengerFromDriverAfterApplied = 60;
-
- // Add ride to database
- await CRUD().post(
- link: "${AppLink.seferCairoServer}/ride/rides/add.php",
- payload: {
- "start_location":
- '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
- "end_location":
- '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
- "date": DateTime.now().toString(),
- "time": DateTime.now().toString(),
- "endtime": durationToAdd.toString(),
- "price": totalPassenger.toStringAsFixed(2),
- "passenger_id": box.read(BoxName.passengerID).toString(),
- "driver_id": dataCarsLocationByPassenger['data'][carsOrder]
- ['driver_id']
- .toString(),
- "status": "waiting",
- 'carType': box.read(BoxName.carType),
- "price_for_driver": totalPassenger.toString(),
- "price_for_passenger": totalME.toString(),
- "distance": distance.toString(),
- "paymentMethod": paymentController.isWalletChecked.toString(),
- }).then((value) {
- if (value is String) {
- final parsedValue = jsonDecode(value);
- rideId = parsedValue['message'];
- } else if (value is Map) {
- rideId = value['message'];
- } else {
- Log.print('Unexpected response type: ${value.runtimeType}');
- }
- // Log.print('value: ${value}');
- // rideId = jsonDecode(value)['message'];
- // rideId = jsonDecode(value)['message'].toString();
-
- // Timer for 5 iterations, runs every 2 seconds
- int iteration = 0;
- Timer.periodic(const Duration(seconds: 2), (timer) async {
- if (iteration >= 10) {
- timer.cancel();
- return;
- }
- iteration++;
-
- // Reload driver locations
- await getCarsLocationByPassengerAndReloadMarker(
- box.read(BoxName.carType), 3000);
-
- // Ensure dataCarsLocationByPassenger and data key are still valid
- if (dataCarsLocationByPassenger != null &&
- dataCarsLocationByPassenger.containsKey('data') &&
- dataCarsLocationByPassenger['data'] != null) {
- // Notify only new drivers
- for (var driverData in dataCarsLocationByPassenger['data']) {
- String driverId = driverData['driver_id'].toString();
- if (!notifiedDrivers.contains(driverId)) {
- notifiedDrivers.add(driverId);
-
- // Prepare body payload for notification
- List body = [
- '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
- '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
- totalPassenger.toStringAsFixed(2),
- totalDriver.toStringAsFixed(2),
- durationToRide.toString(),
- distance.toStringAsFixed(2),
- driverId,
- box.read(BoxName.passengerID).toString(),
- box.read(BoxName.name).toString(),
- box.read(BoxName.tokenFCM).toString(),
- box.read(BoxName.phone).toString(),
- durationByPassenger.toString(),
- distanceByPassenger.toString(),
- paymentController.isWalletChecked.toString(),
- driverData['token'].toString(),
- durationToPassenger.toString(),
- rideId,
- rideTimerBegin.toString(),
- driverId,
- durationToRide.toString(),
- Get.find().wayPoints.length > 1
- ? 'haveSteps'
- : 'startEnd',
- placesCoordinate[0],
- placesCoordinate[1],
- placesCoordinate[2],
- placesCoordinate[3],
- placesCoordinate[4],
- costForDriver.toStringAsFixed(2),
- (double.parse(box.read(BoxName.passengerWalletTotal)) < 0
- ? double.parse(box.read(BoxName.passengerWalletTotal))
- .toStringAsFixed(2)
- : '0'),
- box.read(BoxName.email).toString(),
- data[0]['start_address'],
- data[0]['end_address'],
- box.read(BoxName.carType),
- kazan.toStringAsFixed(0),
- passengerRate.toStringAsFixed(2),
- ];
-
- // Send notification to the driver
- FirebaseMessagesController().sendNotificationToDriverMAP(
- 'OrderSpeed',
- rideId,
- driverData['token'].toString(),
- body,
- 'order.wav',
- );
- }
- }
- }
- });
- });
-
- // Check for additional server endpoint
- if (AppLink.endPoint != AppLink.seferCairoServer) {
- CRUD().post(link: '${AppLink.endPoint}/ride/rides/add.php', payload: {
- "start_location":
+ addRideToNotificationDriverString() async {
+ await CRUD().post(link: AppLink.addWaitingRide, payload: {
+ 'id': rideId.toString(),
+ 'start_location':
+ '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
+ 'end_location':
+ '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
+ "date": DateTime.now().toString(),
+ "time": DateTime.now().toString(),
+ "price": totalPassenger.toStringAsFixed(2),
+ 'passenger_id': box.read(BoxName.passengerID).toString(),
+ 'status': 'waiting',
+ 'carType': box.read(BoxName.carType),
+ 'passengerRate': passengerRate,
+ 'price_for_passenger': totalME.toString(),
+ 'distance': distance.toString(),
+ 'duration': duration ?? '10',
+ });
+ if (AppLink.endPoint != AppLink.seferCairoServer) {
+ CRUD().post(
+ link: '${AppLink.endPoint}/notificationCaptain/addWaitingRide.php',
+ payload: {
+ 'id': rideId.toString(),
+ 'start_location':
'${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
- "end_location":
+ 'end_location':
'${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
"date": DateTime.now().toString(),
"time": DateTime.now().toString(),
- "endtime": durationToAdd.toString(),
"price": totalPassenger.toStringAsFixed(2),
- "passenger_id": box.read(BoxName.passengerID).toString(),
- "driver_id": dataCarsLocationByPassenger['data'][carsOrder]
- ['driver_id']
- .toString(),
- "status": "waiting",
+ 'passenger_id': box.read(BoxName.passengerID).toString(),
+ 'status': 'waiting',
'carType': box.read(BoxName.carType),
- "price_for_driver": totalPassenger.toString(),
- "price_for_passenger": totalME.toString(),
- "distance": distance.toString(),
- "paymentMethod": paymentController.isWalletChecked.toString(),
+ 'passengerRate': passengerRate,
+ 'price_for_passenger': totalME.toString(),
+ 'distance': distance.toString(),
+ 'duration': duration ?? '10',
});
- }
- delayAndFetchRideStatusForAllDriverAvailable(rideId);
- update();
- } else {
- // Show dialog if no drivers found in data key
- MyDialog().getDialog("No Car or Driver Found in your area.".tr,
- "No Car or Driver Found in your area.".tr, () {
- Get.back();
- Get.offAll(const MapPagePassenger());
- });
- }
- } else {
- // Show dialog if dataCarsLocationByPassenger is 'failure' or null
- MyDialog().getDialog("No Car or Driver Found in your area.".tr,
- "No Car or Driver Found in your area.".tr, () {
- Get.back();
- Get.offAll(const MapPagePassenger());
- });
}
}
- Future confirmRideForAllDriverAvailable() async {
- // Try to fetch car locations up to 4 times with a 2-second delay
+ // Future confirmRideForAllDriverAvailable1() async {
+ // // Try to fetch car locations up to 4 times with a 2-second delay
+ // bool driversFound = false;
+ // for (int attempt = 0; attempt < 8; attempt++) {
+ // await getCarsLocationByPassengerAndReloadMarker(
+ // box.read(BoxName.carType), attempt > 5 ? 4500 : 3000);
+
+ // // Check if dataCarsLocationByPassenger is valid and contains drivers
+ // if (dataCarsLocationByPassenger != 'failure' &&
+ // dataCarsLocationByPassenger != null &&
+ // dataCarsLocationByPassenger.containsKey('data') &&
+ // dataCarsLocationByPassenger['data'] != null) {
+ // driversFound = true;
+ // break; // Exit loop if drivers are found
+ // }
+
+ // // Wait 2 seconds before next attempt
+ // await Future.delayed(const Duration(seconds: 2));
+ // }
+
+ // // If no drivers were found after 4 attempts, show a dialog
+ // if (!driversFound) {
+ // Get.dialog(
+ // BackdropFilter(
+ // filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
+ // child: CupertinoAlertDialog(
+ // title: Text(
+ // "No Car or Driver Found in your area.".tr,
+ // style: AppStyle.title.copyWith(
+ // fontSize: 20,
+ // fontWeight: FontWeight.bold,
+ // ),
+ // ),
+ // content: Text(
+ // "No Car or Driver Found in your area.".tr,
+ // style: AppStyle.title.copyWith(fontSize: 16),
+ // ),
+ // actions: [
+ // CupertinoDialogAction(
+ // onPressed: () {
+ // Get.back();
+ // Get.offAll(() => const MapPagePassenger());
+ // },
+ // child: Text('OK'.tr,
+ // style: const TextStyle(color: AppColor.greenColor)),
+ // ),
+ // ],
+ // ),
+ // ),
+ // barrierDismissible: false,
+ // );
+
+ // return;
+ // }
+
+ // // Proceed with the rest of the function if drivers are found
+ // PaymentController paymentController = Get.find();
+ // rideConfirm = true;
+ // shouldFetch = true;
+ // isBottomSheetShown = false;
+ // timeToPassengerFromDriverAfterApplied = 60;
+
+ // // Add ride to database
+ // await CRUD()
+ // .post(link: "${AppLink.seferCairoServer}/ride/rides/add.php", payload: {
+ // "start_location":
+ // '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
+ // "end_location":
+ // '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
+ // "date": DateTime.now().toString(),
+ // "time": DateTime.now().toString(),
+ // "endtime": durationToAdd.toString(),
+ // "price": totalPassenger.toStringAsFixed(2),
+ // "passenger_id": box.read(BoxName.passengerID).toString(),
+ // "driver_id": dataCarsLocationByPassenger['data'][carsOrder]['driver_id']
+ // .toString(),
+ // "status": "waiting",
+ // 'carType': box.read(BoxName.carType),
+ // "price_for_driver": totalPassenger.toString(),
+ // "price_for_passenger": totalME.toString(),
+ // "distance": distance.toString(),
+ // "paymentMethod": paymentController.isWalletChecked.toString(),
+ // }).then((value) {
+ // if (value is String) {
+ // final parsedValue = jsonDecode(value);
+ // rideId = parsedValue['message'];
+ // } else if (value is Map) {
+ // rideId = value['message'];
+ // } else {
+ // Log.print('Unexpected response type: ${value.runtimeType}');
+ // }
+
+ // // Timer to notify drivers every 2 seconds for 5 iterations
+ // int iteration = 0;
+ // Timer.periodic(const Duration(seconds: 2), (timer) async {
+ // if (iteration >= 5) {
+ // timer.cancel();
+ // return;
+ // }
+ // iteration++;
+
+ // // Reload driver locations and notify available drivers
+ // await getCarsLocationByPassengerAndReloadMarker(
+ // box.read(BoxName.carType), 3000);
+ // if (dataCarsLocationByPassenger != null &&
+ // dataCarsLocationByPassenger.containsKey('data') &&
+ // dataCarsLocationByPassenger['data'] != null) {
+ // for (var driverData in dataCarsLocationByPassenger['data']) {
+ // String driverId = driverData['driver_id'].toString();
+ // if (!notifiedDrivers.contains(driverId)) {
+ // notifiedDrivers.add(driverId);
+ // List body = [
+ // '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
+ // '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
+ // totalPassenger.toStringAsFixed(2),
+ // totalDriver.toStringAsFixed(2),
+ // durationToRide.toString(),
+ // distance.toStringAsFixed(2),
+ // driverId.toString(),
+ // box.read(BoxName.passengerID).toString(),
+ // box.read(BoxName.name).toString(),
+ // box.read(BoxName.tokenFCM).toString(),
+ // box.read(BoxName.phone).toString(),
+ // durationByPassenger.toString(),
+ // distanceByPassenger.toString(),
+ // paymentController.isWalletChecked.toString(),
+ // driverData['token'].toString(),
+ // durationToPassenger.toString(),
+ // rideId.toString(),
+ // rideTimerBegin.toString(),
+ // driverId.toString(),
+ // durationToRide.toString(),
+ // Get.find().wayPoints.length > 1
+ // ? 'haveSteps'
+ // : 'startEnd',
+ // placesCoordinate[0],
+ // placesCoordinate[1],
+ // placesCoordinate[2],
+ // placesCoordinate[3],
+ // placesCoordinate[4],
+ // costForDriver.toStringAsFixed(2),
+ // (double.parse(box.read(BoxName.passengerWalletTotal)) < 0
+ // ? double.parse(box.read(BoxName.passengerWalletTotal))
+ // .toStringAsFixed(2)
+ // : '0'),
+ // box.read(BoxName.email).toString(),
+ // data[0]['start_address'],
+ // data[0]['end_address'],
+ // box.read(BoxName.carType),
+ // kazan.toStringAsFixed(0),
+ // passengerRate.toStringAsFixed(2),
+ // ];
+ // Log.print('body: ${body}');
+ // FirebaseMessagesController().sendNotificationToDriverMAP(
+ // 'OrderSpeed',
+ // rideId,
+ // driverData['token'].toString(),
+ // body,
+ // 'order.wav',
+ // );
+ // }
+ // }
+ // }
+ // });
+ // });
+
+ // // If an additional endpoint is available, post data there as well
+ // if (AppLink.endPoint != AppLink.seferCairoServer) {
+ // CRUD().post(link: '${AppLink.endPoint}/ride/rides/add.php', payload: {
+ // "start_location":
+ // '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
+ // "end_location":
+ // '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
+ // "date": DateTime.now().toString(),
+ // "time": DateTime.now().toString(),
+ // "endtime": durationToAdd.toString(),
+ // "price": totalPassenger.toStringAsFixed(2),
+ // "passenger_id": box.read(BoxName.passengerID).toString(),
+ // "driver_id": dataCarsLocationByPassenger['data'][carsOrder]['driver_id']
+ // .toString(),
+ // "status": "waiting",
+ // 'carType': box.read(BoxName.carType),
+ // "price_for_driver": totalPassenger.toString(),
+ // "price_for_passenger": totalME.toString(),
+ // "distance": distance.toString(),
+ // "paymentMethod": paymentController.isWalletChecked.toString(),
+ // });
+ // }
+ // delayAndFetchRideStatusForAllDriverAvailable(rideId);
+ // update();
+ // }
+
+ icreaseForSameRideAndDelay() async {
bool driversFound = false;
- for (int attempt = 0; attempt < 4; attempt++) {
+ for (int attempt = 0; attempt < 8; attempt++) {
await getCarsLocationByPassengerAndReloadMarker(
- box.read(BoxName.carType), 3000);
+ box.read(BoxName.carType), 4500);
// Check if dataCarsLocationByPassenger is valid and contains drivers
if (dataCarsLocationByPassenger != 'failure' &&
@@ -1700,149 +1616,12 @@ class MapPassengerController extends GetxController {
return;
}
-
- // Proceed with the rest of the function if drivers are found
- PaymentController paymentController = Get.find();
- rideConfirm = true;
- shouldFetch = true;
- isBottomSheetShown = false;
- timeToPassengerFromDriverAfterApplied = 60;
-
- // Add ride to database
- await CRUD()
- .post(link: "${AppLink.seferCairoServer}/ride/rides/add.php", payload: {
- "start_location":
- '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
- "end_location":
- '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
- "date": DateTime.now().toString(),
- "time": DateTime.now().toString(),
- "endtime": durationToAdd.toString(),
- "price": totalPassenger.toStringAsFixed(2),
- "passenger_id": box.read(BoxName.passengerID).toString(),
- "driver_id": dataCarsLocationByPassenger['data'][carsOrder]['driver_id']
- .toString(),
- "status": "waiting",
- 'carType': box.read(BoxName.carType),
- "price_for_driver": totalPassenger.toString(),
- "price_for_passenger": totalME.toString(),
- "distance": distance.toString(),
- "paymentMethod": paymentController.isWalletChecked.toString(),
- }).then((value) {
- if (value is String) {
- final parsedValue = jsonDecode(value);
- rideId = parsedValue['message'];
- } else if (value is Map) {
- rideId = value['message'];
- } else {
- Log.print('Unexpected response type: ${value.runtimeType}');
- }
-
- // Timer to notify drivers every 2 seconds for 5 iterations
- int iteration = 0;
- Timer.periodic(const Duration(seconds: 2), (timer) async {
- if (iteration >= 5) {
- timer.cancel();
- return;
- }
- iteration++;
-
- // Reload driver locations and notify available drivers
- await getCarsLocationByPassengerAndReloadMarker(
- box.read(BoxName.carType), 3000);
- if (dataCarsLocationByPassenger != null &&
- dataCarsLocationByPassenger.containsKey('data') &&
- dataCarsLocationByPassenger['data'] != null) {
- for (var driverData in dataCarsLocationByPassenger['data']) {
- String driverId = driverData['driver_id'].toString();
- if (!notifiedDrivers.contains(driverId)) {
- notifiedDrivers.add(driverId);
- List body = [
- '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
- '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
- totalPassenger.toStringAsFixed(2),
- totalDriver.toStringAsFixed(2),
- durationToRide.toString(),
- distance.toStringAsFixed(2),
- driverId,
- box.read(BoxName.passengerID).toString(),
- box.read(BoxName.name).toString(),
- box.read(BoxName.tokenFCM).toString(),
- box.read(BoxName.phone).toString(),
- durationByPassenger.toString(),
- distanceByPassenger.toString(),
- paymentController.isWalletChecked.toString(),
- driverData['token'].toString(),
- durationToPassenger.toString(),
- rideId,
- rideTimerBegin.toString(),
- driverId,
- durationToRide.toString(),
- Get.find().wayPoints.length > 1
- ? 'haveSteps'
- : 'startEnd',
- placesCoordinate[0],
- placesCoordinate[1],
- placesCoordinate[2],
- placesCoordinate[3],
- placesCoordinate[4],
- costForDriver.toStringAsFixed(2),
- (double.parse(box.read(BoxName.passengerWalletTotal)) < 0
- ? double.parse(box.read(BoxName.passengerWalletTotal))
- .toStringAsFixed(2)
- : '0'),
- box.read(BoxName.email).toString(),
- data[0]['start_address'],
- data[0]['end_address'],
- box.read(BoxName.carType),
- kazan.toStringAsFixed(0),
- passengerRate.toStringAsFixed(2),
- ];
- FirebaseMessagesController().sendNotificationToDriverMAP(
- 'OrderSpeed',
- rideId,
- driverData['token'].toString(),
- body,
- 'order.wav',
- );
- }
- }
- }
- });
- });
-
- // If an additional endpoint is available, post data there as well
- if (AppLink.endPoint != AppLink.seferCairoServer) {
- CRUD().post(link: '${AppLink.endPoint}/ride/rides/add.php', payload: {
- "start_location":
- '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
- "end_location":
- '${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
- "date": DateTime.now().toString(),
- "time": DateTime.now().toString(),
- "endtime": durationToAdd.toString(),
- "price": totalPassenger.toStringAsFixed(2),
- "passenger_id": box.read(BoxName.passengerID).toString(),
- "driver_id": dataCarsLocationByPassenger['data'][carsOrder]['driver_id']
- .toString(),
- "status": "waiting",
- 'carType': box.read(BoxName.carType),
- "price_for_driver": totalPassenger.toString(),
- "price_for_passenger": totalME.toString(),
- "distance": distance.toString(),
- "paymentMethod": paymentController.isWalletChecked.toString(),
- });
- }
- delayAndFetchRideStatusForAllDriverAvailable(rideId);
- update();
- }
-
- icreaseForSameRideAndDelay() {
PaymentController paymentController = Get.find();
rideConfirm = true;
shouldFetch = true;
isBottomSheetShown = false;
timeToPassengerFromDriverAfterApplied = 60;
+ // confirmRideForAllDriverAvailable();
for (var i = 0; i < dataCarsLocationByPassenger['data'].length; i++) {
List body = [
'${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
@@ -1861,7 +1640,7 @@ class MapPassengerController extends GetxController {
paymentController.isWalletChecked.toString(),
dataCarsLocationByPassenger['data'][i]['token'].toString(),
durationToPassenger.toString(),
- rideId,
+ rideId.toString(),
rideTimerBegin.toString(),
dataCarsLocationByPassenger['data'][i]['driver_id'].toString(),
durationToRide.toString(),
@@ -1898,64 +1677,76 @@ class MapPassengerController extends GetxController {
int tick = 0; // Move tick outside the function to maintain its state
- void delayAndFetchRideStatus(String rideId, carType) {
- Timer.periodic(const Duration(seconds: 1), (timer) async {
- if (shouldFetch) {
- if (remainingTimeToPassengerFromDriverAfterApplied > 0) {
- String res = await getRideStatus(rideId);
+ // void delayAndFetchRideStatus(String rideId, carType) {
+ // Timer.periodic(const Duration(seconds: 1), (timer) async {
+ // if (shouldFetch) {
+ // if (remainingTimeToPassengerFromDriverAfterApplied > 0) {
+ // String res = await getRideStatus(rideId);
- Log.print('tick: $tick');
- String rideStatusDelayed = res.toString();
- if ((rideStatusDelayed == 'waiting' ||
- rideStatusDelayed == 'Refused') &&
- tick >= 15) {
- timer.cancel(); // Stop the current timer
- showAndResearchForCaptain();
- //TODO add to wait
- await getCarsLocationByPassengerAndReloadMarker(carType, 3000);
- // await getNearestDriverByPassengerLocationAPIGOOGLE();
- // getCarForFirstConfirm(carType);
- confirmRideForAllDriverAvailable();
- // delayAndFetchRideStatusForAllDriverAvailable(rideId);
- } else if (rideStatusDelayed == 'Apply' || statusRide == 'Apply') {
- Log.print('rideStatusDelayed == Apply: $rideStatusDelayed');
- // todo play sound
- Get.find()
- .playSoundFromAssets('assets/start.wav');
- timer.cancel(); // Stop the current timer
- await getUpdatedRideForDriverApply(rideId);
- shouldFetch = false; // Stop further fetches
- statusRide = 'Apply';
- rideConfirm = false;
- isSearchingWindow = false;
- update();
- startTimerFromDriverToPassengerAfterApplied();
- } else if (rideStatusDelayed == 'Refused') {
- statusRide = 'Refused';
- if (isDriversTokensSend == false) {
- confirmRideForAllDriverAvailable();
- isDriversTokensSend = true;
- } // Start 15-second timer
- }
- //else if (isDriversTokensSend == false) {
- // No need to recall delayAndFetchRideStatus as Timer.periodic is already running
- update();
- // }
- if (tick < 19) {
- tick++;
- } else {
- timer.cancel();
- // Stop the timer if remainingTimeToPassengerFromDriverAfterApplied <= 0
- }
- } else {
- timer.cancel();
- // Stop the timer if remainingTimeToPassengerFromDriverAfterApplied <= 0
- }
- } else {
- timer.cancel(); // Stop the timer if shouldFetch is false
- }
- });
- }
+ // Log.print('tick: $tick');
+ // String rideStatusDelayed = res.toString();
+ // if ((rideStatusDelayed == 'waiting' ||
+ // rideStatusDelayed == 'Refused') &&
+ // tick >= 15) {
+ // timer.cancel(); // Stop the current timer
+ // showAndResearchForCaptain();
+ // //TODO add to wait
+ // await getCarsLocationByPassengerAndReloadMarker(carType, 3000);
+ // // await getNearestDriverByPassengerLocationAPIGOOGLE();
+ // // getCarForFirstConfirm(carType);
+ // confirmRideForAllDriverAvailable();
+ // // delayAndFetchRideStatusForAllDriverAvailable(rideId);
+ // } else if (rideStatusDelayed == 'Apply' || statusRide == 'Apply') {
+ // Log.print('rideStatusDelayed == Apply: $rideStatusDelayed');
+ // // todo play sound
+ // Get.find()
+ // .playSoundFromAssets('assets/start.wav');
+ // timer.cancel(); // Stop the current timer
+ // await getUpdatedRideForDriverApply(rideId);
+ // shouldFetch = false; // Stop further fetches
+ // statusRide = 'Apply';
+ // rideConfirm = false;
+ // isSearchingWindow = false;
+ // update();
+ // startTimerFromDriverToPassengerAfterApplied();
+ // if (box.read(BoxName.carType) == 'Speed' ||
+ // box.read(BoxName.carType) == 'Awfar Car') {
+ // NotificationController().showNotification(
+ // 'The captain is responsible for the route.'.tr,
+ // 'This price is fixed even if the route changes for the driver.'
+ // .tr,
+ // 'ding');
+ // } else if (box.read(BoxName.carType) == 'Comfort' ||
+ // box.read(BoxName.carType) == 'Lady') {
+ // NotificationController().showNotification('Attention'.tr,
+ // 'The price may increase if the route changes.'.tr, 'ding');
+ // }
+ // } else if (rideStatusDelayed == 'Refused') {
+ // statusRide = 'Refused';
+ // if (isDriversTokensSend == false) {
+ // confirmRideForAllDriverAvailable();
+ // isDriversTokensSend = true;
+ // } // Start 15-second timer
+ // }
+ // //else if (isDriversTokensSend == false) {
+ // // No need to recall delayAndFetchRideStatus as Timer.periodic is already running
+ // update();
+ // // }
+ // if (tick < 19) {
+ // tick++;
+ // } else {
+ // timer.cancel();
+ // // Stop the timer if remainingTimeToPassengerFromDriverAfterApplied <= 0
+ // }
+ // } else {
+ // timer.cancel();
+ // // Stop the timer if remainingTimeToPassengerFromDriverAfterApplied <= 0
+ // }
+ // } else {
+ // timer.cancel(); // Stop the timer if shouldFetch is false
+ // }
+ // });
+ // }
showAndResearchForCaptain() {
Get.snackbar(
@@ -1969,27 +1760,271 @@ class MapPassengerController extends GetxController {
update();
}
- void delayAndFetchRideStatusForAllDriverAvailable(String rideId) async {
+ Future confirmRideForAllDriverAvailable() async {
+ bool driversFound = false;
+ const maxAttempts = 8;
+ const attemptDelay = Duration(seconds: 3);
+
+ for (int attempt = 0; attempt < maxAttempts; attempt++) {
+ final reloadDuration = attempt > 5 ? 4500 : 3000;
+ await getCarsLocationByPassengerAndReloadMarker(
+ box.read(BoxName.carType), reloadDuration);
+ // await getNearestDriverByPassengerLocation();
+
+ if (isDriversDataValid()) {
+ driversFound = true;
+ break;
+ }
+
+ await Future.delayed(attemptDelay);
+ }
+
+ if (!driversFound) {
+ showNoDriversDialog();
+ return;
+ }
+
+ await postRideDetailsToServer();
+ await notifyAvailableDrivers();
+ delayAndFetchRideStatusForAllDriverAvailable(rideId);
+ update();
+ }
+
+ Future updateConfirmRideForAllDriverAvailable() async {
+ bool driversFound = false;
+ const maxAttempts = 8;
+ const attemptDelay = Duration(seconds: 3);
+
+ for (int attempt = 0; attempt < maxAttempts; attempt++) {
+ final reloadDuration = attempt > 5 ? 4500 : 3000;
+ await getCarsLocationByPassengerAndReloadMarker(
+ box.read(BoxName.carType), reloadDuration);
+ // await getNearestDriverByPassengerLocation();
+
+ if (isDriversDataValid()) {
+ driversFound = true;
+ break;
+ }
+
+ await Future.delayed(attemptDelay);
+ }
+
+ if (!driversFound) {
+ showNoDriversDialog();
+ return;
+ }
+
+ // await postRideDetailsToServer();
+ await notifyAvailableDrivers();
+ delayAndFetchRideStatusForAllDriverAvailable(rideId);
+ update();
+ }
+
+ bool isDriversDataValid() {
+ return dataCarsLocationByPassenger != 'failure' &&
+ dataCarsLocationByPassenger != null &&
+ dataCarsLocationByPassenger.containsKey('data') &&
+ dataCarsLocationByPassenger['data'] != null;
+ }
+
+ void showNoDriversDialog() {
+ Get.dialog(
+ BackdropFilter(
+ filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
+ child: CupertinoAlertDialog(
+ title: Text("No Car or Driver Found in your area.".tr,
+ style: AppStyle.title
+ .copyWith(fontSize: 20, fontWeight: FontWeight.bold)),
+ content: Text("No Car or Driver Found in your area.".tr,
+ style: AppStyle.title.copyWith(fontSize: 16)),
+ actions: [
+ CupertinoDialogAction(
+ onPressed: () {
+ Get.back();
+ Get.offAll(() => const MapPagePassenger());
+ },
+ child: Text('OK'.tr,
+ style: const TextStyle(color: AppColor.greenColor)),
+ ),
+ ],
+ ),
+ ),
+ barrierDismissible: false,
+ );
+ }
+
+ Future postRideDetailsToServer() async {
+ final paymentController = Get.find();
+ final payload = constructRidePayload(paymentController);
+
+ try {
+ final response = await CRUD().post(
+ link: "${AppLink.seferCairoServer}/ride/rides/add.php",
+ payload: payload);
+ if (response is String) {
+ final parsedValue = jsonDecode(response);
+ rideId = parsedValue['message'];
+ } else if (response is Map) {
+ rideId = response['message'];
+ } else {
+ Log.print('Unexpected response type: ${response.runtimeType}');
+ }
+ } catch (e) {
+ Log.print('Error posting ride details: $e');
+ }
+ }
+
+ Map constructRidePayload(
+ PaymentController paymentController) {
+ final startLocation =
+ '${data[0]['start_location']['lat']},${data[0]['start_location']['lng']}';
+ final endLocation =
+ '${data[0]['end_location']['lat']},${data[0]['end_location']['lng']}';
+
+ return {
+ "start_location": startLocation,
+ "end_location": endLocation,
+ "date": DateTime.now().toString(),
+ "time": DateTime.now().toString(),
+ "endtime": durationToAdd.toString(),
+ "price": totalPassenger.toStringAsFixed(2),
+ "passenger_id": box.read(BoxName.passengerID).toString(),
+ "driver_id": dataCarsLocationByPassenger['data'][carsOrder]['driver_id']
+ .toString(),
+ "status": "waiting",
+ 'carType': box.read(BoxName.carType),
+ "price_for_driver": totalPassenger.toString(),
+ "price_for_passenger": totalME.toString(),
+ "distance": distance.toString(),
+ "paymentMethod": paymentController.isWalletChecked.toString(),
+ };
+ }
+
+ Future notifyAvailableDrivers() async {
+ int iteration = 0;
+ const maxIterations = 5;
+ const iterationDelay = Duration(seconds: 2);
+
+ while (iteration < maxIterations) {
+ await Future.delayed(iterationDelay);
+ await getCarsLocationByPassengerAndReloadMarker(
+ box.read(BoxName.carType), 3000);
+
+ if (dataCarsLocationByPassenger != null &&
+ dataCarsLocationByPassenger.containsKey('data') &&
+ dataCarsLocationByPassenger['data'] != null) {
+ for (var driverData in dataCarsLocationByPassenger['data']) {
+ String driverId = driverData['driver_id'].toString();
+ if (!notifiedDrivers.contains(driverId)) {
+ notifiedDrivers.add(driverId);
+ double driverLat = double.parse(driverData['latitude']);
+ double driverLng = double.parse(driverData['longitude']);
+ double distanceToDriverInMeters = Geolocator.distanceBetween(
+ passengerLocation.latitude,
+ passengerLocation.longitude,
+ driverLat,
+ driverLng,
+ );
+
+ double distanceToDriverInKm = distanceToDriverInMeters / 1000;
+ double durationToDriverInHours =
+ distanceToDriverInKm / 25; // 25 km/h as default speed
+ double durationToDriverInSeconds = durationToDriverInHours * 3600;
+ durationToPassenger = durationToDriverInSeconds.toInt();
+ distanceByPassenger = distanceToDriverInMeters.toStringAsFixed(0);
+ final body = constructNotificationBody(driverData);
+ Log.print('body:ww ${body}');
+ FirebaseMessagesController().sendNotificationToDriverMAP(
+ 'OrderSpeed',
+ rideId,
+ driverData['token'].toString(),
+ body,
+ 'order.wav');
+ }
+ }
+ }
+ iteration++;
+ }
+ }
+
+ List constructNotificationBody(var driverData) {
+ final paymentController = Get.find();
+ return [
+ '${data[0]['start_location']['lat']},${data[0]['start_location']['lng']}',
+ '${data[0]['end_location']['lat']},${data[0]['end_location']['lng']}',
+ totalPassenger.toStringAsFixed(2),
+ totalDriver.toStringAsFixed(2),
+ durationToRide.toString(),
+ distance.toStringAsFixed(2),
+ driverData['driver_id'].toString(),
+ box.read(BoxName.passengerID).toString(),
+ box.read(BoxName.name).toString(),
+ box.read(BoxName.tokenFCM).toString(),
+ box.read(BoxName.phone).toString(),
+ durationToPassenger.toString(),
+ distanceByPassenger.toString(),
+ paymentController.isWalletChecked.toString(),
+ driverData['token'].toString(),
+ durationToPassenger.toString(),
+ rideId.toString(),
+ rideTimerBegin.toString(),
+ driverData['driver_id'].toString(),
+ durationToRide.toString(),
+ Get.find().wayPoints.length > 1
+ ? 'haveSteps'
+ : 'startEnd',
+ placesCoordinate[0],
+ placesCoordinate[1],
+ placesCoordinate[2],
+ placesCoordinate[3],
+ placesCoordinate[4],
+ costForDriver.toStringAsFixed(2),
+ (double.parse(box.read(BoxName.passengerWalletTotal)) < 0
+ ? double.parse(box.read(BoxName.passengerWalletTotal))
+ .toStringAsFixed(2)
+ : '0'),
+ box.read(BoxName.email).toString(),
+ data[0]['start_address'],
+ data[0]['end_address'],
+ box.read(BoxName.carType),
+ kazan.toStringAsFixed(0),
+ passengerRate.toStringAsFixed(2),
+ ];
+ }
+
+ StreamController _rideStatusStreamController =
+ StreamController.broadcast();
+ Stream get rideStatusStream => _rideStatusStreamController.stream;
+
+ void delayAndFetchRideStatusForAllDriverAvailable(String rideId) {
const int maxAttempts = 15;
int attemptCounter = 0;
bool isApplied = false;
tick = 0;
- bool shouldContinueSearching = true; // Flag to control searching
- void fetchRideStatus() async {
- if (attemptCounter < maxAttempts &&
- !isApplied &&
- shouldContinueSearching) {
- attemptCounter++;
- tick++;
+ Timer.periodic(const Duration(seconds: 1), (timer) async {
+ if (attemptCounter >= maxAttempts || isApplied) {
+ timer.cancel();
+ _rideStatusStreamController.close(); // Close the stream when done
+ return;
+ }
+
+ attemptCounter++;
+ tick++;
+
+ try {
var res = await getRideStatus(rideId);
String rideStatusDelayed = res.toString();
-
+ addRideToNotificationDriverString();
+ _rideStatusStreamController
+ .add(rideStatusDelayed); // Emit the ride status
+ // addRideToNotificationDriverString();
if (rideStatusDelayed == 'Cancel') {
- shouldContinueSearching = false; // Stop searching
- attemptCounter = maxAttempts + 1;
+ timer.cancel();
NotificationController().showNotification(
"Order Cancelled".tr, "you canceled order".tr, 'ding');
+ _rideStatusStreamController
+ .close(); // Close stream after cancellation
} else if (rideStatusDelayed == 'Apply' ||
rideStatusDelayed == 'Applied') {
await getUpdatedRideForDriverApply(rideId);
@@ -1997,8 +2032,19 @@ class MapPassengerController extends GetxController {
'Order Accepted'.tr,
'$driverName ${'accepted your order at price'.tr} ${totalPassenger.toStringAsFixed(1)} ${'with type'.tr} ${box.read(BoxName.carType)}',
'ding');
+ if (box.read(BoxName.carType) == 'Speed' ||
+ box.read(BoxName.carType) == 'Awfar Car') {
+ NotificationController().showNotification(
+ 'The captain is responsible for the route.'.tr,
+ 'This price is fixed even if the route changes for the driver.'
+ .tr,
+ 'ding');
+ } else if (box.read(BoxName.carType) == 'Comfort' ||
+ box.read(BoxName.carType) == 'Lady') {
+ NotificationController().showNotification('Attention'.tr,
+ 'The price may increase if the route changes.'.tr, 'ding');
+ }
isApplied = true;
- shouldFetch = false;
statusRide = 'Apply';
rideConfirm = false;
isSearchingWindow = false;
@@ -2006,26 +2052,42 @@ class MapPassengerController extends GetxController {
startTimer();
update();
startTimerFromDriverToPassengerAfterApplied();
- shouldContinueSearching = false; // Stop searching if applied
+
+ timer.cancel();
+ _rideStatusStreamController.close(); // Close stream after applying
} else if (attemptCounter >= maxAttempts &&
rideStatusDelayed != 'Cancel') {
- shouldContinueSearching = false; // Stop searching
+ timer.cancel();
+ // addRideToNotificationDriverString();
// Show dialog to increase fee...
update();
- } else {
- Timer(const Duration(seconds: 2), fetchRideStatus);
+ _rideStatusStreamController
+ .close(); // Close stream after max attempts
}
+ } catch (e) {
+ _rideStatusStreamController.addError(e); // Handle errors in the stream
}
- }
+ });
+ }
- fetchRideStatus(); // Initial call to start the process
+// Listening to the Stream
+ void listenToRideStatusStream() {
+ rideStatusStream.listen((rideStatus) {
+ print("Ride Status: $rideStatus");
+ // Handle updates based on the ride status
+ }, onError: (error) {
+ print("Error in Ride Status Stream: $error");
+ // Handle stream errors
+ }, onDone: () {
+ print("Ride status stream closed.");
+ });
}
reSearchAfterCanceledFromDriver() async {
await getCarsLocationByPassengerAndReloadMarker(
box.read(BoxName.carType), 3000);
- confirmRideForAllDriverAvailable();
+ updateConfirmRideForAllDriverAvailable();
shouldFetch = true; // Stop further fetches
statusRide = 'wait';
rideConfirm = true;
@@ -2089,20 +2151,22 @@ class MapPassengerController extends GetxController {
driverPhone = response['data']['phone'];
driverCarMake = response['data']['make'];
model = response['data']['model'];
+ colorHex = response['data']['color_hex'];
+ carColor = response['data']['color'];
make = response['data']['make'];
licensePlate = response['data']['car_plate'];
- firstName = response['data']['first_name'];
- driverName = response['data']['driverName'].toString().split(' ')[0];
+ passengerName = response['data']['passengerName'];
+ driverName = response['data']['driverName'].toString();
driverToken = response['data']['token'];
- Log.print('driverToken updated: $driverToken');
+ // Log.print('driverToken updated: $driverToken');
carYear = response['data']['year'];
driverRate = response['data']['ratingDriver'].toString();
}
// driversToken.remove(driverToken);
// for (var i = 1; i < driversToken.length; i++) {
FirebaseMessagesController().sendNotificationToDriverMAP(
- 'Order Applied'.tr,
- '$driverName Apply order\nTake attention in other order'.tr,
+ 'Order Accepted'.tr,
+ '$driverName${'Accepted your order'.tr}',
driverToken.toString(),
[],
'start.wav',
@@ -2428,10 +2492,11 @@ class MapPassengerController extends GetxController {
} else {
noCarString = false;
dataCarsLocationByPassenger = jsonDecode(res);
+ Log.print('dataCarsLocationByPassenger: ${dataCarsLocationByPassenger}');
// Check if 'message' is present and not null
- if (dataCarsLocationByPassenger['message'] != null &&
- dataCarsLocationByPassenger['message'].isNotEmpty) {
+ if (dataCarsLocationByPassenger['data'] != null &&
+ dataCarsLocationByPassenger['data'].isNotEmpty) {
// Check if carsOrder is within bounds
// if (carsOrder < dataCarsLocationByPassenger['message'].length) {
// driverId = dataCarsLocationByPassenger['message'][carsOrder]
@@ -2454,8 +2519,8 @@ class MapPassengerController extends GetxController {
carsLocationByPassenger.clear(); // Clear existing markers
- for (var i = 0; i < dataCarsLocationByPassenger['message'].length; i++) {
- var json = dataCarsLocationByPassenger['message'][i];
+ for (var i = 0; i < dataCarsLocationByPassenger['data'].length; i++) {
+ var json = dataCarsLocationByPassenger['data'][i];
_updateOrCreateMarker(
MarkerId(json['latitude']).toString(),
LatLng(
@@ -3175,23 +3240,101 @@ class MapPassengerController extends GetxController {
update();
}
- Future getPlaces() async {
+// Future getPlaces() async {
+// var languageCode;
+
+// // Check if `placeDestinationController.text` contains English characters
+// if (RegExp(r'[a-zA-Z]').hasMatch(placeDestinationController.text)) {
+// languageCode = 'en';
+// } else {
+// languageCode = 'ar';
+// }
+// var url =
+// '${AppLink.searcMaps}?q=${placeDestinationController.text}&in=circle:${passengerLocation.latitude},${passengerLocation.longitude};r=250000&countryCode=${box.read(BoxName.countryCode) == 'EGYPT' ? 'EGY' : 'JOR'}&apiKey=${AK.apiKeyHere}';
+// // '${AppLink.googleMapsLink}place/nearbysearch/json?location=${mylocation.longitude}&radius=25000&language=ar&keyword=&key=${placeController.text}${AK.mapAPIKEY}';
+// // '${AppLink.googleMapsLink}place/nearbysearch/json?keyword=${placeDestinationController.text}&location=${passengerLocation.latitude},${passengerLocation.longitude}&radius=250000&language=$languageCode&key=${AK.mapAPIKEY.toString()}';
+// print(url);
+// var response = await CRUD().getGoogleApi(link: url, payload: {});
+// Log.print('response: ${response}');
+
+// placesDestination = response['results'];
+// update();
+// }
+ getAIKey(String key) async {
+ var res =
+ await CRUD().get(link: AppLink.getapiKey, payload: {"keyName": key});
+ if (res != 'failure') {
+ var d = jsonDecode(res)['message'];
+ return d[key].toString();
+ } else {}
+ }
+
+ Future getPlaces() async {
var languageCode;
-// Check if `placeDestinationController.text` contains English characters
+ // Check if `placeDestinationController.text` contains English characters
if (RegExp(r'[a-zA-Z]').hasMatch(placeDestinationController.text)) {
languageCode = 'en';
} else {
languageCode = 'ar';
}
- var url =
- // '${AppLink.googleMapsLink}place/nearbysearch/json?location=${mylocation.longitude}&radius=25000&language=ar&keyword=&key=${placeController.text}${AK.mapAPIKEY}';
- '${AppLink.googleMapsLink}place/nearbysearch/json?keyword=${placeDestinationController.text}&location=${passengerLocation.latitude},${passengerLocation.longitude}&radius=250000&language=$languageCode&key=${AK.mapAPIKEY.toString()}';
- print(url);
- var response = await CRUD().getGoogleApi(link: url, payload: {});
- Log.print('response: ${response}');
- placesDestination = response['results'];
+ // Construct the URL
+ var url = Uri.parse(
+ '${AppLink.searcMaps}?q=${Uri.encodeQueryComponent(placeDestinationController.text)}&limit=4&in=circle:${passengerLocation.latitude},${passengerLocation.longitude};r=250000&countryCode=${box.read(BoxName.countryCode) == 'EGYPT' ? 'EGY' : 'JOR'}&lang=$languageCode&apiKey=$k',
+ );
+
+ // Log the URL for debugging
+ print(url);
+ // box.remove(BoxName.placesDestination);
+ try {
+ // Make the API request
+ var response = await CRUD().getHereMap(
+ link: url.toString(),
+ );
+
+ // Log the response for debugging
+ // Log.print('response: ${response}');
+
+ // Check if the response is valid
+ if (response != null && response['items'] != null) {
+ placesDestination = response['items'];
+ // Log.print('placesDestination: ${placesDestination}');
+
+ placesDestination = response['items'];
+ // box.write(BoxName.placesDestination, placesDestination);
+ for (var i = 0; i < placesDestination.length; i++) {
+ var res = placesDestination[i];
+
+ // Extract fields with null safety
+ var title = res['title']?.toString() ?? 'Unknown Place';
+ var position = res['position'];
+ var address = res['address']?['label'] ?? 'Unknown Address';
+ if (position == null) {
+ Log.print('Position is null for place: $title');
+ continue; // Skip this place and continue with the next one
+ }
+
+ String latitude = position['lat']?.toString() ?? '0.0';
+ String longitude = position['lng']?.toString() ?? '0.0';
+
+ try {
+ await savePlaceToServer(latitude, longitude, title, address);
+ // Log.print('Place saved successfully: $title');
+ } catch (e) {
+ // Log.print('Failed to save place: $e');
+ }
+ } // todo save key in env then get key and use it
+ } else {
+ placesDestination = [];
+ }
+ } catch (e) {
+ // Handle any errors that occur during the API request
+ Log.print('Error fetching places: $e');
+ placesDestination = [];
+ }
+
+ // Notify listeners that the state has changed
update();
}
@@ -3248,6 +3391,25 @@ class MapPassengerController extends GetxController {
print('Error fetching places: $e');
}
}
+
+ Future savePlaceToServer(
+ String latitude, String longitude, String name, String rate) async {
+ var data = {
+ 'latitude': latitude,
+ 'longitude': longitude,
+ 'name': name,
+ 'rate': rate,
+ };
+
+ try {
+ CRUD().post(
+ link: AppLink.savePlacesServer,
+ payload: data,
+ );
+ } catch (e) {
+ print('Error: $e');
+ }
+ }
// Future getPlacesListsWayPoint(int index) async {
// var url =
// '${AppLink.googleMapsLink}place/nearbysearch/json?keyword=${wayPoint0Controller.text}&location=${passengerLocation.latitude},${passengerLocation.longitude}&radius=80000&language=${}&key=${AK.mapAPIKEY.toString()}';
@@ -3521,7 +3683,7 @@ class MapPassengerController extends GetxController {
int reloadCount = 0;
startMarkerReloading() async {
if (reloadStartApp == false) {
- Timer.periodic(const Duration(seconds: 5), (timer) async {
+ Timer.periodic(const Duration(seconds: 3), (timer) async {
reloadCount++;
Log.print('reloadCount: $reloadCount');
@@ -3530,7 +3692,7 @@ class MapPassengerController extends GetxController {
// _smoothlyUpdateMarker();
// startCarLocationSearch(box.read(BoxName.carType));
await getCarsLocationByPassengerAndReloadMarker(
- box.read(BoxName.carType), 6000);
+ box.read(BoxName.carType), 5000);
await getNearestDriverByPassengerLocation();
Log.print('reloadMarkers: from startMarkerReloading');
} else {
@@ -3613,26 +3775,19 @@ class MapPassengerController extends GetxController {
// return null;
// }
Future getNearestDriverByPassengerLocation() async {
- // if (polyLines.isEmpty && data.isEmpty) {
- // return null; // Early return if data is empty
- // }
- // Log.print('rideConfirm: ${rideConfirm}');
- // Log.print('dataCarsLocationByPassenger: ${dataCarsLocationByPassenger}');
if (!rideConfirm) {
- if (dataCarsLocationByPassenger != 'failure') {
- if (dataCarsLocationByPassenger != null &&
- dataCarsLocationByPassenger['message'] != null &&
- dataCarsLocationByPassenger['message'].length > 0) {
- double nearestDistance =
- double.infinity; // Initialize nearest distance
- CarLocation? nearestCar;
+ if (dataCarsLocationByPassenger != 'failure' &&
+ dataCarsLocationByPassenger != null &&
+ dataCarsLocationByPassenger['data'] != null &&
+ dataCarsLocationByPassenger['data'].length > 0) {
+ double nearestDistance = double.infinity; // Initialize nearest distance
+ CarLocation? nearestCar;
- for (var i = 0;
- i < dataCarsLocationByPassenger['message'].length;
- i++) {
- var carLocation = dataCarsLocationByPassenger['message'][i];
- Log.print('carLocation: $carLocation');
+ for (var i = 0; i < dataCarsLocationByPassenger['data'].length; i++) {
+ var carLocation = dataCarsLocationByPassenger['data'][i];
+ Log.print('carLocation: $carLocation');
+ try {
// Calculate distance between passenger's location and current driver's location
final distance = Geolocator.distanceBetween(
passengerLocation.latitude,
@@ -3642,10 +3797,13 @@ class MapPassengerController extends GetxController {
);
// Calculate duration assuming an average speed of 25 km/h (adjust as needed)
- int durationToPassenger = (distance * 25 * (1000 / 3600)).round();
+ int durationToPassenger = (distance / 1000 / 25 * 3600).round();
Log.print('distance: $distance');
Log.print('durationToPassenger: $durationToPassenger');
-
+ Log.print('passengerLocation: $passengerLocation');
+ Log.print('carLocation: $carLocation');
+ Log.print('distance: $distance meters');
+ Log.print('durationToPassenger: $durationToPassenger seconds');
// Update the UI with the distance and duration for each car
update();
@@ -3664,11 +3822,13 @@ class MapPassengerController extends GetxController {
// Update the UI with the nearest driver
update();
}
+ } catch (e) {
+ Log.print('Error calculating distance/duration: $e');
}
-
- // Return the nearest car found
- return nearestCar;
}
+
+ // Return the nearest car found
+ return nearestCar;
}
}
@@ -4728,7 +4888,7 @@ class MapPassengerController extends GetxController {
'address': driver['address'],
'religion': driver['religion'] ?? 'UnKnown',
'age': driver['age'].toString(), // Convert age to String
- 'education': driver['education'] ?? 'UnKnown',
+ 'education': driver['education'] ?? 'UnKnown', //startlocationname
'license_type': driver['license_type'] ?? 'UnKnown',
'national_number': driver['national_number'] ?? 'UnKnown',
'car_plate': driver['car_plate'],
@@ -4746,6 +4906,9 @@ class MapPassengerController extends GetxController {
'passengerId': box.read(BoxName.passengerID),
'timeSelected': tripDateTime.toIso8601String(),
'status': 'pending',
+ 'startNameAddress': startNameAddress.toString(),
+ 'locationCoordinate':
+ '${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
};
Log.print('tripData: $tripData');
@@ -4828,8 +4991,10 @@ class MapPassengerController extends GetxController {
driver['token'].toString(),
[
id,
+ rideId,
driver['id'],
passengerLocation.latitude.toString(),
+ startNameAddress.toString(),
passengerLocation.longitude.toString(),
box.read(BoxName.name).toString(),
box.read(BoxName.passengerID).toString(),
@@ -4904,11 +5069,17 @@ class MapPassengerController extends GetxController {
}
late List recentPlaces = [];
- getFavioratePlaces() async {
+ getFavioratePlaces0() async {
recentPlaces = await sql.getCustomQuery(
'SELECT DISTINCT latitude, longitude, name, rate FROM ${TableName.recentLocations}');
}
+ getFavioratePlaces() async {
+ recentPlaces = await sql.getCustomQuery(
+ 'SELECT * FROM ${TableName.recentLocations} ORDER BY createdAt DESC');
+ // Log.print('recentPlaces: ${recentPlaces}');
+ }
+
double passengerRate = 5;
double comfortPrice = 8;
double speedPrice = 4;
@@ -4990,9 +5161,11 @@ class MapPassengerController extends GetxController {
}
}
+ var k;
@override
void onInit() async {
mapAPIKEY = await storage.read(key: BoxName.mapAPIKEY);
+ k = await getAIKey('HERE_API');
getFavioratePlaces();
readyWayPoints();
addCustomPicker();
diff --git a/lib/controller/home/vip_waitting_page.dart b/lib/controller/home/vip_waitting_page.dart
index 9cc1287..7990458 100644
--- a/lib/controller/home/vip_waitting_page.dart
+++ b/lib/controller/home/vip_waitting_page.dart
@@ -58,15 +58,15 @@ class VipOrderController extends GetxController {
tripData.value = decodedResponse['message'];
} else {
tripData.clear(); // Ensure empty list if no data
- mySnackeBarError('No trip data found');
+ // mySnackeBarError('No trip data found');
}
} else {
tripData.clear();
- mySnackeBarError('Failed to fetch trip data');
+ // mySnackeBarError('Failed to fetch trip data');
}
} catch (e) {
tripData.clear();
- mySnackeBarError('An error occurred: $e');
+ // mySnackeBarError('An error occurred: $e');
} finally {
isLoading.value = false;
}
diff --git a/lib/controller/local/translations.dart b/lib/controller/local/translations.dart
index ba8998e..6bfd249 100644
--- a/lib/controller/local/translations.dart
+++ b/lib/controller/local/translations.dart
@@ -4,6 +4,13 @@ class MyTranslation extends Translations {
@override
Map> get keys => {
"ar": {
+ "Home Page": "الصفحة الرئيسية",
+ "To change Language the App": "لتغيير لغة التطبيق",
+ "Learn more about our app and mission":
+ "تعرف على المزيد حول تطبيقنا ورسالتنا",
+ "Promos For Today": "عروض اليوم",
+ 'Bonus gift': 'بونص', "Pay": "ادفع",
+ "Get": "احصل على",
"Send to Driver Again": "إرسال إلى السائق مرة أخرى",
"Driver Name:": "اسم السائق:",
'No trip data available': "لا توجد بيانات رحلة متاحة",
@@ -79,6 +86,7 @@ class MyTranslation extends Translations {
"Pick from map destination": "حدد وجهتك على الخريطة",
"Pick or Tap to confirm": "حدد أو انقر للتأكيد",
"Select Order Type": "حدد نوع الطلب",
+ 'Accepted your order': "تم قبول طلبك",
"Choose who this order is for": "اختر لمن هذا الطلب",
"Order Accepted": "تم قبول الطلب", "with type": "مع النوع",
"accepted your order at price": "قبل طلبك بالسعر",
@@ -473,7 +481,7 @@ iOS [https://getapp.cc/app/6458734951]
"Go to this Target": "الانْتِقَال إِلَى هَذَا الهَدَف",
"My Profile": "مَلَفِي الشَّخْصِي",
"Sign Out": "تَسْجِيل الخُرُوج",
- "Home Page": "الصَّفْحَة الرَّئِيسِيَّة",
+
"Are you want to go to this site":
"هَل تَرْغَب فِي الانْتِقَال إِلَى هَذَا المَوْقِع",
"MyLocation": "مَوْقِعِي",
@@ -550,11 +558,11 @@ iOS [https://getapp.cc/app/6458734951]
"Bachelor's Degree": "بَكَالُورِيُوس",
"Master's Degree": "مَاجِسْتِير",
"Doctoral Degree": "دُكْتُورَاه",
- "Promos For today": "الْعُرُوض التَّرْوِيجِيَّة لِلْيَوْم",
+
"Copy this Promo to use it in your Ride!":
"انْسَخْ هَذَا الْعَرْض لِاسْتِخْدَامِهِ فِي رِحْلَتِك!",
"To change some Settings": "لِتَغْيِير بَعْض الإِعْدَادَات",
- "To change Language the App": "لِتَغْيِير لُغَة التَّطْبِيق",
+
"Order Request Page": "صَفْحَة طَلَب الطَّلَب",
"Rouats of Trip": "طُرُق الرِّحْلَة",
"Passenger Name is ": "اسْم الرَّاكِب هُوَ ",
@@ -607,6 +615,24 @@ iOS [https://getapp.cc/app/6458734951]
"Do you want to pay Tips for this Driver":
"هَل تُرِيد دَفْع أُكْرَامِيَّة لِهَذَا السَّائِق؟",
"Tip is ": " مَبْلَغ الأُكْرَامِيَّة هُوَ",
+ "Are you sure to delete this location?":
+ "هل أنت متأكد من حذف هذا الموقع؟",
+ "deleted": "تم الحذف",
+ 'Trip is begin': "الرحلة قد بدأت",
+ 'This price is fixed even if the route changes for the driver.':
+ "هذا السعر مثبت حتى لو تغير المسار للسائق",
+ 'The price may increase if the route changes.':
+ "احتمالية زيادة السعر عند تغيير المسار",
+ "The captain is responsible for the route.":
+ "الكابتن مسؤول عن المسار",
+ "يمكنك الاتصال أو تسجيل صوت لهذه الرحلة":
+ "You can call or record audio of this trip",
+
+ 'The trip has started! Feel free to contact emergency numbers, share your trip, or activate voice recording for the journey':
+ "بدأت الرحلة! لا تتردد في الاتصال بأرقام الطوارئ، مشاركة رحلتك، أو تفعيل التسجيل الصوتي للرحلة",
+ 'Please make sure you have all your personal belongings and that any remaining fare, if applicable, has been added to your wallet before leaving. Thank you for choosing the Sefer app':
+ 'الرجاء التأكد من جميع أغراضك الشخصية وأنه تم إضافة باقي الأجرة إن وجد إلى محفظتك قبل النزول. شكرا لاختيارك تطبيق سفر',
+ 'Don’t forget your personal belongings.': "لا تنسى متعلقاتك الشخصية",
"Tip is": " مَبْلَغ الأُكْرَامِيَّة هُوَ",
"Camera Access Denied.": "تَمَّ رَفْض الْوُصُول إِلَى الْكَامِيرَا.",
"Open Settings": "افْتَحْ الإِعْدَادَات",
diff --git a/lib/controller/payment/payment_controller.dart b/lib/controller/payment/payment_controller.dart
index 44b1eb7..b4dde90 100644
--- a/lib/controller/payment/payment_controller.dart
+++ b/lib/controller/payment/payment_controller.dart
@@ -700,8 +700,9 @@ class PaymentController extends GetxController {
);
// Log.print('response.message!: ${response!.responseCode!}');
// if (response!.success == true && response.responseCode == '200') {
- if (response!.responseCode.toString() == '200' &&
- response.success == true) {
+
+ if (response!.success == true &&
+ response!.message.toString() == 'Approved') {
// Log.print('transactionID wewer: ${response.transactionID}');
Toast.show(context, 'Payment Successful'.tr, AppColor.greenColor);
method();
diff --git a/lib/controller/rate/rate_conroller.dart b/lib/controller/rate/rate_conroller.dart
index 32f2b90..4d5ef26 100644
--- a/lib/controller/rate/rate_conroller.dart
+++ b/lib/controller/rate/rate_conroller.dart
@@ -81,34 +81,28 @@ class RateController extends GetxController {
}
}
await CRUD().post(
- link: "${AppLink.seferCairoServer}/rate/addRateToDriver.php",
+ link: "${AppLink.seferCairoServer}/ride/rate/addRateToDriver.php",
payload: {
'passenger_id': box.read(BoxName.passengerID).toString(),
- 'driver_id': driverId,
- 'ride_id': rideId,
+ 'driver_id': driverId.toString(),
+ 'ride_id': rideId.toString(),
'rating': selectedRateItemId.toString(),
'comment': comment.text,
- }).then((value) {
+ });
+
+ if (AppLink.endPoint != AppLink.seferCairoServer) {
CRUD().post(
- link: "${AppLink.seferAlexandriaServer}/rate/addRateToDriver.php",
+ link: "${AppLink.endPoint}/ride/rate/addRateToDriver.php",
payload: {
'passenger_id': box.read(BoxName.passengerID).toString(),
- 'driver_id': driverId,
- 'ride_id': rideId,
+ 'driver_id': driverId.toString(),
+ 'ride_id': rideId.toString(),
'rating': selectedRateItemId.toString(),
'comment': comment.text,
});
- CRUD().post(
- link: "${AppLink.seferGizaServer}/rate/addRateToDriver.php",
- payload: {
- 'passenger_id': box.read(BoxName.passengerID).toString(),
- 'driver_id': driverId,
- 'ride_id': rideId,
- 'rating': selectedRateItemId.toString(),
- 'comment': comment.text,
- });
- Get.find().restCounter();
- Get.offAll(const MapPagePassenger());
- });
+ }
+
+ Get.find().restCounter();
+ Get.offAll(const MapPagePassenger());
}
}
diff --git a/lib/models/db_sql.dart b/lib/models/db_sql.dart
index 0caa829..4178e68 100644
--- a/lib/models/db_sql.dart
+++ b/lib/models/db_sql.dart
@@ -37,18 +37,21 @@ class DbSql {
latitude REAL,
longitude REAL,
name TEXT UNIQUE,
- rate TEXT
+ rate TEXT,
+ createdAt TEXT
)
''');
+ await db.execute('DROP TABLE IF EXISTS ${TableName.recentLocations}');
await db.execute('''
- CREATE TABLE IF NOT EXISTS ${TableName.recentLocations}(
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- latitude REAL,
- longitude REAL,
- name TEXT ,
- rate TEXT
- )
- ''');
+ CREATE TABLE ${TableName.recentLocations}(
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ latitude REAL,
+ longitude REAL,
+ name TEXT,
+ rate TEXT,
+ createdAt TEXT
+ )
+''');
await db.execute('''
CREATE TABLE IF NOT EXISTS ${TableName.driverOrdersRefuse}(
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -97,6 +100,34 @@ class DbSql {
return await db.insert(table, map);
}
+ Future insertMapLocation(Map map, String table) async {
+ Database db = await instance.database;
+
+ // Check if the record already exists (based on latitude, longitude, and name)
+ var existing = await db.query(
+ table,
+ where: 'latitude = ? AND longitude = ? AND name = ?',
+ whereArgs: [map['latitude'], map['longitude'], map['name']],
+ );
+
+ if (existing.isNotEmpty) {
+ // If record exists, update the createdAt field with the current timestamp
+ var updatedMap = Map.from(map);
+ updatedMap['createdAt'] =
+ DateTime.now().toIso8601String(); // Update timestamp
+ return await db.update(
+ table,
+ updatedMap,
+ where: 'id = ?',
+ whereArgs: [existing.first['id']], // Update the existing row
+ );
+ } else {
+ // If record doesn't exist, insert new record with the current timestamp
+ map['createdAt'] = DateTime.now().toIso8601String();
+ return await db.insert(table, map);
+ }
+ }
+
Future updateData(Map map, String table, int id) async {
Database db = await instance.database;
diff --git a/lib/views/Rate/rate_captain.dart b/lib/views/Rate/rate_captain.dart
index b680eb3..e3be4bd 100644
--- a/lib/views/Rate/rate_captain.dart
+++ b/lib/views/Rate/rate_captain.dart
@@ -40,7 +40,7 @@ class RateDriverFromPassenger extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
- '${'Total price to '.tr}${Get.find().firstName}',
+ '${'Total price to '.tr}${Get.find().driverName}',
style: AppStyle.title,
),
Row(
diff --git a/lib/views/auth/login_page.dart b/lib/views/auth/login_page.dart
index b4d6405..8cceb25 100644
--- a/lib/views/auth/login_page.dart
+++ b/lib/views/auth/login_page.dart
@@ -12,6 +12,7 @@ import 'package:SEFER/constant/style.dart';
import 'package:SEFER/main.dart';
import 'package:SEFER/views/widgets/elevated_btn.dart';
import 'package:SEFER/views/widgets/my_scafold.dart';
+import 'package:permission_handler/permission_handler.dart';
import '../../constant/info.dart';
import '../../controller/auth/apple_signin_controller.dart';
@@ -456,6 +457,16 @@ class LoginPage extends StatelessWidget {
textAlign: TextAlign.center,
style: AppStyle.title,
),
+ TextButton(
+ onPressed: () {
+ // Optionally, navigate to app settings for manual permission control
+ openAppSettings();
+ },
+ child: Text(
+ "Open Settings".tr,
+ style: const TextStyle(color: AppColor.blueColor),
+ ),
+ ),
MyElevatedButton(
title: 'Next'.tr,
onPressed: () async {
diff --git a/lib/views/home/HomePage/contact_us.dart b/lib/views/home/HomePage/contact_us.dart
index 58a104c..e7012dc 100644
--- a/lib/views/home/HomePage/contact_us.dart
+++ b/lib/views/home/HomePage/contact_us.dart
@@ -23,9 +23,9 @@ class ContactUsPage extends StatelessWidget {
body: [
Padding(
padding: const EdgeInsets.all(8.0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.center,
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ child: ListView(
+ // crossAxisAlignment: CrossAxisAlignment.center,
+ // mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
decoration: AppStyle.boxDecoration1,
diff --git a/lib/views/home/home_page.dart b/lib/views/home/home_page.dart
index 9c58f41..3b9949d 100644
--- a/lib/views/home/home_page.dart
+++ b/lib/views/home/home_page.dart
@@ -1,10 +1,8 @@
import 'package:SEFER/controller/home/home_page_controller.dart';
+import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
-import 'package:SEFER/constant/colors.dart';
-import 'package:SEFER/constant/style.dart';
import 'package:SEFER/views/lang/languages.dart';
-import 'package:SEFER/views/widgets/my_scafold.dart';
import 'HomePage/about_page.dart';
import 'HomePage/frequentlyQuestionsPage.dart';
@@ -18,121 +16,108 @@ class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
Get.put(HomePageController());
- return MyScafolld(
- isleading: true,
- title: 'Home Page'.tr,
- body: [
- ListView(
+ return CupertinoPageScaffold(
+ navigationBar: CupertinoNavigationBar(
+ middle: Text('Home Page'.tr),
+ leading: CupertinoButton(
+ padding: EdgeInsets.zero,
+ child: const Icon(CupertinoIcons.back),
+ onPressed: () {
+ Navigator.pop(context);
+ },
+ ),
+ ),
+ child: SafeArea(
+ child: ListView(
children: [
- ListTile(
+ CupertinoListTile(
onTap: () {
Get.to(() => const Language());
},
- title: Text(
- 'Language'.tr,
- style: AppStyle.headTitle2,
- ),
- subtitle: Text(
- 'To change Language the App'.tr,
- style: AppStyle.title,
- ),
- trailing: const Icon(
- Icons.arrow_forward_ios,
- size: 30,
- color: AppColor.primaryColor,
- ),
- leading: const Icon(
- Icons.language_sharp,
- color: AppColor.primaryColor,
- ),
+ leading: const Icon(CupertinoIcons.globe,
+ color: CupertinoColors.activeBlue),
+ title: Text('Language'.tr),
+ subtitle: Text('To change Language the App'.tr),
+ trailing: const CupertinoListTileChevron(),
),
- ListTile(
- leading: const Icon(Icons.location_city_outlined),
- title: Text(
- 'Change Country'.tr,
- style: AppStyle.headTitle2,
- ),
- subtitle: Text(
- 'You can change the Country to get all features'.tr,
- style: AppStyle.title,
- ),
- onTap: () => Get.to(MyScafolld(
- title: 'Change Country'.tr,
- body: [CountryPickerFromSetting()],
- isleading: true)),
- ),
- ListTile(
- leading: const Icon(Icons.question_answer),
- title: Text(
- 'Frequently Questions'.tr,
- style: AppStyle.headTitle2,
- ),
- subtitle: Text(
- 'You can change the Country to get all features'.tr,
- style: AppStyle.title,
- ),
- onTap: () => Get.to(() => const FrequentlyQuestionsPage()),
- ),
- ListTile(
- leading: const Icon(Icons.vibration),
- title: GetBuilder(builder: (controller) {
- return SwitchListTile(
- title: Text(
- 'Vibration'.tr,
- style: AppStyle.headTitle2,
+ CupertinoListTile(
+ onTap: () {
+ Get.to(CupertinoPageScaffold(
+ navigationBar: CupertinoNavigationBar(
+ middle: Text('Change Country'.tr),
),
- value: controller.isVibrate,
- onChanged: controller.changeVibrateOption,
- activeColor: AppColor.primaryColor,
- );
- }),
- subtitle: Text(
- "You can change the vibration feedback for all buttons".tr,
- style: AppStyle.title,
- ),
- onTap: () => Get.to(() => const FrequentlyQuestionsPage()),
+ child: SafeArea(
+ child: CountryPickerFromSetting(),
+ ),
+ ));
+ },
+ leading: const Icon(CupertinoIcons.location,
+ color: CupertinoColors.activeBlue),
+ title: Text('Change Country'.tr),
+ subtitle:
+ Text('You can change the Country to get all features'.tr),
+ trailing: const CupertinoListTileChevron(),
),
- ListTile(
- leading: const Icon(Icons.record_voice_over_outlined),
- title: Text(
- 'Trips recorded'.tr,
- style: AppStyle.headTitle2,
- ),
- subtitle: Text(
- 'Here recorded trips audio'.tr,
- style: AppStyle.title,
- ),
- onTap: () async {
- Get.to(() => TripsRecordedPage());
- }),
- ListTile(
- leading: const Icon(Icons.account_balance_outlined),
- title: Text(
- 'About Us'.tr,
- style: AppStyle.headTitle2,
- ),
- subtitle: Text(
- 'You can change the Country to get all features'.tr,
- style: AppStyle.title,
- ),
- onTap: () => Get.to(() => const AboutPage()),
+ CupertinoListTile(
+ onTap: () {
+ Get.to(() => const FrequentlyQuestionsPage());
+ },
+ leading: const Icon(CupertinoIcons.question,
+ color: CupertinoColors.activeBlue),
+ title: Text('Frequently Questions'.tr),
+ subtitle: Text('Find answers to common questions'.tr),
+ trailing: const CupertinoListTileChevron(),
),
- ListTile(
- leading: const Icon(Icons.share),
- title: Text(
- 'Share App'.tr,
- style: AppStyle.headTitle2,
+ CupertinoListTile(
+ leading: const Icon(Icons.vibration,
+ color: CupertinoColors.activeBlue),
+ title: Text('Vibration'.tr),
+ trailing: GetBuilder(
+ builder: (controller) {
+ return CupertinoSwitch(
+ value: controller.isVibrate,
+ onChanged: controller.changeVibrateOption,
+ );
+ },
),
subtitle: Text(
- 'You can share the SEFER App with your friends and earn rewards for rides they take using your code'
- .tr,
- style: AppStyle.title,
- ),
- onTap: () => Get.to(() => ShareAppPage()),
+ 'You can change the vibration feedback for all buttons'.tr),
+ ),
+ CupertinoListTile(
+ onTap: () {
+ Get.to(() => const TripsRecordedPage());
+ },
+ leading: const Icon(CupertinoIcons.mic_circle,
+ color: CupertinoColors.activeBlue),
+ title: Text('Trips recorded'.tr),
+ subtitle: Text('Here recorded trips audio'.tr),
+ trailing: const CupertinoListTileChevron(),
+ ),
+ CupertinoListTile(
+ onTap: () {
+ Get.to(() => const AboutPage());
+ },
+ leading: const Icon(CupertinoIcons.info_circle,
+ color: CupertinoColors.activeBlue),
+ title: Text('About Us'.tr),
+ subtitle: Text('Learn more about our app and mission'.tr),
+ trailing: const CupertinoListTileChevron(),
+ ),
+ CupertinoListTile(
+ onTap: () {
+ Get.to(() => ShareAppPage());
+ },
+ leading: const Icon(CupertinoIcons.share,
+ color: CupertinoColors.activeBlue),
+ title: Text('Share App'.tr),
+ subtitle: Text(
+ 'You can share the SEFER App with your friends and earn rewards for rides they take using your code'
+ .tr),
+ trailing: const CupertinoListTileChevron(),
),
],
),
- ],
+ ),
);
}
}
diff --git a/lib/views/home/map_page_passenger.dart b/lib/views/home/map_page_passenger.dart
index 3c251df..040f669 100644
--- a/lib/views/home/map_page_passenger.dart
+++ b/lib/views/home/map_page_passenger.dart
@@ -66,6 +66,7 @@ class MapPagePassenger extends StatelessWidget {
const RideBeginPassenger(),
const VipRideBeginPassenger(),
const RideFromStartApp(),
+
cancelRidePage(),
const MenuIconMapPageWidget(),
PointsPageForRider()
@@ -85,7 +86,7 @@ class CancelRidePageShow extends StatelessWidget {
Widget build(BuildContext context) {
return GetBuilder(
builder: (controller) =>
- (controller.data.isNotEmpty && controller.remainingTime > 0)
+ (controller.data.isNotEmpty && controller.statusRide != 'Begin')
// ||
// controller.timeToPassengerFromDriverAfterApplied == 0
? Positioned(
diff --git a/lib/views/home/map_widget.dart/apply_order_widget.dart b/lib/views/home/map_widget.dart/apply_order_widget.dart
index 1f61c68..2a974d8 100644
--- a/lib/views/home/map_widget.dart/apply_order_widget.dart
+++ b/lib/views/home/map_widget.dart/apply_order_widget.dart
@@ -17,6 +17,21 @@ class ApplyOrderWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
+ Color _parseColor(String colorHex) {
+ if (colorHex.isEmpty) {
+ return Colors.grey; // Fallback for empty color
+ }
+
+ // Ensure the string starts with '0xff' for ARGB format
+ String processedHex = colorHex.replaceFirst('#', '0xff').trim();
+
+ if (!processedHex.startsWith('0xff')) {
+ processedHex = '0xff$processedHex'; // Add '0xff' if missing
+ }
+
+ return Color(int.parse(processedHex));
+ }
+
return GetBuilder(builder: (controller) {
if (controller.statusRide == 'Apply' &&
controller.isSearchingWindow == false) {
@@ -108,36 +123,43 @@ class ApplyOrderWidget extends StatelessWidget {
],
),
Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
- Image.asset(
- box.read(BoxName.carType) == 'Comfort'
- ? 'assets/images/blob.png'
- : box.read(BoxName.carType) == 'Lady'
- ? 'assets/images/lady.png' // Assuming there's an image for Lady
- : box.read(BoxName.carType) == 'Speed'
- ? 'assets/images/carspeed.png'
- : box.read(BoxName.carType) ==
- 'Scooter'
- ? 'assets/images/moto.png'
- : box.read(BoxName.carType) ==
- 'Mishwar Vip'
- ? 'assets/images/freeRide.png'
- : box.read(BoxName
- .carType) ==
- 'Awfar Car'
- ? 'assets/images/balash.png'
- : box.read(BoxName
- .carType) ==
- 'Pink Bike'
- ? 'assets/images/pinkBike.png'
- : box.read(BoxName
- .carType) ==
- 'Rayeh Gai'
- ? 'assets/images/roundtrip.png'
- : 'assets/images/carspeed.png', // Default image if none of the above
- width: 80,
- ),
+ // ColorFiltered(
+ // colorFilter: ColorFilter.mode(
+ // _parseColor(controller.colorHex),
+ // BlendMode.srcIn,
+ // ),
+ // child: Image.asset(
+ // box.read(BoxName.carType) == 'Comfort'
+ // ? 'assets/images/blob.png'
+ // : box.read(BoxName.carType) == 'Lady'
+ // ? 'assets/images/lady.png' // Assuming there's an image for Lady
+ // : box.read(BoxName.carType) == 'Speed'
+ // ? 'assets/images/carspeed.png'
+ // : box.read(BoxName.carType) ==
+ // 'Scooter'
+ // ? 'assets/images/moto.png'
+ // : box.read(BoxName.carType) ==
+ // 'Mishwar Vip'
+ // ? 'assets/images/freeRide.png'
+ // : box.read(BoxName
+ // .carType) ==
+ // 'Awfar Car'
+ // ? 'assets/images/balash.png'
+ // : box.read(BoxName
+ // .carType) ==
+ // 'Pink Bike'
+ // ? 'assets/images/pinkBike.png'
+ // : box.read(BoxName
+ // .carType) ==
+ // 'Rayeh Gai'
+ // ? 'assets/images/roundtrip.png'
+ // : 'assets/images/carspeed.png', // Default image if none of the above
+ // width: 80,
+ // ),
+ // ),
+
Column(
children: [
Text(
@@ -152,14 +174,31 @@ class ApplyOrderWidget extends StatelessWidget {
),
],
),
+ const SizedBox(
+ width: 10,
+ ),
Text(
// 'Black',
- controller.carColor,
+ controller.carColor.toString(),
style: AppStyle.title,
),
const SizedBox(
width: 10,
),
+ ColorFiltered(
+ colorFilter: ColorFilter.mode(
+ _parseColor(controller.colorHex),
+ BlendMode.srcIn,
+ ),
+ child: Image.asset(
+ box.read(BoxName.carType) == 'Scooter' ||
+ box.read(BoxName.carType) ==
+ 'Pink Bike'
+ ? 'assets/images/moto.png'
+ : 'assets/images/car3.png',
+ width: 80,
+ ),
+ ),
],
),
Padding(
@@ -218,7 +257,7 @@ class ApplyOrderWidget extends StatelessWidget {
children: [
Text(
// 'fadi ahmad',
- controller.firstName,
+ controller.driverName,
style: AppStyle.title,
),
Text(
diff --git a/lib/views/home/map_widget.dart/form_search_places_destenation.dart b/lib/views/home/map_widget.dart/form_search_places_destenation.dart
index 525e642..83217c3 100644
--- a/lib/views/home/map_widget.dart/form_search_places_destenation.dart
+++ b/lib/views/home/map_widget.dart/form_search_places_destenation.dart
@@ -242,109 +242,127 @@ GetBuilder formSearchPlacesDestenation() {
// )
// : const SizedBox(),
Container(
- height: controller.placesDestination.isNotEmpty
- ? controller.height
- : 0,
- color: AppColor.secondaryColor,
- child: ListView.builder(
- itemCount: controller.placesDestination.length,
- itemBuilder: (BuildContext context, int index) {
- var res = controller.placesDestination[index];
- return InkWell(
- onTap: () async {
- controller.changeHeightPlaces();
- await sql.insertData({
- 'latitude': res['geometry']['location']['lat'],
- 'longitude': res['geometry']['location']['lng'],
- 'name': res['name'].toString(),
- 'rate': res['rating'].toString(),
- }, TableName.recentLocations);
+ height: controller.placesDestination.isNotEmpty
+ ? controller.height
+ : 0,
+ color: AppColor.secondaryColor,
+ child: ListView.builder(
+ itemCount: controller.placesDestination.length,
+ itemBuilder: (BuildContext context, int index) {
+ var res = controller.placesDestination[index];
- controller.changeHeightPlaces();
+ // Extract fields with null safety
+ var title = res['title']?.toString() ?? 'Unknown Place';
+ var position = res['position'];
+ var latitude = position?['lat'];
+ var longitude = position?['lng'];
+ var address =
+ res['address']?['label'] ?? 'Unknown Address';
+ var categories = res['categories'] ?? [];
+ var primaryCategory = categories.isNotEmpty
+ ? categories[0]['name']
+ : 'Unknown Category';
- controller.passengerLocation = controller.newMyLocation;
- controller.myDestination = LatLng(
- double.parse(
- res['geometry']['location']['lat'].toString()),
- double.parse(
- res['geometry']['location']['lng'].toString()),
- );
- controller.convertHintTextDestinationNewPlaces(index);
+ return InkWell(
+ onTap: () async {
+ if (latitude != null && longitude != null) {
+ sql.insertMapLocation({
+ 'latitude': latitude,
+ 'longitude': longitude,
+ 'name': title,
+ 'rate': 'N/A',
+ 'createdAt': DateTime.now().toIso8601String(),
+ // No rating in this structure, adjust as needed
+ }, TableName.recentLocations);
- controller.placesDestination = [];
- controller.placeDestinationController.clear();
- controller.changeMainBottomMenuMap();
- controller.passengerStartLocationFromMap = true;
- controller.isPickerShown = true;
- },
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 10),
- child: Column(
- children: [
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Column(
- children: [
- Image.network(
- res['icon'],
- width: 20,
+ controller.passengerLocation =
+ controller.newMyLocation;
+ controller.myDestination =
+ LatLng(latitude, longitude);
+ controller
+ .convertHintTextDestinationNewPlaces(index);
+
+ controller.placesDestination = [];
+ controller.placeDestinationController.clear();
+ controller.changeMainBottomMenuMap();
+ controller.passengerStartLocationFromMap = true;
+ controller.isPickerShown = true;
+ } else {
+ Toast.show(
+ context,
+ 'Invalid location data',
+ AppColor.redColor,
+ );
+ }
+ },
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 10),
+ child: Column(
+ children: [
+ Row(
+ mainAxisAlignment:
+ MainAxisAlignment.spaceBetween,
+ children: [
+ Column(
+ children: [
+ const Icon(Icons.place,
+ size: 20), // Fallback icon for places
+ IconButton(
+ onPressed: () async {
+ if (latitude != null &&
+ longitude != null) {
+ await sql.insertMapLocation({
+ 'latitude': latitude,
+ 'longitude': longitude,
+ 'name': title,
+ 'rate': 'N/A',
+ }, TableName.placesFavorite);
+ Toast.show(
+ context,
+ '$title ${'Saved Successfully'.tr}',
+ AppColor.primaryColor,
+ );
+ } else {
+ Toast.show(
+ context,
+ 'Invalid location data',
+ AppColor.redColor,
+ );
+ }
+ },
+ icon: const Icon(Icons.favorite_border),
+ ),
+ ],
+ ),
+ Expanded(
+ child: Column(
+ crossAxisAlignment:
+ CrossAxisAlignment.start,
+ children: [
+ Text(
+ title,
+ style: AppStyle.title,
+ ),
+ Text(
+ address,
+ style: AppStyle.subtitle,
+ ),
+ Text(
+ primaryCategory,
+ style: AppStyle.subtitle,
+ ),
+ ],
),
- IconButton(
- onPressed: () async {
- await sql.insertData({
- 'latitude': res['geometry']
- ['location']['lat'],
- 'longitude': res['geometry']
- ['location']['lng'],
- 'name': res['name'].toString(),
- 'rate': res['rating'].toString(),
- }, TableName.placesFavorite);
- Toast.show(
- context,
- '${res['name']} ${'Saved Sucssefully'.tr}',
- AppColor.primaryColor);
- },
- icon: const Icon(Icons.favorite_border),
- ),
- ],
- ),
- Column(
- children: [
- Text(
- res['name'].toString(),
- style: AppStyle.title,
- ),
- Text(
- res['vicinity'].toString(),
- style: AppStyle.subtitle,
- ),
- ],
- ),
- Column(
- children: [
- Text(
- 'rate',
- style: AppStyle.subtitle,
- ),
- Text(
- res['rating'].toString(),
- style: AppStyle.subtitle,
- ),
- ],
- ),
- ],
- ),
- const Divider(
- thickness: 1,
- )
- ],
+ ),
+ ],
+ ),
+ const Divider(thickness: 1),
+ ],
+ ),
),
- ),
- );
- },
- ),
- )
+ );
+ },
+ ))
],
));
}
diff --git a/lib/views/home/map_widget.dart/form_search_start.dart b/lib/views/home/map_widget.dart/form_search_start.dart
index 171ec03..ac7d2d2 100644
--- a/lib/views/home/map_widget.dart/form_search_start.dart
+++ b/lib/views/home/map_widget.dart/form_search_start.dart
@@ -103,7 +103,7 @@ GetBuilder formSearchPlacesStart() {
// controller.myLocation =
// controller.newStartPointLocation;
// }
- await sql.insertData({
+ await sql.insertMapLocation({
'latitude': res['geometry']['location']['lat'],
'longitude': res['geometry']['location']['lng'],
'name': res['name'].toString(),
@@ -130,7 +130,7 @@ GetBuilder formSearchPlacesStart() {
),
IconButton(
onPressed: () async {
- await sql.insertData({
+ await sql.insertMapLocation({
'latitude': res['geometry']
['location']['lat'],
'longitude': res['geometry']
diff --git a/lib/views/home/map_widget.dart/form_serch_multiy_point.dart b/lib/views/home/map_widget.dart/form_serch_multiy_point.dart
index 0347790..fed2274 100644
--- a/lib/views/home/map_widget.dart/form_serch_multiy_point.dart
+++ b/lib/views/home/map_widget.dart/form_serch_multiy_point.dart
@@ -109,7 +109,7 @@ GetBuilder formSearchPlaces(int index) {
),
IconButton(
onPressed: () async {
- await sql.insertData({
+ await sql.insertMapLocation({
'latitude': res['geometry']
['location']['lat'],
'longitude': res['geometry']
diff --git a/lib/views/home/map_widget.dart/left_main_menu_icons.dart b/lib/views/home/map_widget.dart/left_main_menu_icons.dart
index ff26bb6..09b3346 100644
--- a/lib/views/home/map_widget.dart/left_main_menu_icons.dart
+++ b/lib/views/home/map_widget.dart/left_main_menu_icons.dart
@@ -8,7 +8,7 @@ import '../../../controller/home/map_passenger_controller.dart';
import '../../../controller/home/vip_waitting_page.dart';
GetBuilder leftMainMenuIcons() {
- final textToSpeechController = Get.put(TextToSpeechController());
+ Get.put(TextToSpeechController());
return GetBuilder(
builder: (controller) => Positioned(
top: Get.height * .008,
@@ -108,7 +108,9 @@ GetBuilder leftMainMenuIcons() {
// borderRadius: BorderRadius.circular(15)),
// child: IconButton(
// onPressed: () async {
- // print(Get.put(MapPassengerController()).data);
+ // controller.statusRide == 'Apply' &&
+ // controller.isSearchingWindow == false;
+ // controller.update();
// },
// icon: const Icon(
// Octicons
diff --git a/lib/views/home/map_widget.dart/main_bottom_Menu_map.dart b/lib/views/home/map_widget.dart/main_bottom_Menu_map.dart
index 3acfe04..65591c5 100644
--- a/lib/views/home/map_widget.dart/main_bottom_Menu_map.dart
+++ b/lib/views/home/map_widget.dart/main_bottom_Menu_map.dart
@@ -1,4 +1,6 @@
+import 'package:SEFER/views/widgets/my_dialog.dart';
import 'package:SEFER/views/widgets/my_textField.dart';
+import 'package:SEFER/views/widgets/mysnakbar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
@@ -14,6 +16,7 @@ import '../../../constant/colors.dart';
import '../../../constant/table_names.dart';
import '../../../controller/functions/toast.dart';
import '../../../controller/functions/tts.dart';
+import '../../../print.dart';
import 'form_search_start.dart';
class MainBottomMenuMap extends StatelessWidget {
@@ -46,24 +49,34 @@ class MainBottomMenuMap extends StatelessWidget {
child: Container(
width: Get.width * .8,
height: Get.height * .1,
- decoration: const BoxDecoration(
- boxShadow: [
- BoxShadow(
- color: Color.fromARGB(
- 255, 237, 230, 230),
- blurRadius: 5,
- offset: Offset(2, 4)),
- BoxShadow(
- color: Color.fromARGB(
- 255, 242, 237, 237),
- blurRadius: 5,
- offset: Offset(-2, -2))
- ],
- color: AppColor.blueColor,
- borderRadius: BorderRadius.all(
- Radius.elliptical(15, 30),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 20, vertical: 10),
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ colors: [
+ AppColor.blueColor.withOpacity(0.8),
+ AppColor.blueColor.withOpacity(0.6),
+ ],
+ begin: Alignment.topLeft,
+ end: Alignment.bottomRight,
),
+ boxShadow: const [
+ BoxShadow(
+ color: Color.fromARGB(
+ 255, 237, 230, 230),
+ blurRadius: 8,
+ offset: Offset(4, 8),
+ ),
+ BoxShadow(
+ color: Color.fromARGB(
+ 255, 242, 237, 237),
+ blurRadius: 8,
+ offset: Offset(-4, -4),
+ ),
+ ],
+ borderRadius: BorderRadius.circular(30),
),
+
// decoration: AppStyle.boxDecoration1,
child: DefaultTextStyle(
style: AppStyle.title.copyWith(
@@ -350,6 +363,18 @@ class MainBottomMenuMap extends StatelessWidget {
},
));
},
+ onLongPress: () {
+ MyDialog().getDialog(
+ "Are you sure to delete this location?".tr, '', () {
+ sql.deleteData(TableName.recentLocations,
+ controller.recentPlaces[index]['id']);
+
+ controller.getFavioratePlaces();
+ controller.update();
+ Get.back();
+ mySnackbarSuccess('deleted'.tr);
+ });
+ },
child: Container(
decoration: AppStyle.boxDecoration1,
child: Padding(
diff --git a/lib/views/home/map_widget.dart/ride_begin_passenger.dart b/lib/views/home/map_widget.dart/ride_begin_passenger.dart
index 3c71f0e..cf919a1 100644
--- a/lib/views/home/map_widget.dart/ride_begin_passenger.dart
+++ b/lib/views/home/map_widget.dart/ride_begin_passenger.dart
@@ -53,7 +53,7 @@ class RideBeginPassenger extends StatelessWidget {
Container(
decoration: AppStyle.boxDecoration,
child: Text(
- controller.firstName,
+ controller.driverName,
style: AppStyle.title,
),
),
diff --git a/lib/views/home/my_wallet/passenger_wallet.dart b/lib/views/home/my_wallet/passenger_wallet.dart
index 1bbe5f9..ce13291 100644
--- a/lib/views/home/my_wallet/passenger_wallet.dart
+++ b/lib/views/home/my_wallet/passenger_wallet.dart
@@ -1,4 +1,3 @@
-import 'package:SEFER/views/widgets/my_dialog.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
@@ -12,11 +11,8 @@ import '../../../controller/functions/toast.dart';
import '../../../controller/home/payment/credit_card_controller.dart';
import '../../../controller/payment/payment_controller.dart';
import '../../../main.dart';
-import '../../../models/model/painter_copoun.dart';
-import '../../../print.dart';
import '../../widgets/elevated_btn.dart';
import '../../widgets/my_scafold.dart';
-import '../../widgets/my_textField.dart';
import 'passenger_wallet_dialoge.dart';
class PassengerWallet extends StatelessWidget {
@@ -51,33 +47,33 @@ class PassengerWallet extends StatelessWidget {
},
),
),
- Padding(
- padding:
- const EdgeInsets.symmetric(horizontal: 80, vertical: 10),
- child: MyElevatedButton(
- kolor: AppColor.yellowColor,
- title: 'Bounus gift'.tr,
- onPressed: () {
- Get.dialog(
- AlertDialog(
- contentPadding: EdgeInsets
- .zero, // Removes the padding around the content
- content: SizedBox(
- width: 300, // Match the width of PromoBanner
- // height: 250, // Match the height of PromoBanner
- child: PromoBanner(
- promoCode: box.read(BoxName.promo),
- discountPercentage: box.read(BoxName.discount),
- validity: box.read(BoxName.validity),
- ),
- ),
- ),
- );
- Log.print(
- 'box.read(BoxName.isGiftToken).toString(): ${box.read(BoxName.isGiftToken).toString()}');
- },
- ),
- )
+ // Padding(
+ // padding:
+ // const EdgeInsets.symmetric(horizontal: 80, vertical: 10),
+ // child: MyElevatedButton(
+ // kolor: AppColor.yellowColor,
+ // title: 'Bonus gift'.tr,
+ // onPressed: () {
+ // Get.dialog(
+ // AlertDialog(
+ // contentPadding: EdgeInsets
+ // .zero, // Removes the padding around the content
+ // content: SizedBox(
+ // width: 300, // Match the width of PromoBanner
+ // // height: 250, // Match the height of PromoBanner
+ // child: PromoBanner(
+ // promoCode: box.read(BoxName.promo),
+ // discountPercentage: box.read(BoxName.discount),
+ // validity: box.read(BoxName.validity),
+ // ),
+ // ),
+ // ),
+ // );
+ // Log.print(
+ // 'box.read(BoxName.isGiftToken).toString(): ${box.read(BoxName.isGiftToken).toString()}');
+ // },
+ // ),
+ // )
],
),
),
@@ -98,7 +94,8 @@ class PassengerWallet extends StatelessWidget {
MyElevatedButton(
title: 'Show Promos to Charge'.tr,
onPressed: () {
- controller.changePromoSheetDialogue();
+ // controller.changePromoSheetDialogue();
+ showPaymentBottomSheet(context);
},
),
const SizedBox(
diff --git a/lib/views/home/my_wallet/passenger_wallet_dialoge.dart b/lib/views/home/my_wallet/passenger_wallet_dialoge.dart
index 89b9933..af85f94 100644
--- a/lib/views/home/my_wallet/passenger_wallet_dialoge.dart
+++ b/lib/views/home/my_wallet/passenger_wallet_dialoge.dart
@@ -1,4 +1,6 @@
+import 'package:SEFER/constant/style.dart';
import 'package:flutter/cupertino.dart';
+import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:SEFER/constant/box_name.dart';
import 'package:SEFER/constant/colors.dart';
@@ -89,6 +91,147 @@ class PassengerWalletDialog extends StatelessWidget {
);
}
}
+// class PassengerWalletDialog extends StatelessWidget {
+// const PassengerWalletDialog({
+// super.key,
+// });
+
+// @override
+// Widget build(BuildContext context) {
+// return GetBuilder(
+// builder: (controller) {
+// return Positioned(
+// top: Get.height * .1,
+// right: Get.width * .15,
+// left: Get.width * .15,
+// bottom: Get.height * .1,
+// child: controller.isPromoSheetDialogue
+// ? Container()
+// : SizedBox
+// .shrink(), // If condition is false, return an empty widget
+// );
+// },
+// );
+// }
+// }
+void showPaymentBottomSheet(BuildContext context) {
+ final controller = Get.find();
+
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(15.0)),
+ ),
+ builder: (BuildContext context) {
+ return WillPopScope(
+ onWillPop: () async {
+ Get.back();
+ return false;
+ },
+ child: Container(
+ padding: const EdgeInsets.all(16.0),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ 'Select Payment Amount'.tr,
+ style: AppStyle.headTitle2,
+ textAlign: TextAlign.center,
+ ),
+ const SizedBox(height: 16.0),
+
+ // Payment Options List
+ _buildPaymentOption(
+ context: context,
+ controller: controller,
+ amount: box.read(BoxName.countryCode) == 'Egypt' ? 100 : 10,
+ bonusAmount: 0,
+ currency: box.read(BoxName.countryCode) == 'Egypt'
+ ? 'LE'.tr
+ : 'JOD'.tr,
+ ),
+
+ const SizedBox(height: 8.0),
+ _buildPaymentOption(
+ context: context,
+ controller: controller,
+ amount: box.read(BoxName.countryCode) == 'Egypt' ? 200 : 20,
+ bonusAmount: box.read(BoxName.countryCode) == 'Egypt' ? 5 : 1,
+ currency: box.read(BoxName.countryCode) == 'Egypt'
+ ? 'LE'.tr
+ : 'JOD'.tr,
+ ),
+
+ const SizedBox(height: 8.0),
+ _buildPaymentOption(
+ context: context,
+ controller: controller,
+ amount: box.read(BoxName.countryCode) == 'Egypt' ? 400 : 40,
+ bonusAmount:
+ box.read(BoxName.countryCode) == 'Egypt' ? 15 : 2.5,
+ currency: box.read(BoxName.countryCode) == 'Egypt'
+ ? 'LE'.tr
+ : 'JOD'.tr,
+ ),
+
+ const SizedBox(height: 8.0),
+ _buildPaymentOption(
+ context: context,
+ controller: controller,
+ amount: box.read(BoxName.countryCode) == 'Egypt' ? 1000 : 50,
+ bonusAmount: box.read(BoxName.countryCode) == 'Egypt' ? 100 : 6,
+ currency: box.read(BoxName.countryCode) == 'Egypt'
+ ? 'LE'.tr
+ : 'JOD'.tr,
+ ),
+
+ const SizedBox(height: 16.0),
+ TextButton(
+ onPressed: () => Get.back(),
+ child: Text('Cancel'.tr),
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+}
+
+Widget _buildPaymentOption({
+ required BuildContext context,
+ required PaymentController controller,
+ required int amount,
+ required double bonusAmount,
+ required String currency,
+}) {
+ return Material(
+ color: Colors.transparent,
+ child: InkWell(
+ onTap: () {
+ controller.updateSelectedAmount(amount);
+ Get.back();
+ showPaymentOptions(context, controller);
+ },
+ child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
+ decoration: BoxDecoration(
+ border: Border.all(color: Colors.grey[300]!),
+ borderRadius: BorderRadius.circular(8.0),
+ ),
+ child: Text(
+ bonusAmount > 0
+ ? '${'Pay'.tr} $amount $currency, ${'Get'.tr} ${amount + bonusAmount} $currency'
+ : '$amount $currency',
+ style: AppStyle.title,
+ textAlign: TextAlign.center,
+ ),
+ ),
+ ),
+ );
+}
void showPaymentOptions(BuildContext context, PaymentController controller) {
showCupertinoModalPopup(
@@ -209,7 +352,8 @@ void showPaymentOptions(BuildContext context, PaymentController controller) {
cancelButton: CupertinoActionSheetAction(
child: Text('Cancel'.tr),
onPressed: () {
- controller.changePromoSheetDialogue();
+ // controller.changePromoSheetDialogue();
+ Get.back();
},
),
),
diff --git a/lib/views/home/profile/promos_passenger_page.dart b/lib/views/home/profile/promos_passenger_page.dart
index 1d995d4..923478b 100644
--- a/lib/views/home/profile/promos_passenger_page.dart
+++ b/lib/views/home/profile/promos_passenger_page.dart
@@ -20,211 +20,211 @@ class PromosPassengerPage extends StatelessWidget {
Widget build(BuildContext context) {
Get.put(PromosController());
return MyScafolld(
- title: 'Promos For today'.tr,
+ title: "Promos For Today".tr,
isleading: true,
body: [
GetBuilder(
builder: (orderHistoryController) => orderHistoryController.isLoading
? const MyCircularProgressIndicator()
: ListView.builder(
- itemCount: orderHistoryController.promoList.length +
- 1, // Adding 1 for the ad
+ itemCount: orderHistoryController
+ .promoList.length, // Adding 1 for the ad
itemBuilder: (BuildContext context, int index) {
- if (index == 0) {
- // Ad at the beginning
- return Padding(
- padding: const EdgeInsets.all(8.0),
- child: Container(
- height: 120, // Adjust the height of the ad container
- decoration: BoxDecoration(
- color:
- Colors.grey[200], // Background color for the ad
- borderRadius: BorderRadius.circular(10),
- ),
- child: Center(
- child: Container(
- decoration: AppStyle.boxDecoration,
- height: Get.height * .19,
- child: ListView(
- scrollDirection: Axis.horizontal,
- children: [
- PointsCaptain(
- kolor: AppColor.greyColor,
- pricePoint:
- box.read(BoxName.countryCode) ==
- 'Jordan'
- ? 5
- : 100,
- countPoint:
- box.read(BoxName.countryCode) ==
- 'Jordan'
- ? '300'
- : '100',
- ),
- PointsCaptain(
- kolor: AppColor.bronze,
- pricePoint:
- box.read(BoxName.countryCode) ==
- 'Jordan'
- ? 10
- : 200,
- countPoint:
- box.read(BoxName.countryCode) ==
- 'Jordan'
- ? '1040'
- : '210',
- ),
- PointsCaptain(
- kolor: AppColor.goldenBronze,
- pricePoint:
- box.read(BoxName.countryCode) ==
- 'Jordan'
- ? 22
- : 400,
- countPoint:
- box.read(BoxName.countryCode) ==
- 'Jordan'
- ? '2300'
- : '450',
- ),
- PointsCaptain(
- kolor: AppColor.gold,
- pricePoint:
- box.read(BoxName.countryCode) ==
- 'Jordan'
- ? 50
- : 1000,
- countPoint:
- box.read(BoxName.countryCode) ==
- 'Jordan'
- ? '55000'
- : '1200',
- ),
- ],
- )),
- ),
- ),
- );
- } else {
- // Promo items
- final rides = orderHistoryController.promoList[index - 1];
+ // if (index == 0) {
+ // // Ad at the beginning
+ // return Padding(
+ // padding: const EdgeInsets.all(8.0),
+ // child: Container(
+ // height: 120, // Adjust the height of the ad container
+ // decoration: BoxDecoration(
+ // color:
+ // Colors.grey[200], // Background color for the ad
+ // borderRadius: BorderRadius.circular(10),
+ // ),
+ // child: Center(
+ // child: Container(
+ // decoration: AppStyle.boxDecoration,
+ // height: Get.height * .19,
+ // child: ListView(
+ // scrollDirection: Axis.horizontal,
+ // children: [
+ // PointsCaptain(
+ // kolor: AppColor.greyColor,
+ // pricePoint:
+ // box.read(BoxName.countryCode) ==
+ // 'Jordan'
+ // ? 5
+ // : 100,
+ // countPoint:
+ // box.read(BoxName.countryCode) ==
+ // 'Jordan'
+ // ? '300'
+ // : '100',
+ // ),
+ // PointsCaptain(
+ // kolor: AppColor.bronze,
+ // pricePoint:
+ // box.read(BoxName.countryCode) ==
+ // 'Jordan'
+ // ? 10
+ // : 200,
+ // countPoint:
+ // box.read(BoxName.countryCode) ==
+ // 'Jordan'
+ // ? '1040'
+ // : '210',
+ // ),
+ // PointsCaptain(
+ // kolor: AppColor.goldenBronze,
+ // pricePoint:
+ // box.read(BoxName.countryCode) ==
+ // 'Jordan'
+ // ? 22
+ // : 400,
+ // countPoint:
+ // box.read(BoxName.countryCode) ==
+ // 'Jordan'
+ // ? '2300'
+ // : '450',
+ // ),
+ // PointsCaptain(
+ // kolor: AppColor.gold,
+ // pricePoint:
+ // box.read(BoxName.countryCode) ==
+ // 'Jordan'
+ // ? 50
+ // : 1000,
+ // countPoint:
+ // box.read(BoxName.countryCode) ==
+ // 'Jordan'
+ // ? '55000'
+ // : '1200',
+ // ),
+ // ],
+ // )),
+ // ),
+ // ),
+ // );
+ // } else {
+ // Promo items
+ final rides = orderHistoryController.promoList[index];
- return Padding(
- padding: const EdgeInsets.all(12.0),
- child: Container(
- decoration: BoxDecoration(
- color: CupertinoColors.systemGrey6,
- borderRadius: BorderRadius.circular(16),
- boxShadow: [
- BoxShadow(
- color:
- CupertinoColors.systemGrey.withOpacity(0.5),
- blurRadius: 8,
- offset: Offset(0, 4),
- ),
- ],
- ),
- child: Padding(
- padding: const EdgeInsets.all(16.0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Column(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- GestureDetector(
- onTap: () {},
- child: AnimatedTextKit(
- animatedTexts: [
- ScaleAnimatedText(
- rides['promo_code'],
- textStyle:
- AppStyle.title.copyWith(
- fontSize:
- 32, // Increased font size for emphasis
- color: CupertinoColors
- .activeBlue,
- fontWeight: FontWeight.bold,
- ),
+ return Padding(
+ padding: const EdgeInsets.all(12.0),
+ child: Container(
+ decoration: BoxDecoration(
+ color: CupertinoColors.systemGrey6,
+ borderRadius: BorderRadius.circular(16),
+ boxShadow: [
+ BoxShadow(
+ color:
+ CupertinoColors.systemGrey.withOpacity(0.5),
+ blurRadius: 8,
+ offset: Offset(0, 4),
+ ),
+ ],
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(16.0),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ mainAxisAlignment:
+ MainAxisAlignment.spaceBetween,
+ children: [
+ Column(
+ crossAxisAlignment:
+ CrossAxisAlignment.start,
+ children: [
+ GestureDetector(
+ onTap: () {},
+ child: AnimatedTextKit(
+ animatedTexts: [
+ ScaleAnimatedText(
+ rides['promo_code'],
+ textStyle:
+ AppStyle.title.copyWith(
+ fontSize:
+ 32, // Increased font size for emphasis
+ color:
+ CupertinoColors.activeBlue,
+ fontWeight: FontWeight.bold,
),
- WavyAnimatedText(
- rides['promo_code'],
- textStyle:
- AppStyle.title.copyWith(
- fontSize:
- 32, // Increased font size for emphasis
- color: CupertinoColors
- .activeBlue,
- fontWeight: FontWeight.bold,
- ),
+ ),
+ WavyAnimatedText(
+ rides['promo_code'],
+ textStyle:
+ AppStyle.title.copyWith(
+ fontSize:
+ 32, // Increased font size for emphasis
+ color:
+ CupertinoColors.activeBlue,
+ fontWeight: FontWeight.bold,
),
- ],
- isRepeatingAnimation: true,
- ),
+ ),
+ ],
+ isRepeatingAnimation: true,
),
- const SizedBox(height: 8),
- // Description Text
- Text(
- rides['description'],
- style: AppStyle.title.copyWith(
- fontSize: 22,
- color: CupertinoColors.systemGrey,
- ),
- ),
- ],
- ),
- Column(
- children: [
- // Only displaying end date
- Text(
- '${'Valid Until:'.tr} ${rides['validity_end_date']}',
- style: AppStyle.subtitle.copyWith(
- fontWeight: FontWeight.bold,
- fontSize: 20,
- color: CupertinoColors.systemGrey,
- ),
- ),
- ],
- ),
- ],
- ),
- // const SizedBox(height: 16),
- // Copy Promo Text
- Center(
- child: GestureDetector(
- onTap: () {
- Clipboard.setData(ClipboardData(
- text: rides['promo_code']));
- Get.snackbar(
- 'Promo Copied!'.tr,
- 'You have copied the promo code.'.tr,
- snackPosition: SnackPosition.BOTTOM,
- backgroundColor:
- CupertinoColors.systemGrey,
- colorText: CupertinoColors.white,
- );
- },
- child: Text(
- 'Copy Code'.tr,
- textAlign: TextAlign.center,
- style: AppStyle.headTitle2.copyWith(
- color: CupertinoColors.systemBlue,
- fontWeight: FontWeight.bold,
),
+ const SizedBox(height: 8),
+ // Description Text
+ Text(
+ rides['description'],
+ style: AppStyle.title.copyWith(
+ fontSize: 22,
+ color: CupertinoColors.systemGrey,
+ ),
+ ),
+ ],
+ ),
+ Column(
+ children: [
+ // Only displaying end date
+ Text(
+ '${'Valid Until:'.tr} ${rides['validity_end_date']}',
+ style: AppStyle.subtitle.copyWith(
+ fontWeight: FontWeight.bold,
+ fontSize: 20,
+ color: CupertinoColors.systemGrey,
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ // const SizedBox(height: 16),
+ // Copy Promo Text
+ Center(
+ child: GestureDetector(
+ onTap: () {
+ Clipboard.setData(ClipboardData(
+ text: rides['promo_code']));
+ Get.snackbar(
+ 'Promo Copied!'.tr,
+ 'You have copied the promo code.'.tr,
+ snackPosition: SnackPosition.BOTTOM,
+ backgroundColor:
+ CupertinoColors.systemGrey,
+ colorText: CupertinoColors.white,
+ );
+ },
+ child: Text(
+ 'Copy Code'.tr,
+ textAlign: TextAlign.center,
+ style: AppStyle.headTitle2.copyWith(
+ color: CupertinoColors.systemBlue,
+ fontWeight: FontWeight.bold,
),
),
),
- ],
- ),
+ ),
+ ],
),
),
- );
- }
+ ),
+ );
+ // }
},
),
)