This commit is contained in:
Hamza-Ayed
2024-11-09 10:49:04 +02:00
parent fc81405b7a
commit 213c2724aa
44 changed files with 3009 additions and 1130 deletions

View File

@@ -769,7 +769,8 @@ class MapPassengerController extends GetxController {
if (res != 'failure') {
var decode = jsonDecode(res);
if (decode['data']['status'] != 'Apply') {
// if (decode['data']['status'] != 'Apply') {
if (decode['data']['status'] == 'Begin') {
timeToPassengerFromDriverAfterApplied = 0;
remainingTime = 0;
remainingTimeToPassengerFromDriverAfterApplied = 0;
@@ -1077,7 +1078,7 @@ class MapPassengerController extends GetxController {
// licensePlate = nearestDriverData['car_plate'].toString();
// startCarLocationSearch(box.read(BoxName.carType));
await getCarsLocationByPassengerAndReloadMarker(
box.read(BoxName.carType), 4500);
box.read(BoxName.carType), 3000);
// await getCarsLocationByPassengerAndReloadMarker(
// box.read(BoxName.carType), 7000);
// await getNearestDriverByPassengerLocation();
@@ -1112,26 +1113,28 @@ class MapPassengerController extends GetxController {
isDriversTokensSend = false;
update();
await 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(),
}).then((value) {
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<String> body = [
rideId = jsonDecode(value)['message'];
List<String> body = [
@@ -1188,6 +1191,29 @@ class MapPassengerController extends GetxController {
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();
@@ -1211,10 +1237,11 @@ class MapPassengerController extends GetxController {
}
}
String driverOrderStatus = 'yet';
bool isDriversTokensSend = false;
confirmRideForAllDriverAvailable() async {
confirmRideForAllDriverAvailable0() async {
await getCarsLocationByPassengerAndReloadMarker(
box.read(BoxName.carType), 4500);
box.read(BoxName.carType), 3500);
if (dataCarsLocationByPassenger != 'failure') {
// driversToken.remove(driverToken);
PaymentController paymentController = Get.find<PaymentController>();
@@ -1291,33 +1318,38 @@ class MapPassengerController extends GetxController {
// Log.print('body: ${body}');
FirebaseMessagesController().sendNotificationToDriverMAP(
'OrderSpeed',
rideId.toString(),
dataCarsLocationByPassenger['data'][i]['token'].toString(),
body,
'order.wav');
'OrderSpeed',
rideId.toString(),
dataCarsLocationByPassenger['data'][i]['token'].toString(),
body,
'order.wav',
);
driverOrderStatus = 'recive';
}
});
(rideId); //
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(),
});
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();
@@ -1330,6 +1362,344 @@ class MapPassengerController extends GetxController {
}
}
Set<String> notifiedDrivers = {};
confirmRideForAllDriverAvailable() 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<PaymentController>();
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 >= 5) {
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<String> 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<WayPointController>().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":
'${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();
} 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());
});
}
}
confirmRideForAllDriverAvailable1() async {
int attempts = 0;
const int maxAttempts = 4;
const Duration delayDuration = Duration(seconds: 2);
// Initial data fetch
await getCarsLocationByPassengerAndReloadMarker(
box.read(BoxName.carType), 3000);
if (dataCarsLocationByPassenger != null &&
dataCarsLocationByPassenger != 'failure') {
PaymentController paymentController = Get.find<PaymentController>();
rideConfirm = true;
shouldFetch = true;
isBottomSheetShown = false;
timeToPassengerFromDriverAfterApplied = 60;
// Create a set to keep track of notified driver IDs
Set<String> notifiedDriverIds = {};
// Send the initial ride request once
rideId = 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) => jsonDecode(value)['message']);
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(),
});
}
// Add the initially available drivers to the notified set
for (var driver in dataCarsLocationByPassenger['data']) {
notifiedDriverIds.add(driver['driver_id'].toString());
}
// Periodically check for new drivers
Timer.periodic(delayDuration, (Timer timer) async {
attempts++;
await getCarsLocationByPassengerAndReloadMarker(
box.read(BoxName.carType), 3000);
if (dataCarsLocationByPassenger != 'failure') {
// Check for new drivers and notify them
for (var driver in dataCarsLocationByPassenger['data']) {
String driverId = driver['driver_id'].toString();
// Only notify new drivers
if (!notifiedDriverIds.contains(driverId)) {
notifiedDriverIds.add(driverId);
// Prepare notification body
List<String> 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(),
driver['token'].toString(),
durationToPassenger.toString(),
rideId,
rideTimerBegin.toString(),
durationToRide.toString(),
Get.find<WayPointController>().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 new driver
FirebaseMessagesController().sendNotificationToDriverMAP(
'OrderSpeed',
rideId.toString(),
driver['token'].toString(),
body,
'order.wav',
);
}
}
} 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());
});
}
// Stop after max attempts
if (attempts >= maxAttempts) {
timer.cancel();
}
});
} 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());
});
}
}
icreaseForSameRideAndDelay() {
PaymentController paymentController = Get.find<PaymentController>();
rideConfirm = true;
@@ -1398,19 +1768,20 @@ class MapPassengerController extends GetxController {
String res = await getRideStatus(rideId);
Log.print('tick: $tick');
if ((res.toString() == 'waiting' || res.toString() == 'Refused') &&
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, 4500);
await getCarsLocationByPassengerAndReloadMarker(carType, 3000);
// await getNearestDriverByPassengerLocationAPIGOOGLE();
// getCarForFirstConfirm(carType);
confirmRideForAllDriverAvailable();
// delayAndFetchRideStatusForAllDriverAvailable(rideId);
} else if (res.toString() == 'Apply') {
Log.print('res.toString() == Apply: ${res.toString()}');
} else if (rideStatusDelayed == 'Apply') {
Log.print('rideStatusDelayed == Apply: ${rideStatusDelayed}');
// todo play sound
Get.find<AudioRecorderController>()
.playSoundFromAssets('assets/start.wav');
@@ -1422,7 +1793,7 @@ class MapPassengerController extends GetxController {
isSearchingWindow = false;
update();
startTimerFromDriverToPassengerAfterApplied();
} else if (res.toString() == 'Refused') {
} else if (rideStatusDelayed == 'Refused') {
statusRide = 'Refused';
if (isDriversTokensSend == false) {
confirmRideForAllDriverAvailable();
@@ -1473,17 +1844,22 @@ class MapPassengerController extends GetxController {
attemptCounter++;
tick++;
var res = await getRideStatus(rideId);
String rideStatusDelayed = res.toString();
if (res.toString() == 'Apply' || res.toString() == 'Applied') {
if (rideStatusDelayed == 'Apply' || rideStatusDelayed == 'Applied') {
await getUpdatedRideForDriverApply(rideId);
isApplied = true;
shouldFetch = false;
statusRide = 'Apply';
rideConfirm = false;
isSearchingWindow = false;
startTimer();
update();
startTimerFromDriverToPassengerAfterApplied();
} else if (attemptCounter >= maxAttempts && statusRide != 'Cancel') {
} else if (attemptCounter >= maxAttempts &&
rideStatusDelayed != 'Cancel') {
shouldFetch = false;
// If the status is still not "Apply" after 15 attempts
MyDialog().getDialog('upgrade price'.tr,
@@ -1573,7 +1949,7 @@ class MapPassengerController extends GetxController {
reSearchAfterCanceledFromDriver() async {
await getCarsLocationByPassengerAndReloadMarker(
box.read(BoxName.carType), 4500);
box.read(BoxName.carType), 3000);
confirmRideForAllDriverAvailable();
shouldFetch = true; // Stop further fetches
@@ -1616,8 +1992,9 @@ class MapPassengerController extends GetxController {
}
Future<String> getRideStatus(String rideId) async {
final response =
await CRUD().get(link: AppLink.getRideStatus, payload: {'id': rideId});
final response = await CRUD().get(
link: "${AppLink.endPoint}/ride/rides/getRideStatus.php",
payload: {'id': rideId});
return jsonDecode(response)['data'];
}
@@ -1638,7 +2015,7 @@ class MapPassengerController extends GetxController {
make = response['data']['make'];
licensePlate = response['data']['car_plate'];
firstName = response['data']['first_name'];
driverName = response['data']['driverName'];
driverName = response['data']['driverName'].toString().split(' ')[0];
driverToken = response['data']['token'];
Log.print('driverToken updated: $driverToken');
carYear = response['data']['year'];
@@ -1646,10 +2023,11 @@ class MapPassengerController extends GetxController {
}
// driversToken.remove(driverToken);
// for (var i = 1; i < driversToken.length; i++) {
FirebaseMessagesController().sendNotificationToAnyWithoutData(
FirebaseMessagesController().sendNotificationToDriverMAP(
'Order Applied'.tr,
'$driverName Apply order\nTake attention in other order'.tr,
driverToken,
[],
'start.wav',
);
// }
@@ -1871,6 +2249,7 @@ class MapPassengerController extends GetxController {
longitude >= 31.215009 &&
longitude <= 31.532186) {
box.write(BoxName.serverChosen, AppLink.seferCairoServer);
return 'Cairo';
} else if (latitude >= 29.904975 &&
latitude <= 30.143372 &&
@@ -2380,12 +2759,13 @@ class MapPassengerController extends GetxController {
double tripDurationInMinutes = durationToRide / 6;
int loopCount = tripDurationInMinutes.ceil();
// If the trip duration is less than or equal to 50 minutes, then break the loop.
clearMarkersExceptStartEnd();
for (var i = 0; i < loopCount; i++) {
// Wait for 50 seconds.
await Future.delayed(const Duration(seconds: 4));
if (rideTimerBegin == true && statusRide == 'Apply') {
await getDriverCarsLocationToPassengerAfterApplied();
}
// if (rideTimerBegin == true && statusRide == 'Apply') {
await getDriverCarsLocationToPassengerAfterApplied();
// }
reloadMarkerDriverCarsLocationToPassengerAfterApplied();
}
}
@@ -2517,79 +2897,66 @@ class MapPassengerController extends GetxController {
}
Future cancelRide() async {
if (rideConfirm == false && statusRide == 'Apply' ||
statusRide == 'Applied' ||
statusRide == 'waiting') {
clearPlacesDestination();
clearPolyline();
// clearPolylineAll();
data = [];
changeCancelRidePageShow();
if (rideId != 'yet') {
await CRUD().post(link: AppLink.updateDriverOrder, payload: {
"order_id": rideId.toString(), // Convert to String
"status": 'Cancel'
});
FirebaseMessagesController().sendNotificationToDriverMAP(
'Cancel Trip',
'Trip Cancelled'.tr,
driverToken,
[],
'cancel.wav',
);
if (AppLink.endPoint != AppLink.seferCairoServer) {
CRUD().post(
link: "$AppLink.endPoint/ride/driver_order/update.php",
payload: {
"order_id": rideId.toString(), // Convert to String
"status": 'Cancel'
});
}
await CRUD().post(link: AppLink.updateRides, payload: {
// if (rideConfirm == true ||
// statusRide == 'Apply' ||
// statusRide == 'Applied' ||
// statusRide == 'wait' ||
// statusRide == 'waiting') {
clearPlacesDestination();
clearPolyline();
// clearPolylineAll();
data = [];
changeCancelRidePageShow();
if (rideId != 'yet') {
Log.print('cancelRide: 1');
FirebaseMessagesController().sendNotificationToDriverMAP(
'Cancel Trip'.tr,
'Trip Cancelled'.tr,
driverToken,
[],
'cancel.wav',
);
await Future.wait([
CRUD().post(link: AppLink.updateRides, payload: {
"id": rideId.toString(), // Convert to String
"status": 'Cancel'
});
if (AppLink.endPoint != AppLink.seferCairoServer) {
CRUD().post(
link: "${AppLink.endPoint}/ride/rides/update.php",
payload: {
"id": rideId.toString(), // Convert to String
"status": 'Cancel'
});
}
}),
CRUD().post(link: AppLink.updateDriverOrder, payload: {
"order_id": rideId.toString(), // Convert to String
"status": 'Cancel'
}),
CRUD().post(link: AppLink.updateWaitingTrip, payload: {
"id": rideId.toString(), // Convert to String
"status": 'Cancel'
}),
]);
if (AppLink.endPoint != AppLink.seferCairoServer) {
CRUD().post(
link: "${AppLink.endPoint}/ride/driver_order/update.php",
payload: {
"order_id": rideId.toString(), // Convert to String
"status": 'Cancel'
});
CRUD()
.post(link: "${AppLink.endPoint}/ride/rides/update.php", payload: {
"id": rideId.toString(), // Convert to String
"status": 'Cancel'
});
if (AppLink.endPoint != AppLink.seferCairoServer) {
CRUD().post(
link:
"${AppLink.endPoint}/ride/notificationCaptain/updateWaitingTrip.php",
payload: {
"id": rideId.toString(), // Convert to String
"status": 'Cancel'
});
}
print('Cancel');
CRUD().post(
link:
"${AppLink.endPoint}/ride/notificationCaptain/updateWaitingTrip.php",
payload: {
"id": rideId.toString(), // Convert to String
"status": 'Cancel'
});
}
Get.offAll(const MapPagePassenger());
} else {
clearPlacesDestination();
clearPolyline();
data = [];
// await CRUD().post(link: AppLink.updateDriverOrder, payload: {
// "order_id": rideId.toString(), // Convert to String
// "status": 'Cancel'
// });
// await CRUD().post(link: AppLink.updateRides, payload: {
// "id": rideId.toString(), // Convert to String
// "status": 'Cancel'
// });
Get.offAll(const MapPagePassenger());
print('Cancel');
// }
}
Future.delayed(const Duration(seconds: 1));
Get.offAll(() => const MapPagePassenger());
}
void changePickerShown() {
@@ -2942,28 +3309,28 @@ class MapPassengerController extends GetxController {
? LatLng(_locationData.latitude!, _locationData.longitude!)
: null)!;
getLocationArea(passengerLocation.latitude, passengerLocation.longitude);
Log.print('AppLink.endPoint: ${AppLink.endPoint}');
// Log.print('BoxName.serverChosen: ${box.read(BoxName.serverChosen)}');
newStartPointLocation = passengerLocation;
Log.print('passengerLocation: ${passengerLocation}');
speed = _locationData.speed!;
// //print location details
isLoading = false;
update();
}
LatLngBounds calculateBounds(
double centerLat, double centerLng, double radius) {
// double radius = 4000; // 10 km in meters
LatLngBounds calculateBounds(double lat, double lng, double radiusInMeters) {
const double earthRadius = 6378137.0; // Earth's radius in meters
southwest = LatLng(
centerLat - (radius / 111000),
centerLng - (radius / (111000 * cos(centerLat))),
double latDelta = radiusInMeters / earthRadius * (180 / pi);
double lngDelta =
radiusInMeters / (earthRadius * cos(pi * lat / 180)) * (180 / pi);
return LatLngBounds(
southwest: LatLng(lat - latDelta, lng - lngDelta),
northeast: LatLng(lat + latDelta, lng + lngDelta),
);
northeast = LatLng(
centerLat + (radius / 111000),
centerLng + (radius / (111000 * cos(centerLat))),
);
return LatLngBounds(southwest: southwest, northeast: northeast);
}
GoogleMapController? mapController;
@@ -2992,8 +3359,6 @@ class MapPassengerController extends GetxController {
bool reloadStartApp = false;
int reloadCount = 0;
startMarkerReloading() async {
Log.print('AppLink.endPoint: ${AppLink.endPoint}');
if (reloadStartApp == false) {
Timer.periodic(const Duration(seconds: 5), (timer) async {
reloadCount++;
@@ -3233,7 +3598,7 @@ class MapPassengerController extends GetxController {
remainingTime = 25; //to make cancel every call
// startCarLocationSearch(box.read(BoxName.carType));
await getCarsLocationByPassengerAndReloadMarker(
box.read(BoxName.carType), 7000);
box.read(BoxName.carType), 5000);
// await getCarsLocationByPassengerAndReloadMarker();
var coordDestination = destination.split(',');
double latPassengerDestination = double.parse(coordDestination[0]);
@@ -4093,55 +4458,77 @@ class MapPassengerController extends GetxController {
try {
// Prepare trip data
Map<String, dynamic> tripData = {
'id': driver['id'],
'id': driver['id'].toString(), // Ensure the id is a string
'phone': driver['phone'],
'gender': driver['gender'],
'name': driver['name'],
'name': driver['NAME'],
'name_english': driver['name_english'],
'address': driver['address'],
'religion': driver['religion'],
'age': driver['age'],
'age': driver['age'].toString(), // Convert age to String
'education': driver['education'],
'license_type': driver['license_type'],
'national_number': driver['national_number'],
'car_plate': driver['car_plate'],
'make': driver['make'],
'model': driver['model'],
'year': driver['year'],
'year': driver['year'].toString(), // Convert year to String
'color': driver['color'],
'color_hex': driver['color_hex'],
'displacement': driver['displacement'],
'fuel': driver['fuel'],
'token': driver['token'],
'rating': driver['rating'],
'countRide': driver['countRide'],
'rating': driver['rating'].toString(), // Convert rating to String
'countRide':
driver['countRide'].toString(), // Convert countRide to String
'passengerId': box.read(BoxName.passengerID),
'timeSelected': tripDateTime.toIso8601String(),
'status': 'pending', // Or other appropriate status
'status': 'pending',
};
// Log.print('tripData: $tripData');
// Send data to server
var response =
await CRUD().post(link: AppLink.addMishwari, payload: tripData);
// Log.print('response: $response');
if (response != 'failure') {
// Trip saved successfully
Get.snackbar('Success'.tr, 'Trip booked successfully'.tr);
var id = response['message'].toString();
if (AppLink.endPoint != AppLink.seferCairoServer) {
CRUD().post(
await CRUD().post(
link: "${AppLink.endPoint}/ride/mishwari/add.php",
payload: tripData);
}
// Set up local notification
// Optionally, set up local notification or send a push notification
// await setLocalNotification(tripDateTime);
// Send notification to driver
// await FirebaseMessagesController().sendNotificationToDriverMAP();
await FirebaseMessagesController().sendNotificationToDriverMAP(
'OrderVIP',
rideId.toString(),
driver['token'].toString(),
[
id,
driver['id'],
passengerLocation.latitude.toString(),
passengerLocation.longitude.toString(),
box.read(BoxName.name).toString(),
box.read(BoxName.passengerID).toString(),
box.read(BoxName.phone).toString(),
box.read(BoxName.email).toString(),
box.read(BoxName.passengerPhotoUrl).toString(),
box.read(BoxName.tokenFCM).toString(),
driver['token'].toString(),
],
'order.wav');
} else {
throw Exception('Failed to save trip');
}
} catch (e) {
Get.snackbar('Error'.tr, 'Failed to book trip: $e'.tr);
// Show error message with more details for debugging
Get.snackbar('Error'.tr, 'Failed to book trip: $e'.tr,
backgroundColor: AppColor.redColor);
Log.print('Error: $e');
}
}
@@ -4253,8 +4640,8 @@ class MapPassengerController extends GetxController {
addCustomStepIcon();
addCustomStartIcon();
addCustomEndIcon();
addToken();
getLocation();
// addToken();
await getLocation();
getPassengerLocationUniversity();
_initializePolygons();
// await addToken();