25-7-28-2

This commit is contained in:
Hamza-Ayed
2025-07-28 12:21:28 +03:00
parent 660d60e1f5
commit 83a97baed1
549 changed files with 109870 additions and 0 deletions

View File

@@ -0,0 +1,115 @@
import 'dart:convert';
import 'dart:math';
import 'package:get/get.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import '../../../constant/table_names.dart';
import '../../../main.dart';
class DriverBehaviorController extends GetxController {
Future<List<Map<String, dynamic>>> getAllData() async {
return await sql.getAllData(TableName.behavior);
}
var isLoading = false.obs;
var overallScore = 100.0.obs;
var lastTrips = [].obs;
Future<void> fetchDriverBehavior() async {
isLoading.value = true;
try {
final response = await CRUD().get(
link: AppLink.get_driver_behavior,
payload: {"driver_id": box.read(BoxName.driverID).toString()},
);
if (response != 'failure') {
final json = jsonDecode(response.body);
overallScore.value =
double.parse(json['data']['overall_behavior_score'].toString());
lastTrips.value = json['data']['last_10_trips'];
} else {
// Get.snackbar("Error", json['message'] ?? "Unknown error");
}
} catch (e) {
Get.snackbar("Error", "Exception: $e");
} finally {
isLoading.value = false;
}
}
Future<Map<String, dynamic>> analyzeData() async {
final data = await getAllData();
if (data.isEmpty) return {};
double maxSpeed = 0;
double totalSpeed = 0;
int hardBrakes = 0;
double totalDistance = 0;
double? prevLat, prevLng;
for (var item in data) {
double speed = item['speed'] ?? 0;
double lat = item['lat'] ?? 0;
double lng = item['lng'] ?? 0;
double acc = item['acceleration'] ?? 0;
if (speed > maxSpeed) maxSpeed = speed;
totalSpeed += speed;
// ✅ Hard brake threshold
if (acc.abs() > 3.0) hardBrakes++;
// ✅ Distance between points
if (prevLat != null && prevLng != null) {
totalDistance += _calculateDistance(prevLat, prevLng, lat, lng);
}
prevLat = lat;
prevLng = lng;
}
double avgSpeed = totalSpeed / data.length;
double behaviorScore = 100 - (hardBrakes * 5) - ((maxSpeed > 100) ? 10 : 0);
behaviorScore = behaviorScore.clamp(0, 100);
return {
'max_speed': maxSpeed,
'avg_speed': avgSpeed,
'hard_brakes': hardBrakes,
'total_distance': totalDistance,
'behavior_score': behaviorScore,
};
}
Future<void> sendSummaryToServer(String driverId, String tripId) async {
final summary = await analyzeData();
if (summary.isEmpty) return;
final body = {
'driver_id': driverId,
'trip_id': tripId,
...summary,
};
CRUD().post(link: AppLink.saveBehavior, payload: (body));
await clearData();
}
Future<void> clearData() async {
await sql.deleteAllData(TableName.behavior);
}
double _calculateDistance(
double lat1, double lon1, double lat2, double lon2) {
const p = 0.017453292519943295;
final a = 0.5 -
cos((lat2 - lat1) * p) / 2 +
cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2;
return 12742 * asin(sqrt(a)); // distance in km
}
}

View File

@@ -0,0 +1,78 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:get/get.dart';
import '../../../constant/colors.dart';
import '../../functions/launch.dart';
class ContactUsController extends GetxController {
final String phone1 = '+201018805430';
final String phone2 = '+201080182934';
final TimeOfDay workStartTime = const TimeOfDay(hour: 12, minute: 0);
final TimeOfDay workEndTime = const TimeOfDay(hour: 19, minute: 0);
bool _isWithinWorkTime(TimeOfDay now) {
return (now.hour > workStartTime.hour ||
(now.hour == workStartTime.hour &&
now.minute >= workStartTime.minute)) &&
(now.hour < workEndTime.hour ||
(now.hour == workEndTime.hour && now.minute <= workEndTime.minute));
}
void showContactDialog(BuildContext context) {
TimeOfDay now = TimeOfDay.now();
showCupertinoModalPopup(
context: context,
builder: (context) => CupertinoActionSheet(
title: Text('Contact Us'.tr),
message: Text('Choose a contact option'.tr),
actions: <Widget>[
if (_isWithinWorkTime(now))
CupertinoActionSheetAction(
child: Text(phone1),
onPressed: () => makePhoneCall(
phone1,
),
),
if (_isWithinWorkTime(now))
CupertinoActionSheetAction(
child: Text(phone2),
onPressed: () => makePhoneCall(phone2),
),
if (!_isWithinWorkTime(now))
CupertinoActionSheetAction(
child: Text(
'Work time is from 12:00 - 19:00.\nYou can send a WhatsApp message or email.'
.tr),
onPressed: () => Navigator.pop(context),
),
CupertinoActionSheetAction(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
const Icon(
FontAwesome.whatsapp,
color: AppColor.greenColor,
),
Text('Send WhatsApp Message'.tr),
],
),
onPressed: () =>
launchCommunication('whatsapp', phone1, 'Hello'.tr),
),
CupertinoActionSheetAction(
child: Text('Send Email'.tr),
onPressed: () =>
launchCommunication('email', 'support@sefer.live', 'Hello'.tr),
),
],
cancelButton: CupertinoActionSheetAction(
child: Text('Cancel'.tr),
onPressed: () => Navigator.pop(context),
),
),
);
}
}

View File

@@ -0,0 +1,150 @@
import 'dart:convert';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/models/model/driver/rides_summary_model.dart';
class DurationController extends GetxController {
final data = DurationData;
// late AnimationController animationController;
late List<MonthlyDataModel> rideData;
late List<MonthlyRideModel> rideCountData;
late List<MonthlyPriceDriverModel> ridePriceDriverData;
Map<String, dynamic> jsonData1 = {};
Map<String, dynamic> jsonData2 = {};
bool isLoading = false;
String totalDurationToday = '';
var chartData;
var chartRideCount;
var chartRidePriceDriver;
List monthlyList = [];
@override
void onInit() async {
super.onInit();
await fetchData();
await fetchRideDriver();
await getStaticDriver();
}
getStaticDriver() async {
isLoading = true;
update();
var res = await CRUD().get(
link: AppLink.driverStatistic,
payload: {'driverID': box.read(BoxName.driverID)});
if (res == 'failure') {
monthlyList = [];
isLoading = false;
update();
} else {
monthlyList = jsonDecode(res)['message'];
isLoading = false;
update();
}
}
Future<void> fetchData() async {
isLoading = true;
update(); // Notify the observers about the loading state change
var res = await CRUD().get(
link: AppLink.getTotalDriverDuration,
payload: {'driver_id': box.read(BoxName.driverID)},
);
jsonData1 = jsonDecode(res);
var jsonResponse = jsonDecode(res) as Map<String, dynamic>;
isLoading = false;
final List<dynamic> jsonData = jsonResponse['message'];
rideData = jsonData.map<MonthlyDataModel>((item) {
return MonthlyDataModel.fromJson(item);
}).toList();
final List<FlSpot> spots = rideData
.map((data) => FlSpot(
data.day.toDouble(),
data.totalDuration.toDouble(),
))
.toList();
chartData = spots;
update(); // Notify the observers about the data and loading state change
}
Future<void> fetchRideDriver() async {
isLoading = true;
update(); // Notify the observers about the loading state change
var res = await CRUD().get(
link: AppLink.getRidesDriverByDay,
payload: {'driver_id': box.read(BoxName.driverID)},
);
if (res != 'failure') {
jsonData2 = jsonDecode(res);
var jsonResponse = jsonDecode(res) as Map<String, dynamic>;
isLoading = false;
final List<dynamic> jsonData = jsonResponse['message'];
rideCountData = jsonData.map<MonthlyRideModel>((item) {
return MonthlyRideModel.fromJson(item);
}).toList();
ridePriceDriverData = jsonData.map<MonthlyPriceDriverModel>((item) {
return MonthlyPriceDriverModel.fromJson(item);
}).toList();
final List<FlSpot> spots = rideCountData
.map((data) => FlSpot(
data.day.toDouble(),
data.countRide.toDouble(),
))
.toList();
chartRideCount = spots;
final List<FlSpot> spotsDriverPrices = ridePriceDriverData
.map((data) => FlSpot(
data.day.toDouble(),
data.pricePerDay.toDouble(),
))
.toList();
chartRidePriceDriver = spotsDriverPrices;
update(); // Notify the observers about the data and loading state change
} else {
Get.defaultDialog(
title: 'No data yet!'.tr,
middleText: '',
confirm: MyElevatedButton(
title: 'OK'.tr,
onPressed: () {
Get.back();
Get.back();
}));
}
}
List<DurationData> parseData(List<dynamic> json) {
return json.map((entry) {
final Map<String, dynamic> entryMap = entry;
final day = DateTime.parse(entryMap['day']);
final totalDuration = _parseDuration(entryMap['total_duration']);
return DurationData(day, totalDuration);
}).toList();
}
Duration _parseDuration(String durationString) {
final parts = durationString.split(':');
final hours = int.parse(parts[0]);
final minutes = int.parse(parts[1]);
final seconds = int.parse(parts[2]);
return Duration(hours: hours, minutes: minutes, seconds: seconds);
}
}
class DurationData {
final DateTime day;
final Duration totalDuration;
DurationData(this.day, this.totalDuration);
}

View File

@@ -0,0 +1,58 @@
import 'dart:convert';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:get/get.dart';
class AssuranceHealthController extends GetxController {
bool isLoading = false;
Map tripCount = {};
Future getTripCountByCaptain() async {
var res = await CRUD().get(link: AppLink.getTripCountByCaptain, payload: {
"driver_id": box.read(BoxName.driverID).toString(),
});
if (res != 'failure') {
tripCount = jsonDecode(res)['message'];
update();
}
}
Future<void> addDriverHealthAssurance({
String? driverId,
String? assured,
required String healthInsuranceProvider,
}) async {
// Define the URL to your PHP backend
// Data to be sent to the backend
Map<String, String> data = {
"driver_id": box.read(BoxName.driverID).toString(),
"assured": '1',
"health_insurance_provider": healthInsuranceProvider,
};
try {
// Send the POST request to your backend
var response = await CRUD()
.post(link: AppLink.addHealthInsuranceProvider, payload: data);
if (response != 'failure') {
// Handle success (e.g., show a success message)
mySnackbarSuccess(
"You have successfully opted for health insurance.".tr);
} else {
// Handle failure (e.g., show an error message)
print("Failed to save health assurance data");
mySnackeBarError("Please enter a health insurance status.".tr);
}
} catch (e) {
// Handle any errors
print("Error: $e");
}
}
}

View File

@@ -0,0 +1,103 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../constant/box_name.dart';
import '../../../../constant/links.dart';
import '../../../../constant/style.dart';
import '../../../../main.dart';
import '../../../../views/widgets/elevated_btn.dart';
import '../../../functions/crud.dart';
import '../../../functions/encrypt_decrypt.dart';
class HelpController extends GetxController {
bool isLoading = false;
final formKey = GlobalKey<FormState>();
final helpQuestionController = TextEditingController();
Map helpQuestionDate = {};
Map helpQuestionRepleyDate = {};
String status = '';
String qustion = '';
late int indexQuestion = 0;
getIndex(int i, String qustion1) async {
indexQuestion = i;
qustion = qustion1;
update();
}
void addHelpQuestion() async {
isLoading = true;
update();
var res = await CRUD().post(link: AppLink.addhelpCenter, payload: {
'driverID': box.read(BoxName.driverID).toString(),
'helpQuestion': (helpQuestionController.text)
});
var d = jsonDecode(res);
isLoading = false;
update();
if (d['status'].toString() == 'success') {
getHelpQuestion();
// Get.snackbar('Feedback data saved successfully'.tr, '',
// backgroundColor: AppColor.greenColor,
// snackPosition: SnackPosition.BOTTOM);
}
}
void getHelpQuestion() async {
isLoading = true;
update();
var res = await CRUD().get(link: AppLink.gethelpCenter, payload: {
'driverID': box.read(BoxName.driverID).toString(),
});
if (res == "failure") {
isLoading = false;
update();
Get.defaultDialog(
title: 'There is no help Question here'.tr,
titleStyle: AppStyle.title,
middleText: '',
confirm: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
MyElevatedButton(
title: 'Add Question'.tr,
onPressed: () {
Get.back();
}),
MyElevatedButton(
title: 'Back'.tr,
onPressed: () {
Get.back();
Get.back();
}),
],
));
}
helpQuestionDate = jsonDecode(res);
isLoading = false;
update();
}
Future getHelpRepley(String id) async {
isLoading = true;
update();
var res = await CRUD().get(link: AppLink.getByIdhelpCenter, payload: {
'id': id,
});
if (res == "failure") {
status = 'not yet';
isLoading = false;
update();
}
helpQuestionRepleyDate = jsonDecode(res);
isLoading = false;
update();
}
@override
void onInit() {
getHelpQuestion();
super.onInit();
}
}

View File

@@ -0,0 +1,22 @@
import 'dart:convert';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/main.dart';
import 'package:get/get.dart';
class MaintainCenterController extends GetxController {
bool isLoading = false;
Map tripCount = {};
Future getTripCountByCaptain() async {
var res = await CRUD().get(link: AppLink.getTripCountByCaptain, payload: {
"driver_id": box.read(BoxName.driverID).toString(),
});
if (res != 'failure') {
tripCount = jsonDecode(res)['message'];
update();
}
}
}

View File

@@ -0,0 +1,69 @@
import 'dart:convert';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/print.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';
class VideoController extends GetxController {
var videos = [];
var isLoading = true.obs;
final String apiUrl =
'${AppLink.seferCairoServer}/ride/videos_driver/get.php';
@override
void onInit() {
fetchVideos();
super.onInit();
}
late VideoPlayerController videoPlayerController;
// Initialize the video player with the provided URL
Future<void> initializeVideo(String videoUrl) async {
videoPlayerController =
VideoPlayerController.networkUrl(Uri.parse(videoUrl));
await videoPlayerController.initialize();
videoPlayerController
.setLooping(true); // Set to true if you want the video to loop
update(); // Update the UI after the video has been initialized
}
// Play the video
void play() {
videoPlayerController.play();
update();
}
// Pause the video
void pause() {
videoPlayerController.pause();
update();
}
@override
void onClose() {
videoPlayerController
.dispose(); // Dispose of the video player controller when not in use
super.onClose();
}
void fetchVideos() async {
try {
var res = await CRUD().get(link: apiUrl, payload: {});
if (res != 'failure') {
videos = jsonDecode(res)['message'];
// Log.print('videos: ${videos}');
update();
} else {
mySnackeBarError('');
}
} catch (e) {
mySnackeBarError(e.toString());
} finally {
isLoading(false);
}
}
}

View File

@@ -0,0 +1,454 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/controller/home/captin/map_driver_controller.dart';
import 'dart:async';
import '../../../constant/links.dart';
import '../../../constant/style.dart';
import '../../../constant/table_names.dart';
import '../../../main.dart';
import '../../../print.dart';
import '../../../views/home/my_wallet/walet_captain.dart';
import '../../../views/widgets/elevated_btn.dart';
import '../../firebase/firbase_messge.dart';
import '../../functions/crud.dart';
import '../../functions/location_background_controller.dart';
import '../../functions/location_controller.dart';
import '../payment/captain_wallet_controller.dart';
class HomeCaptainController extends GetxController {
bool isActive = false;
DateTime? activeStartTime;
Duration activeDuration = Duration.zero;
Timer? activeTimer;
Map data = {};
BitmapDescriptor carIcon = BitmapDescriptor.defaultMarker;
bool isLoading = true;
late double kazan = 0;
double latePrice = 0;
double heavyPrice = 0;
double comfortPrice = 0,
speedPrice = 0,
deliveryPrice = 0,
mashwariPrice = 0,
fuelPrice = 0;
double naturePrice = 0;
bool isCallOn = false;
String totalMoneyToday = '0';
double? rating = 5;
String rideId = '0';
String countRideToday = '0';
String totalMoneyInSEFER = '0';
String totalDurationToday = '0';
Timer? timer;
late LatLng myLocation = const LatLng(32, 36);
String totalPoints = '0';
String countRefuse = '0';
bool mapType = false;
bool mapTrafficON = false;
double widthMapTypeAndTraffic = 50;
// Inject the LocationController class
final locationController = Get.put(LocationController());
// final locationBackController = Get.put(LocationBackgroundController());
String formatDuration(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, "0");
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
return "${duration.inHours}:$twoDigitMinutes:$twoDigitSeconds";
}
void goToWalletFromConnect() {
Get.back();
Get.back();
Get.to(() => WalletCaptainRefactored());
}
void changeRideId() {
rideId = 'rideId';
update();
}
void addCustomCarIcon() {
ImageConfiguration config = ImageConfiguration(
size: const Size(30, 35), devicePixelRatio: Get.pixelRatio);
BitmapDescriptor.asset(
config,
'assets/images/car.png',
// mipmaps: false,
).then((value) {
carIcon = value;
update();
});
}
String stringActiveDuration = '';
void onButtonSelected() {
// totalPoints = Get.find<CaptainWalletController>().totalPoints;
isActive = !isActive;
if (isActive) {
if (double.parse(totalPoints) > -300) {
locationController.startLocationUpdates();
HapticFeedback.heavyImpact();
// locationBackController.startBackLocation();
activeStartTime = DateTime.now();
activeTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
activeDuration = DateTime.now().difference(activeStartTime!);
stringActiveDuration = formatDuration(activeDuration);
update();
});
} else {
locationController.stopLocationUpdates();
activeStartTime = null;
activeTimer?.cancel();
savePeriod(activeDuration);
activeDuration = Duration.zero;
update();
}
} else {
locationController.stopLocationUpdates();
activeStartTime = null;
activeTimer?.cancel();
savePeriod(activeDuration);
activeDuration = Duration.zero;
update();
}
// }
}
void getRefusedOrderByCaptain() async {
DateTime today = DateTime.now();
int todayDay = today.day;
String driverId = box.read(BoxName.driverID).toString();
String customQuery = '''
SELECT COUNT(*) AS count
FROM ${TableName.driverOrdersRefuse}
WHERE driver_id = '$driverId'
AND created_at LIKE '%$todayDay%'
''';
try {
List<Map<String, dynamic>> results =
await sql.getCustomQuery(customQuery);
countRefuse = results[0]['count'].toString();
update();
if (int.parse(countRefuse) > 3 || double.parse(totalPoints) <= -3000) {
locationController.stopLocationUpdates();
activeStartTime = null;
activeTimer?.cancel();
savePeriod(activeDuration);
activeDuration = Duration.zero;
update();
Get.defaultDialog(
// backgroundColor: CupertinoColors.destructiveRed,
barrierDismissible: false,
title: 'You Are Stopped For this Day !'.tr,
content: Text(
'You Refused 3 Rides this Day that is the reason \nSee you Tomorrow!'
.tr,
style: AppStyle.title,
),
confirm: MyElevatedButton(
title: 'Ok , See you Tomorrow'.tr,
onPressed: () {
Get.back();
Get.back();
}));
}
} catch (e) {}
}
void changeMapType() {
mapType = !mapType;
// heightButtomSheetShown = isButtomSheetShown == true ? 240 : 0;
update();
}
void changeMapTraffic() {
mapTrafficON = !mapTrafficON;
update();
}
// late GoogleMapController mapHomeCaptainController;
// void onMapCreated(GoogleMapController controller) {
// mapHomeCaptainController = controller;
// controller.getVisibleRegion();
// // Animate camera to user location (optional)
// controller.animateCamera(
// CameraUpdate.newLatLng(Get.find<LocationController>().myLocation),
// );
// }
GoogleMapController? mapHomeCaptainController; // Nullable controller
void onMapCreated(GoogleMapController controller) {
mapHomeCaptainController = controller;
// Optional: Check if the controller is still null (just for safety)
if (mapHomeCaptainController != null) {
// Get the visible region
controller.getVisibleRegion();
// Animate camera to user location (optional)
controller.animateCamera(
CameraUpdate.newLatLng(Get.find<LocationController>().myLocation),
);
} else {}
}
void savePeriod(Duration period) {
final periods = box.read<List<dynamic>>(BoxName.periods) ?? [];
periods.add(period.inSeconds);
box.write(BoxName.periods, periods);
}
Duration calculateTotalDuration() {
final periods = box.read<List<dynamic>>(BoxName.periods) ?? [];
Duration totalDuration = Duration.zero;
for (dynamic periodInSeconds in periods) {
final periodDuration = Duration(seconds: periodInSeconds);
totalDuration += periodDuration;
}
return totalDuration;
}
void startPeriodicExecution() {
Timer.periodic(const Duration(seconds: 30), (timer) async {
await getCaptainDurationOnToday();
});
}
void stopTimer() {
timer?.cancel();
}
getlocation() async {
isLoading = true;
update();
await Get.find<LocationController>().getLocation();
isLoading = false;
update();
}
Map walletDriverPointsDate = {};
Future getCaptainWalletFromBuyPoints() async {
// isLoading = true;
update();
var res = await CRUD().get(
link: AppLink.getDriverPaymentPoints,
payload: {'driverID': box.read(BoxName.driverID).toString()},
);
isLoading = false;
// update();
if (res != 'failure') {
walletDriverPointsDate = jsonDecode(res);
double totalPointsDouble = double.parse(
walletDriverPointsDate['message'][0]['total_amount'].toString());
totalPoints = totalPointsDouble.toStringAsFixed(0);
update();
} else {
totalPoints = '0';
}
}
@override
void onInit() async {
// await locationBackController.requestLocationPermission();
Get.put(FirebaseMessagesController());
addToken();
await getlocation();
onButtonSelected();
getDriverRate();
addCustomCarIcon();
getKazanPercent();
getPaymentToday();
getCountRideToday();
getAllPayment();
startPeriodicExecution();
getCaptainWalletFromBuyPoints();
onMapCreated(mapHomeCaptainController!);
// totalPoints = Get.find<CaptainWalletController>().totalPoints.toString();
getRefusedOrderByCaptain();
// LocationController().getLocation();
super.onInit();
}
// void getRefusedOrderByCaptain() async {
// // Get today's date in YYYY-MM-DD format
// String today = DateTime.now().toString().substring(0, 10);
// String driverId = box.read(BoxName.driverID).toString();
// String customQuery = '''
// SELECT COUNT(*) AS count
// FROM ${TableName.driverOrdersRefuse}
// WHERE driver_id = '$driverId'
// AND DATE(created_at) = '$today'
// ''';
// try {
// List<Map<String, dynamic>> results =
// await sql.getCustomQuery(customQuery);
// countRefuse = results[0]['count'].toString();
// update();
// if (int.parse(countRefuse) > 3) {
// box.write(BoxName.statusDriverLocation, 'on');
// locationController.stopLocationUpdates();
// Get.defaultDialog(
// // backgroundColor: CupertinoColors.destructiveRed,
// barrierDismissible: false,
// title: 'You Are Stopped For this Day !'.tr,
// content: Text(
// 'You Refused 3 Rides this Day that is the reason \nSee you Tomorrow!'
// .tr,
// style: AppStyle.title,
// ),
// confirm: MyElevatedButton(
// title: 'Ok , See you Tomorrow'.tr,
// onPressed: () => Get.back()));
// } else {
// box.write(BoxName.statusDriverLocation, 'off');
// }
// } catch (e) {}
// }
addToken() async {
String? fingerPrint = await storage.read(key: BoxName.fingerPrint);
CRUD().post(link: AppLink.addTokensDriver, payload: {
'token': (box.read(BoxName.tokenDriver)),
'captain_id': (box.read(BoxName.driverID)).toString(),
'fingerPrint': (fingerPrint).toString()
});
// CRUD().post(
// link: "${AppLink.seferAlexandriaServer}/ride/firebase/addDriver.php",
// payload: {
// 'token': box.read(BoxName.tokenDriver),
// 'captain_id': box.read(BoxName.driverID).toString(),
// 'fingerPrint': (fingerPrint).toString()
// });
// CRUD().post(
// link: "${AppLink.seferGizaServer}/ride/firebase/addDriver.php",
// payload: {
// 'token': box.read(BoxName.tokenDriver),
// 'captain_id': box.read(BoxName.driverID).toString(),
// 'fingerPrint': (fingerPrint).toString()
// });
await CRUD().postWallet(
link: "${AppLink.seferPaymentServer}/ride/firebase/addDriver.php",
payload: {
'token': box.read(BoxName.tokenDriver),
'captain_id': box.read(BoxName.driverID).toString(),
'fingerPrint': (fingerPrint).toString()
});
// MapDriverController().driverCallPassenger();
// box.write(BoxName.statusDriverLocation, 'off');
}
getPaymentToday() async {
var res = await CRUD().get(
link: AppLink.getDriverPaymentToday,
payload: {'driverID': box.read(BoxName.driverID).toString()});
if (res != 'failure') {
data = jsonDecode(res);
totalMoneyToday = data['message'][0]['todayAmount'].toString();
update();
} else {}
}
getKazanPercent() async {
var res = await CRUD().get(
link: AppLink.getKazanPercent,
payload: {'country': box.read(BoxName.countryCode).toString()},
);
if (res != 'failure') {
var json = jsonDecode(res);
kazan = double.parse(json['message'][0]['kazan']);
naturePrice = double.parse(json['message'][0]['naturePrice']);
heavyPrice = double.parse(json['message'][0]['heavyPrice']);
latePrice = double.parse(json['message'][0]['latePrice']);
comfortPrice = double.parse(json['message'][0]['comfortPrice']);
speedPrice = double.parse(json['message'][0]['speedPrice']);
deliveryPrice = double.parse(json['message'][0]['deliveryPrice']);
mashwariPrice = double.parse(json['message'][0]['freePrice']);
fuelPrice = double.parse(json['message'][0]['fuelPrice']);
}
update();
}
double mpg = 0;
calculateConsumptionFuel() {
mpg = fuelPrice / 12; //todo in register car add mpg in box
}
getCountRideToday() async {
var res = await CRUD().get(
link: AppLink.getCountRide,
payload: {'driver_id': box.read(BoxName.driverID).toString()});
data = jsonDecode(res);
countRideToday = data['message'][0]['count'].toString();
update();
}
getDriverRate() async {
var res = await CRUD().get(
link: AppLink.getDriverRate,
payload: {'driver_id': box.read(BoxName.driverID).toString()});
if (res != 'failure') {
var decod = jsonDecode(res);
if (decod['message'][0]['rating'] != null) {
rating = double.parse(decod['message'][0]['rating'].toString());
} else {
rating = 5.0; // Set a default value (e.g., 5.0 for full rating)
}
} else {
rating = 5;
}
}
getAllPayment() async {
var res = await CRUD().get(
link: AppLink.getAllPaymentFromRide,
payload: {'driverID': box.read(BoxName.driverID).toString()});
data = jsonDecode(res);
totalMoneyInSEFER = data['message'][0]['total_amount'] ?? '0';
update();
}
void changeToAppliedRide(String status) {
box.write(BoxName.rideStatus, status);
Log.print('rideStatus from homcaptain : ${box.read(BoxName.rideStatus)}');
update();
}
Future<void> getCaptainDurationOnToday() async {
var res = await CRUD().get(
link: AppLink.getTotalDriverDurationToday,
payload: {'driver_id': box.read(BoxName.driverID).toString()});
data = jsonDecode(res);
totalDurationToday = data['message'][0]['total_duration'];
update();
}
@override
void dispose() {
activeTimer?.cancel();
stopTimer();
super.dispose();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,282 @@
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/main.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'dart:math' as math;
import '../../../constant/box_name.dart';
import '../../../print.dart';
import '../../functions/audio_controller.dart';
import '../../functions/crud.dart';
import '../../functions/encrypt_decrypt.dart';
import '../../functions/location_controller.dart';
import 'home_captain_controller.dart';
class OrderRequestController extends GetxController {
double progress = 0;
double progressSpeed = 0;
int duration = 15;
int durationSpeed = 20;
int remainingTime = 0;
int remainingTimeSpeed = 0;
String countRefuse = '0';
bool applied = false;
final locationController = Get.put(LocationController());
BitmapDescriptor startIcon = BitmapDescriptor.defaultMarker;
BitmapDescriptor endIcon = BitmapDescriptor.defaultMarker;
final arguments = Get.arguments;
var myList;
late int hours;
late int minutes;
GoogleMapController? mapController; // Make it nullable
@override
Future<void> onInit() async {
print('OrderRequestController onInit called');
await initializeOrderPage();
bool isOverlayActive = await FlutterOverlayWindow.isActive();
if (isOverlayActive) {
await FlutterOverlayWindow.closeOverlay();
}
addCustomStartIcon();
addCustomEndIcon();
startTimer(
myList[6].toString(),
myList[16].toString(),
);
update();
super.onInit();
}
late LatLngBounds bounds;
late List<LatLng> pointsDirection;
late String body;
late double latPassengerLocation;
late double lngPassengerLocation;
late double lngPassengerDestination;
late double latPassengerDestination;
Future<void> initializeOrderPage() async {
final myListString = Get.arguments['myListString'];
if (Get.arguments['DriverList'] == null ||
Get.arguments['DriverList'].isEmpty) {
myList = jsonDecode(myListString);
Log.print('myList from myListString: ${myList}');
} else {
myList = Get.arguments['DriverList'];
Log.print('myList from DriverList: ${myList}');
}
body = Get.arguments['body'];
Duration durationToAdd =
Duration(seconds: (double.tryParse(myList[4]) ?? 0).toInt());
hours = durationToAdd.inHours;
minutes = (durationToAdd.inMinutes % 60).round();
startTimerSpeed(myList[6].toString(), body.toString());
// --- Using the provided logic for initialization ---
var cords = myList[0].toString().split(',');
var cordDestination = myList[1].toString().split(',');
double? parseDouble(String value) {
try {
return double.parse(value);
} catch (e) {
Log.print("Error parsing value: $value");
return null; // or handle the error appropriately
}
}
latPassengerLocation = parseDouble(cords[0]) ?? 0.0;
lngPassengerLocation = parseDouble(cords[1]) ?? 0.0;
latPassengerDestination = parseDouble(cordDestination[0]) ?? 0.0;
lngPassengerDestination = parseDouble(cordDestination[1]) ?? 0.0;
pointsDirection = [
LatLng(latPassengerLocation, lngPassengerLocation),
LatLng(latPassengerDestination, lngPassengerDestination)
];
Log.print('pointsDirection: $pointsDirection');
calculateBounds();
update();
}
void onMapCreated(GoogleMapController controller) {
mapController = controller;
animateCameraToBounds();
}
void calculateBounds() {
double minLat = math.min(latPassengerLocation, latPassengerDestination);
double maxLat = math.max(latPassengerLocation, latPassengerDestination);
double minLng = math.min(lngPassengerLocation, lngPassengerDestination);
double maxLng = math.max(lngPassengerLocation, lngPassengerDestination);
bounds = LatLngBounds(
southwest: LatLng(minLat, minLng),
northeast: LatLng(maxLat, maxLng),
);
Log.print('Calculated Bounds: $bounds');
}
void animateCameraToBounds() {
if (mapController != null) {
mapController!.animateCamera(CameraUpdate.newLatLngBounds(bounds, 80.0));
} else {
Log.print('mapController is null, cannot animate camera.');
}
}
getRideDEtailsForBackgroundOrder(String rideId) async {
await CRUD().get(link: AppLink.getRidesDetails, payload: {
'id': rideId,
});
}
void addCustomStartIcon() async {
ImageConfiguration config = const ImageConfiguration(size: Size(30, 30));
BitmapDescriptor.asset(
config,
'assets/images/A.png',
).then((value) {
startIcon = value;
update();
});
}
void addCustomEndIcon() {
ImageConfiguration config = const ImageConfiguration(size: Size(30, 30));
BitmapDescriptor.asset(
config,
'assets/images/b.png',
).then((value) {
endIcon = value;
update();
});
}
void changeApplied() {
applied = true;
update();
}
double mpg = 0;
calculateConsumptionFuel() {
mpg = Get.find<HomeCaptainController>().fuelPrice / 12;
}
bool _timerActive = false;
Future<void> startTimer(String driverID, String orderID) async {
_timerActive = true;
for (int i = 0; i <= duration && _timerActive; i++) {
await Future.delayed(const Duration(seconds: 1));
progress = i / duration;
remainingTime = duration - i;
update();
}
if (remainingTime == 0 && _timerActive) {
if (applied == false) {
endTimer();
refuseOrder(orderID);
}
}
}
void endTimer() {
_timerActive = false;
}
void startTimerSpeed(String driverID, orderID) async {
for (int i = 0; i <= durationSpeed; i++) {
await Future.delayed(const Duration(seconds: 1));
progressSpeed = i / durationSpeed;
remainingTimeSpeed = durationSpeed - i;
update();
}
if (remainingTimeSpeed == 0) {
if (applied == false) {
Get.back();
}
}
}
void refuseOrder(
orderID,
) async {
await CRUD().postFromDialogue(link: AppLink.addDriverOrder, payload: {
'driver_id': box.read(BoxName.driverID),
'order_id': (orderID),
'status': 'Refused'
});
await CRUD().post(link: AppLink.updateRides, payload: {
'id': (orderID),
'status': 'Refused',
'driver_id': box.read(BoxName.driverID),
});
if (AppLink.endPoint != AppLink.seferCairoServer) {
CRUD().post(link: '${AppLink.endPoint}/rides/update.php', payload: {
'id': (orderID),
'status': 'Refused',
'driver_id': box.read(BoxName.driverID),
});
}
update();
}
addRideToNotificationDriverString(
orderID,
String startLocation,
String endLocation,
String date,
String time,
String price,
String passengerId,
String status,
String carType,
String passengerRate,
String priceForPassenger,
String distance,
String duration,
) async {
await CRUD().post(link: AppLink.addWaitingRide, payload: {
'id': (orderID),
'start_location': startLocation,
'end_location': endLocation,
'date': date,
'time': time,
'price': price,
'passenger_id': (passengerId),
'status': status,
'carType': carType,
'passengerRate': passengerRate,
'price_for_passenger': priceForPassenger,
'distance': distance,
'duration': duration,
});
if (AppLink.endPoint != AppLink.seferCairoServer) {
CRUD().post(
link: '${AppLink.endPoint}/notificationCaptain/addWaitingRide.php',
payload: {
'id': (orderID),
'start_location': startLocation,
'end_location': endLocation,
'date': date,
'time': time,
'price': price,
'passenger_id': (passengerId),
'status': status,
'carType': carType,
'passengerRate': passengerRate,
'price_for_passenger': priceForPassenger,
'distance': distance,
'duration': duration,
});
}
}
}