feat: N1d/N2/N3 + قانون فلاتر وإعادة ضبط تطبيق السائق
الباك إند: - تعيين أول أدمن صار يُنشئ المستخدم إن لم يوجد — كان يشترط دخولاً سابقاً، وهي بيضة ودجاجة تمنع الدخول إلى لوحة أي مستأجر جديد أصلاً. - OTP_DEV_MODE كان يفشل مفتوحاً (`!== 'false'`): غياب المتغيّر أو خطأ مطبعي يترك الإنتاج برمز ثابت يفتح كل حساب، ويحرس السحب المالي كذلك. صار `=== 'true'` في الإعداد وفي قارئَيه، مع تحذير عند الإقلاع. - N2: التحقّق من اللوغو عند الرفع (PNG/JPEG · 512+ · مربّع · سقف 5MB) عبر قراءة الترويسة بلا اعتمادية — بدل اكتشاف أيقونة ممطوطة بعد النشر. N3: السكربت يولّد build_config.dart بأعلام const (طبقات docs/22 §1.5)، ويضبط bundle IDs واسم التطبيق والأيقونات/splash، و--build يشغّل Shorebird. فلاتر: - docs/23: قانون مُلزِم للتطبيقين (البنية · Cubit · طبقة الشبكة · الأعلام). - السائق: أُزيل Dart القديم (GetX) مع الإبقاء على الأصيل والإضافات وشهادات التوقيع وShorebird وFirebase الخاص به، وأُعيد هيكلته مطابقاً للراكب. - طبقة الشبكة ترسل x-device-id وتجدّد التوكن عند 401 مرة واحدة فقط. - الحزم موحّدة بين التطبيقين، والـAPI https حصراً في الاثنين. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
3ab74a13a8
commit
de4bbd00ac
@@ -1,146 +0,0 @@
|
||||
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';
|
||||
import '../../../print.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);
|
||||
|
||||
overallScore.value =
|
||||
double.parse(json['message']['overall_behavior_score'].toString());
|
||||
lastTrips.value = json['message']['last_10_trips'];
|
||||
} else {
|
||||
// Get.snackbar("Error", json['message'] ?? "Unknown error");
|
||||
}
|
||||
} catch (e) {
|
||||
// Get.snackbar("Error", "Exception: $e");
|
||||
Log.print('e: ${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;
|
||||
DateTime? prevTime;
|
||||
|
||||
// ترتيب البيانات حسب الوقت لضمان دقة الحساب (اختياري لكن مفضل)
|
||||
// data.sort((a, b) => a['created_at'].compareTo(b['created_at']));
|
||||
|
||||
for (var item in data) {
|
||||
// 1. قراءة البيانات بالأسماء الصحيحة من الجدول
|
||||
double lat = item['latitude'] ?? item['lat'] ?? 0.0;
|
||||
double lng = item['longitude'] ?? item['lng'] ?? 0.0;
|
||||
double acc = item['acceleration'] ?? 0.0;
|
||||
|
||||
// قراءة الوقت لحساب السرعة
|
||||
DateTime currentTime =
|
||||
DateTime.tryParse(item['created_at'].toString()) ?? DateTime.now();
|
||||
|
||||
double currentSpeed = 0;
|
||||
|
||||
// 2. حساب السرعة والمسافة إذا وجدت نقطة سابقة
|
||||
if (prevLat != null && prevLng != null && prevTime != null) {
|
||||
double distKm = _calculateDistance(prevLat, prevLng, lat, lng);
|
||||
int timeDiffSeconds = currentTime.difference(prevTime).inSeconds;
|
||||
|
||||
if (timeDiffSeconds > 0) {
|
||||
// السرعة (كم/س) = (المسافة بالكيلومتر * 3600) / الزمن بالثواني
|
||||
currentSpeed = (distKm * 3600) / timeDiffSeconds;
|
||||
}
|
||||
|
||||
totalDistance += distKm;
|
||||
}
|
||||
|
||||
// تحديث القيم الإحصائية
|
||||
if (currentSpeed > maxSpeed) maxSpeed = currentSpeed;
|
||||
totalSpeed += currentSpeed;
|
||||
|
||||
// حساب الفرملة القوية (يعتمد على التسارع المحفوظ مسبقاً)
|
||||
if (acc.abs() > 3.0) hardBrakes++;
|
||||
|
||||
// حفظ النقطة الحالية لتكون هي "السابقة" في الدورة التالية
|
||||
prevLat = lat;
|
||||
prevLng = lng;
|
||||
prevTime = currentTime;
|
||||
}
|
||||
|
||||
// تجنب القسمة على صفر
|
||||
double avgSpeed = (data.length > 1) ? totalSpeed / (data.length - 1) : 0;
|
||||
|
||||
// حساب تقييم السلوك
|
||||
double behaviorScore = 100 - (hardBrakes * 5) - ((maxSpeed > 100) ? 10 : 0);
|
||||
behaviorScore = behaviorScore.clamp(0.0, 100.0);
|
||||
|
||||
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 Map<String, dynamic> body = {
|
||||
'driver_id': driverId,
|
||||
'trip_id': tripId,
|
||||
...summary, // فيه doubles
|
||||
};
|
||||
|
||||
// اجبر كل القيم على String
|
||||
final payload = body.map((k, v) => MapEntry(k, v?.toString() ?? ''));
|
||||
|
||||
await CRUD().post(link: AppLink.saveBehavior, payload: payload);
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
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 = '+963992952235';
|
||||
final String phone2 = '+963992952235';
|
||||
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 10:00 - 17: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),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
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.server}/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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,740 +0,0 @@
|
||||
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:flutter_map/flutter_map.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
// import 'package:latlong2/latlong.dart'
|
||||
// as latlng; // هذا مهم جداً للتعامل مع إحداثيات OSM
|
||||
import 'package:sefer_driver/constant/box_name.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/background_service.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 = {};
|
||||
bool isHomeMapActive = true;
|
||||
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,
|
||||
familyPrice = 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(33.5138, 36.2765);
|
||||
String totalPoints = '0';
|
||||
String countRefuse = '0';
|
||||
bool mapType = false;
|
||||
bool mapTrafficON = false;
|
||||
double widthMapTypeAndTraffic = 50;
|
||||
// === متغيرات الهيت ماب الجديدة ===
|
||||
bool isHeatmapVisible = false;
|
||||
Set<Polygon> heatmapPolygons =
|
||||
{}; // سنستخدم Polygon لرسم المربعات على جوجل مابس
|
||||
|
||||
// Inject the LocationController class
|
||||
// final locationController = Get.put(LocationController());
|
||||
// الكود الصحيح
|
||||
final locationController = Get.find<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 toggleHeatmap() async {
|
||||
isHeatmapVisible = !isHeatmapVisible;
|
||||
if (isHeatmapVisible) {
|
||||
await fetchAndDrawHeatmap();
|
||||
} else {
|
||||
heatmapPolygons.clear();
|
||||
}
|
||||
update(); // تحديث الواجهة
|
||||
}
|
||||
|
||||
// داخل MapDriverController
|
||||
|
||||
// متغير لتخزين المربعات
|
||||
// Set<Polygon> heatmapPolygons = {};
|
||||
|
||||
// دالة جلب البيانات ورسم الخريطة
|
||||
Future<void> fetchAndDrawHeatmap() async {
|
||||
// استخدم الرابط المباشر لملف JSON لسرعة قصوى
|
||||
final String jsonUrl = "${AppLink.server}/ride/rides/heatmap_live.json";
|
||||
Log.print('jsonUrl: ${jsonUrl}');
|
||||
|
||||
try {
|
||||
// نستخدم timestamp لمنع الكاش من الموبايل نفسه
|
||||
final response = await http.get(
|
||||
Uri.parse("$jsonUrl?t=${DateTime.now().millisecondsSinceEpoch}"));
|
||||
Log.print('heatmap_live: ${response.body}');
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final List<dynamic> data = json.decode(response.body);
|
||||
_generatePolygons(data);
|
||||
}
|
||||
} catch (e) {
|
||||
print("Heatmap Error: $e");
|
||||
}
|
||||
}
|
||||
|
||||
void _generatePolygons(List<dynamic> data) {
|
||||
Set<Polygon> tempPolygons = {};
|
||||
|
||||
// الأوفست لرسم المربع (نصف حجم الشبكة)
|
||||
// الشبكة دقتها 0.01 درجة، لذا نصفها 0.005
|
||||
double offset = 0.005;
|
||||
|
||||
for (var point in data) {
|
||||
double lat = double.parse(point['lat'].toString());
|
||||
double lng = double.parse(point['lng'].toString());
|
||||
|
||||
String intensity = point['intensity'] ?? 'low';
|
||||
int count = int.parse(point['count'].toString()); // ✅ جلب العدد
|
||||
|
||||
Color color;
|
||||
Color strokeColor;
|
||||
|
||||
// 🧠 منطق الألوان: ندمج الذكاء (Intensity) مع العدد (Count)
|
||||
if (intensity == 'high' || count >= 5) {
|
||||
// منطقة مشتعلة (أحمر)
|
||||
// إما فيها طلبات ضائعة (Timeout) أو فيها عدد كبير من الطلبات
|
||||
color = Colors.red.withOpacity(0.35);
|
||||
strokeColor = Colors.red.withOpacity(0.8);
|
||||
} else if (intensity == 'medium' || count >= 3) {
|
||||
// منطقة متوسطة (برتقالي)
|
||||
color = Colors.orange.withOpacity(0.35);
|
||||
strokeColor = Colors.orange.withOpacity(0.8);
|
||||
} else {
|
||||
// منطقة خفيفة (أصفر)
|
||||
color = Colors.yellow.withOpacity(0.3);
|
||||
strokeColor = Colors.yellow.withOpacity(0.6);
|
||||
}
|
||||
|
||||
// رسم المربع
|
||||
tempPolygons.add(Polygon(
|
||||
polygonId: PolygonId("$lat-$lng"),
|
||||
consumeTapEvents: true, // للسماح بالضغط عليه مستقبلاً
|
||||
points: [
|
||||
LatLng(lat - offset, lng - offset),
|
||||
LatLng(lat + offset, lng - offset),
|
||||
LatLng(lat + offset, lng + offset),
|
||||
LatLng(lat - offset, lng + offset),
|
||||
],
|
||||
fillColor: color,
|
||||
strokeColor: strokeColor,
|
||||
strokeWidth: 2,
|
||||
));
|
||||
}
|
||||
|
||||
heatmapPolygons = tempPolygons;
|
||||
update(); // تحديث الخريطة
|
||||
}
|
||||
|
||||
// دالة لتشغيل الخريطة الحرارية كل فترة (مثلاً عند فتح الصفحة)
|
||||
void startHeatmapCycle() {
|
||||
fetchAndDrawHeatmap();
|
||||
// يمكن تفعيل Timer هنا لو أردت تحديثها تلقائياً كل 5 دقائق
|
||||
}
|
||||
|
||||
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() {
|
||||
// تم الإصلاح: التأكد من أن المتحكم موجود قبل استخدامه لتجنب الكراش
|
||||
if (!Get.isRegistered<CaptainWalletController>()) {
|
||||
Get.put(CaptainWalletController());
|
||||
}
|
||||
totalPoints = Get.find<CaptainWalletController>().totalPoints;
|
||||
isActive = !isActive;
|
||||
if (isActive) {
|
||||
if (double.parse(totalPoints) > -200) {
|
||||
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();
|
||||
}
|
||||
// }
|
||||
}
|
||||
|
||||
// متغيرات العداد للحظر
|
||||
RxString remainingBlockTimeStr = "".obs;
|
||||
Timer? _blockTimer;
|
||||
|
||||
/// دالة الفحص والدايلوج
|
||||
void checkAndShowBlockDialog() {
|
||||
String? blockStr = box.read(BoxName.blockUntilDate);
|
||||
if (blockStr == null || blockStr.isEmpty) return;
|
||||
|
||||
DateTime blockExpiry = DateTime.parse(blockStr);
|
||||
DateTime now = DateTime.now();
|
||||
|
||||
if (now.isBefore(blockExpiry)) {
|
||||
// 1. إجبار السائق على وضع الأوفلاين
|
||||
box.write(BoxName.statusDriverLocation, 'blocked');
|
||||
update();
|
||||
|
||||
// 2. بدء العداد
|
||||
_startBlockCountdown(blockExpiry);
|
||||
|
||||
// 3. إظهار الديالوج المانع
|
||||
Get.defaultDialog(
|
||||
title: "حسابك مقيد مؤقتاً ⛔",
|
||||
titleStyle:
|
||||
const TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
|
||||
barrierDismissible: false, // 🚫 ممنوع الإغلاق بالضغط خارجاً
|
||||
onWillPop: () async => false, // 🚫 ممنوع زر الرجوع في الأندرويد
|
||||
content: Obx(() => Column(
|
||||
children: [
|
||||
const Icon(Icons.timer_off_outlined,
|
||||
size: 50, color: Colors.orange),
|
||||
const SizedBox(height: 15),
|
||||
const Text(
|
||||
"لقد تجاوزت حد الإلغاء المسموح به (3 مرات).\nلا يمكنك العمل حتى انتهاء العقوبة.",
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text(
|
||||
remainingBlockTimeStr.value, // 🔥 الوقت يتحدث هنا
|
||||
style: const TextStyle(
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.black87),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
],
|
||||
)),
|
||||
confirm: Obx(() {
|
||||
// الزر يكون مفعلاً فقط عندما ينتهي الوقت
|
||||
bool isFinished = remainingBlockTimeStr.value == "00:00:00" ||
|
||||
remainingBlockTimeStr.value == "Done";
|
||||
return ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: isFinished ? Colors.green : Colors.grey,
|
||||
),
|
||||
onPressed: isFinished
|
||||
? () {
|
||||
Get.back(); // إغلاق الديالوج
|
||||
box.remove(BoxName.blockUntilDate); // إزالة الحظر
|
||||
Get.snackbar("أهلاً بك", "يمكنك الآن استقبال الطلبات",
|
||||
backgroundColor: Colors.green);
|
||||
}
|
||||
: null, // زر معطل
|
||||
child: Text(isFinished ? "Go Online" : "انتظر انتهاء الوقت"),
|
||||
);
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
// الوقت انتهى أصلاً -> تنظيف
|
||||
box.remove(BoxName.blockUntilDate);
|
||||
}
|
||||
}
|
||||
|
||||
/// دالة العداد التنازلي
|
||||
void _startBlockCountdown(DateTime expiry) {
|
||||
_blockTimer?.cancel();
|
||||
_blockTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
DateTime now = DateTime.now();
|
||||
if (now.isAfter(expiry)) {
|
||||
// انتهى الوقت
|
||||
remainingBlockTimeStr.value = "Done";
|
||||
timer.cancel();
|
||||
} else {
|
||||
// حساب الفرق وتنسيقه
|
||||
Duration diff = expiry.difference(now);
|
||||
String twoDigits(int n) => n.toString().padLeft(2, "0");
|
||||
String hours = twoDigits(diff.inHours);
|
||||
String minutes = twoDigits(diff.inMinutes.remainder(60));
|
||||
String seconds = twoDigits(diff.inSeconds.remainder(60));
|
||||
|
||||
remainingBlockTimeStr.value = "$hours:$minutes:$seconds";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_blockTimer?.cancel();
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
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 (double.parse(totalPoints) <= -200) {
|
||||
// if (int.parse(countRefuse) > 3 || double.parse(totalPoints) <= -200) {
|
||||
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;
|
||||
GoogleMapController? mapHomeCaptainController;
|
||||
// final locationController = Get.find<LocationController>();
|
||||
|
||||
// --- FIX 2: Smart Map Creation ---
|
||||
void onMapCreated(GoogleMapController controller) {
|
||||
mapHomeCaptainController = controller;
|
||||
|
||||
// Check actual location before moving camera
|
||||
var currentLoc = locationController.myLocation;
|
||||
if (currentLoc.latitude != 0 && currentLoc.longitude != 0) {
|
||||
controller.animateCamera(
|
||||
CameraUpdate.newLatLng(currentLoc),
|
||||
);
|
||||
} else {
|
||||
// Optional: Move to default city view instead of ocean
|
||||
controller.animateCamera(
|
||||
CameraUpdate.newLatLngZoom(myLocation, 10),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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(minutes: 2), (timer) async {
|
||||
await getCaptainDurationOnToday();
|
||||
});
|
||||
}
|
||||
|
||||
void stopTimer() {
|
||||
timer?.cancel();
|
||||
}
|
||||
|
||||
getlocation() async {
|
||||
isLoading = true;
|
||||
update();
|
||||
// This ensures we try to get a fix, but map doesn't crash if it fails
|
||||
await locationController.getLocation();
|
||||
|
||||
var loc = locationController.myLocation;
|
||||
if (loc.latitude != 0) {
|
||||
myLocation = loc;
|
||||
}
|
||||
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
Map walletDriverPointsDate = {};
|
||||
|
||||
Future getCaptainWalletFromBuyPoints() async {
|
||||
// isLoading = true;
|
||||
update();
|
||||
|
||||
var res = await CRUD().getWallet(
|
||||
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';
|
||||
}
|
||||
}
|
||||
|
||||
// 3. دالة نستدعيها عند قبول الطلب
|
||||
void pauseHomeMapUpdates() {
|
||||
isHomeMapActive = false;
|
||||
update();
|
||||
}
|
||||
|
||||
// 4. دالة نستدعيها عند العودة للصفحة الرئيسية
|
||||
void resumeHomeMapUpdates() {
|
||||
isHomeMapActive = true;
|
||||
// إنعاش الخريطة عند العودة
|
||||
if (mapHomeCaptainController != null) {
|
||||
onMapCreated(mapHomeCaptainController!);
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() async {
|
||||
// ✅ طلب الإذونات أولاً
|
||||
bool permissionsGranted = await PermissionsHelper.requestAllPermissions();
|
||||
|
||||
if (permissionsGranted) {
|
||||
// ✅ بدء الخدمة بعد الحصول على الإذونات
|
||||
await BackgroundServiceHelper.startService();
|
||||
print('✅ Background service started successfully');
|
||||
} else {
|
||||
print('❌ لم يتم منح الإذونات - الخدمة لن تعمل');
|
||||
// اعرض رسالة للمستخدم
|
||||
}
|
||||
// await locationBackController.requestLocationPermission();
|
||||
Get.put(FirebaseMessagesController());
|
||||
addToken();
|
||||
await getlocation();
|
||||
onButtonSelected();
|
||||
addCustomCarIcon();
|
||||
fetchHomeData();
|
||||
// refreshFinancialData();
|
||||
// getAllPayment();
|
||||
startPeriodicExecution();
|
||||
// getCaptainWalletFromBuyPoints();
|
||||
// 🔥 الفحص عند تشغيل التطبيق
|
||||
checkAndShowBlockDialog();
|
||||
box.write(BoxName.statusDriverLocation, 'off');
|
||||
// 2. عدل الليسنر ليصبح مشروطاً
|
||||
locationController.addListener(() {
|
||||
// الشرط الذهبي: إذا كانت الصفحة غير نشطة أو الخريطة غير موجودة، لا تفعل شيئاً
|
||||
if (!isHomeMapActive || mapHomeCaptainController == null || isClosed)
|
||||
return;
|
||||
|
||||
if (isActive) {
|
||||
// isActive الخاصة بالزر "متصل/غير متصل"
|
||||
var loc = locationController.myLocation;
|
||||
if (loc.latitude != 0 && loc.longitude != 0) {
|
||||
try {
|
||||
mapHomeCaptainController!.animateCamera(
|
||||
CameraUpdate.newCameraPosition(
|
||||
CameraPosition(
|
||||
target: loc,
|
||||
zoom: 17.5,
|
||||
tilt: 50.0,
|
||||
bearing: locationController.heading,
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
// التقاط الخطأ بصمت إذا حدث أثناء الانتقال
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
// LocationController().getLocation();
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
addToken() async {
|
||||
String? fingerPrint = await storage.read(key: BoxName.fingerPrint);
|
||||
final payload = {
|
||||
'token': (box.read(BoxName.tokenDriver)),
|
||||
'captain_id': (box.read(BoxName.driverID)).toString(),
|
||||
'fingerPrint': (fingerPrint).toString()
|
||||
};
|
||||
// Log.print('payload: ${payload}');
|
||||
CRUD().post(link: AppLink.addTokensDriver, payload: payload);
|
||||
}
|
||||
|
||||
int morningRideCount = 0;
|
||||
int afternoonRideCount = 0;
|
||||
String weeklyIncome = '0';
|
||||
|
||||
// الدالة الموحدة لجلب كل البيانات المالية دفعة واحدة
|
||||
Future<void> refreshFinancialData() async {
|
||||
isLoading = true; // اختياري
|
||||
update();
|
||||
|
||||
try {
|
||||
var res = await CRUD().post(
|
||||
link: "${AppLink.server}/ride/driverWallet/get_financial_summary.php",
|
||||
payload: {'driverID': box.read(BoxName.driverID).toString()},
|
||||
);
|
||||
|
||||
if (res != 'failure') {
|
||||
// معالجة الرد بذكاء سواء كان String أو Map
|
||||
Map<String, dynamic> body = (res is String) ? jsonDecode(res) : res;
|
||||
|
||||
if (body['status'] == 'success') {
|
||||
// البيانات قد تكون في data أو message
|
||||
var data = body['data'] ?? body['message'];
|
||||
|
||||
// 1. البيانات المالية (من السيرفر المحلي)
|
||||
totalMoneyInSEFER = data['cash_balance']?.toString() ?? '0';
|
||||
totalPoints = double.parse(data['points_balance']?.toString() ?? '0')
|
||||
.toStringAsFixed(0);
|
||||
totalMoneyToday = data['today_income']?.toString() ?? '0';
|
||||
|
||||
// 2. بيانات الرحلات (من السيرفر البعيد - إن وجدت)
|
||||
morningRideCount =
|
||||
int.tryParse(data['morning_count']?.toString() ?? '0') ?? 0;
|
||||
afternoonRideCount =
|
||||
int.tryParse(data['afternoon_count']?.toString() ?? '0') ?? 0;
|
||||
weeklyIncome = data['total_amount_last_week']?.toString() ?? '0';
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print("Error fetching unified summary: $e");
|
||||
} finally {
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
// دالة موحدة لجلب (الرحلات + التقييم + الإعدادات) في طلب واحد
|
||||
Future<void> fetchHomeData() async {
|
||||
// isLoading = true; // اختياري: إذا كنت تريد إظهار لودر
|
||||
// update();
|
||||
|
||||
try {
|
||||
var res = await CRUD().post(
|
||||
link:
|
||||
"${AppLink.server}/ride/kazan/get_home_init.php", // تأكد من المسار الجديد
|
||||
payload: {
|
||||
'driver_id': box.read(BoxName.driverID).toString(),
|
||||
'country': box.read(BoxName.countryCode).toString(),
|
||||
},
|
||||
);
|
||||
|
||||
if (res != 'failure') {
|
||||
var body = (res);
|
||||
if (body['status'] == 'success') {
|
||||
// التعامل مع البيانات القادمة سواء كانت في 'data' أو 'message'
|
||||
var data = body['data'] ?? body['message'];
|
||||
|
||||
// 1. تحديث عدد الرحلات
|
||||
if (data['ride_count'] != null) {
|
||||
countRideToday = data['ride_count'].toString();
|
||||
}
|
||||
|
||||
// 2. تحديث التقييم
|
||||
if (data['rating'] != null) {
|
||||
rating = double.tryParse(data['rating'].toString()) ?? 5.0;
|
||||
}
|
||||
|
||||
// 3. تحديث الأسعار (Kazan)
|
||||
if (data['config'] != null) {
|
||||
var config = data['config'];
|
||||
kazan = double.tryParse(config['kazan']?.toString() ?? '0') ?? 0.0;
|
||||
naturePrice =
|
||||
double.tryParse(config['naturePrice']?.toString() ?? '0') ??
|
||||
0.0;
|
||||
heavyPrice =
|
||||
double.tryParse(config['heavyPrice']?.toString() ?? '0') ?? 0.0;
|
||||
latePrice =
|
||||
double.tryParse(config['latePrice']?.toString() ?? '0') ?? 0.0;
|
||||
comfortPrice =
|
||||
double.tryParse(config['comfortPrice']?.toString() ?? '0') ??
|
||||
0.0;
|
||||
speedPrice =
|
||||
double.tryParse(config['speedPrice']?.toString() ?? '0') ?? 0.0;
|
||||
deliveryPrice =
|
||||
double.tryParse(config['deliveryPrice']?.toString() ?? '0') ??
|
||||
0.0;
|
||||
mashwariPrice =
|
||||
double.tryParse(config['freePrice']?.toString() ?? '0') ?? 0.0;
|
||||
familyPrice =
|
||||
double.tryParse(config['familyPrice']?.toString() ?? '0') ??
|
||||
0.0;
|
||||
fuelPrice =
|
||||
double.tryParse(config['fuelPrice']?.toString() ?? '0') ?? 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print("Error fetching home data: $e");
|
||||
}
|
||||
|
||||
// تحديث الواجهة مرة واحدة فقط بعد جلب كل البيانات
|
||||
// isLoading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
double mpg = 0;
|
||||
calculateConsumptionFuel() {
|
||||
mpg = fuelPrice / 12; //todo in register car add mpg in box
|
||||
}
|
||||
|
||||
getAllPayment() async {
|
||||
var res = await CRUD().getWallet(
|
||||
link: AppLink.getAllPaymentFromRide,
|
||||
payload: {'driverID': box.read(BoxName.driverID).toString()});
|
||||
if (res == 'failure') {
|
||||
totalMoneyInSEFER = '0';
|
||||
} else {
|
||||
data = jsonDecode(res);
|
||||
|
||||
totalMoneyInSEFER = data['message'][0]['total_amount'];
|
||||
}
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
void changeToAppliedRide(String status) {
|
||||
box.write(BoxName.rideStatus, status);
|
||||
Log.print('rideStatus from homcaptain : ${box.read(BoxName.rideStatus)}');
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> getCaptainDurationOnToday() async {
|
||||
try {
|
||||
var res = await CRUD().get(
|
||||
link: AppLink.getTotalDriverDurationToday,
|
||||
payload: {'driver_id': box.read(BoxName.driverID).toString()},
|
||||
);
|
||||
|
||||
if (res == null || res == 'failure') {
|
||||
totalDurationToday = '0';
|
||||
update();
|
||||
return;
|
||||
}
|
||||
|
||||
var data = jsonDecode(res);
|
||||
totalDurationToday = data['message']?[0]?['total_duration'] ?? '0';
|
||||
} catch (e) {
|
||||
print('Error in getCaptainDurationOnToday: $e');
|
||||
totalDurationToday = '0';
|
||||
}
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
activeTimer?.cancel();
|
||||
stopTimer();
|
||||
mapHomeCaptainController?.dispose(); // Dispose controller
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,86 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
|
||||
class NavigationStep {
|
||||
final String instruction;
|
||||
final String maneuver;
|
||||
final double distance;
|
||||
final String duration;
|
||||
final LatLng startLocation;
|
||||
final LatLng endLocation;
|
||||
final String htmlInstructions;
|
||||
|
||||
NavigationStep({
|
||||
required this.instruction,
|
||||
required this.maneuver,
|
||||
required this.distance,
|
||||
required this.duration,
|
||||
required this.startLocation,
|
||||
required this.endLocation,
|
||||
required this.htmlInstructions,
|
||||
});
|
||||
|
||||
factory NavigationStep.fromJson(Map<String, dynamic> json) {
|
||||
return NavigationStep(
|
||||
instruction: json['html_instructions'] ?? '',
|
||||
maneuver: json['maneuver'] ?? 'straight',
|
||||
distance: (json['distance']['value'] ?? 0).toDouble(),
|
||||
duration: json['duration']['text'] ?? '',
|
||||
startLocation: LatLng(
|
||||
json['start_location']['lat'].toDouble(),
|
||||
json['start_location']['lng'].toDouble(),
|
||||
),
|
||||
endLocation: LatLng(
|
||||
json['end_location']['lat'].toDouble(),
|
||||
json['end_location']['lng'].toDouble(),
|
||||
),
|
||||
htmlInstructions: json['html_instructions'] ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
// Get clean instruction text (remove HTML tags)
|
||||
String get cleanInstruction {
|
||||
return instruction
|
||||
.replaceAll(RegExp(r'<[^>]*>'), '')
|
||||
.replaceAll(' ', ' ');
|
||||
}
|
||||
|
||||
// Get instruction icon based on maneuver
|
||||
IconData get instructionIcon {
|
||||
switch (maneuver.toLowerCase()) {
|
||||
case 'turn-left':
|
||||
return Icons.turn_left;
|
||||
case 'turn-right':
|
||||
return Icons.turn_right;
|
||||
case 'turn-slight-left':
|
||||
return Icons.turn_slight_left;
|
||||
case 'turn-slight-right':
|
||||
return Icons.turn_slight_right;
|
||||
case 'turn-sharp-left':
|
||||
return Icons.turn_sharp_left;
|
||||
case 'turn-sharp-right':
|
||||
return Icons.turn_sharp_right;
|
||||
case 'uturn-left':
|
||||
case 'uturn-right':
|
||||
return Icons.u_turn_left;
|
||||
case 'straight':
|
||||
return Icons.straight;
|
||||
case 'ramp-left':
|
||||
return Icons.ramp_left;
|
||||
case 'ramp-right':
|
||||
return Icons.ramp_right;
|
||||
case 'merge':
|
||||
return Icons.merge;
|
||||
case 'fork-left':
|
||||
case 'fork-right':
|
||||
return Icons.call_split;
|
||||
case 'ferry':
|
||||
return Icons.directions_boat;
|
||||
case 'roundabout-left':
|
||||
case 'roundabout-right':
|
||||
return Icons.roundabout_left;
|
||||
default:
|
||||
return Icons.navigation;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'package:google_polyline_algorithm/google_polyline_algorithm.dart';
|
||||
import 'package:sefer_driver/constant/api_key.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/controller/functions/tts.dart';
|
||||
|
||||
import '../../../main.dart';
|
||||
|
||||
/// Handles map-related logic: fetching routes, drawing polylines, and managing markers.
|
||||
class NavigationService extends GetxService {
|
||||
final CRUD _crud = CRUD();
|
||||
final TextToSpeechController _tts = Get.put(TextToSpeechController());
|
||||
|
||||
final RxSet<Marker> markers = <Marker>{}.obs;
|
||||
final RxSet<Polyline> polylines = <Polyline>{}.obs;
|
||||
final RxString currentInstruction = "".obs;
|
||||
|
||||
BitmapDescriptor carIcon = BitmapDescriptor.defaultMarker;
|
||||
BitmapDescriptor passengerIcon = BitmapDescriptor.defaultMarker;
|
||||
BitmapDescriptor startIcon = BitmapDescriptor.defaultMarker;
|
||||
BitmapDescriptor endIcon = BitmapDescriptor.defaultMarker;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
_loadCustomIcons();
|
||||
}
|
||||
|
||||
void _loadCustomIcons() async {
|
||||
carIcon = await _createBitmapDescriptor('assets/images/car.png');
|
||||
passengerIcon = await _createBitmapDescriptor('assets/images/picker.png');
|
||||
startIcon = await _createBitmapDescriptor('assets/images/A.png');
|
||||
endIcon = await _createBitmapDescriptor('assets/images/b.png');
|
||||
}
|
||||
|
||||
Future<BitmapDescriptor> _createBitmapDescriptor(String assetName) {
|
||||
return BitmapDescriptor.fromAssetImage(
|
||||
ImageConfiguration(
|
||||
size: const Size(30, 35), devicePixelRatio: Get.pixelRatio),
|
||||
assetName,
|
||||
);
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>?> getRoute({
|
||||
required LatLng origin,
|
||||
required LatLng destination,
|
||||
}) async {
|
||||
final url =
|
||||
'${AppLink.googleMapsLink}directions/json?language=${box.read(BoxName.lang)}&destination=${destination.latitude},${destination.longitude}&origin=${origin.latitude},${origin.longitude}&key=${AK.mapAPIKEY}';
|
||||
|
||||
final response = await _crud.getGoogleApi(link: url, payload: {});
|
||||
|
||||
if (response != null && response['routes'].isNotEmpty) {
|
||||
return response['routes'][0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void drawRoute(Map<String, dynamic> routeData, {Color color = Colors.blue}) {
|
||||
final pointsString = routeData["overview_polyline"]["points"];
|
||||
final points = decodePolyline(pointsString)
|
||||
.map((p) => LatLng(p[0].toDouble(), p[1].toDouble()))
|
||||
.toList();
|
||||
|
||||
final polyline = Polyline(
|
||||
polylineId: PolylineId(routeData["summary"] ?? DateTime.now().toString()),
|
||||
points: points,
|
||||
width: 8,
|
||||
color: color,
|
||||
);
|
||||
|
||||
polylines.add(polyline);
|
||||
}
|
||||
|
||||
void updateCarMarker(LatLng position, double heading) {
|
||||
markers.removeWhere((m) => m.markerId.value == 'MyLocation');
|
||||
markers.add(
|
||||
Marker(
|
||||
markerId: MarkerId('MyLocation'.tr),
|
||||
position: position,
|
||||
icon: carIcon,
|
||||
rotation: heading,
|
||||
anchor: const Offset(0.5, 0.5),
|
||||
flat: true,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void setInitialMarkers(
|
||||
LatLng passengerLocation, LatLng passengerDestination) {
|
||||
markers.clear();
|
||||
markers.add(Marker(
|
||||
markerId: const MarkerId('passengerLocation'),
|
||||
position: passengerLocation,
|
||||
icon: passengerIcon,
|
||||
));
|
||||
markers.add(Marker(
|
||||
markerId: const MarkerId('passengerDestination'),
|
||||
position: passengerDestination,
|
||||
icon: endIcon,
|
||||
));
|
||||
}
|
||||
|
||||
void clearRoutes() {
|
||||
polylines.clear();
|
||||
currentInstruction.value = "";
|
||||
}
|
||||
}
|
||||
@@ -1,617 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import '../../../constant/box_name.dart';
|
||||
import '../../../constant/links.dart';
|
||||
import '../../../main.dart';
|
||||
import '../../../print.dart';
|
||||
import '../../../views/home/Captin/driver_map_page.dart';
|
||||
import '../../../views/home/Captin/orderCaptin/marker_generator.dart';
|
||||
import '../../../views/widgets/mydialoug.dart';
|
||||
import '../../firebase/local_notification.dart';
|
||||
import '../../functions/crud.dart';
|
||||
import '../../functions/location_controller.dart';
|
||||
import '../../home/captin/home_captain_controller.dart';
|
||||
import '../../firebase/notification_service.dart';
|
||||
import '../navigation/decode_polyline_isolate.dart';
|
||||
|
||||
class OrderRequestController extends GetxController
|
||||
with WidgetsBindingObserver {
|
||||
// --- متغيرات التايمر ---
|
||||
double progress = 1.0;
|
||||
int duration = 15;
|
||||
int remainingTime = 15;
|
||||
Timer? _timer;
|
||||
|
||||
bool applied = false;
|
||||
final locationController = Get.put(LocationController());
|
||||
|
||||
// 🔥 متغير لمنع تكرار القبول
|
||||
bool _isRideTakenHandled = false;
|
||||
|
||||
// --- الأيقونات والماركرز ---
|
||||
BitmapDescriptor? driverIcon;
|
||||
Map<MarkerId, Marker> markersMap = {};
|
||||
Set<Marker> get markers => markersMap.values.toSet();
|
||||
|
||||
// --- البيانات والتحكم ---
|
||||
// 🔥 تم إضافة myMapData لدعم السوكيت الجديد
|
||||
List<dynamic>? myList;
|
||||
Map<dynamic, dynamic>? myMapData;
|
||||
|
||||
GoogleMapController? mapController;
|
||||
|
||||
// الإحداثيات (أزلنا late لتجنب الأخطاء القاتلة)
|
||||
double latPassenger = 0.0;
|
||||
double lngPassenger = 0.0;
|
||||
double latDestination = 0.0;
|
||||
double lngDestination = 0.0;
|
||||
|
||||
// --- متغيرات العرض ---
|
||||
String passengerRating = "5.0";
|
||||
String tripType = "Standard";
|
||||
String totalTripDistance = "--";
|
||||
String totalTripDuration = "--";
|
||||
String tripPrice = "--";
|
||||
|
||||
String timeToPassenger = "جاري الحساب...";
|
||||
String distanceToPassenger = "--";
|
||||
|
||||
// --- الخريطة ---
|
||||
Set<Polyline> polylines = {};
|
||||
|
||||
// حالة التطبيق والصوت
|
||||
bool isInBackground = false;
|
||||
final AudioPlayer audioPlayer = AudioPlayer();
|
||||
|
||||
@override
|
||||
Future<void> onInit() async {
|
||||
// 🛑 حماية من الفتح المتكرر لنفس الطلب
|
||||
if (Get.arguments == null) {
|
||||
print("❌ OrderController Error: No arguments received.");
|
||||
Get.back(); // إغلاق الصفحة فوراً
|
||||
return;
|
||||
}
|
||||
super.onInit();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
|
||||
_checkOverlay();
|
||||
|
||||
// 🔥 تهيئة البيانات هي الخطوة الأولى والأهم
|
||||
_initializeData();
|
||||
_parseExtraData();
|
||||
|
||||
// 1. تجهيز أيقونة السائق
|
||||
await _prepareDriverIcon();
|
||||
|
||||
// 2. وضع الماركرز المبدئية
|
||||
_updateMarkers(
|
||||
paxTime: "...",
|
||||
paxDist: "",
|
||||
destTime: totalTripDuration,
|
||||
destDist: totalTripDistance);
|
||||
|
||||
// 3. رسم مبدئي
|
||||
_initialMapSetup();
|
||||
|
||||
// 4. الاستماع للسوكيت
|
||||
_listenForRideTaken();
|
||||
|
||||
// 5. حساب المسارين
|
||||
await _calculateFullJourney();
|
||||
|
||||
// 6. تشغيل التايمر
|
||||
startTimer();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// 🔥🔥🔥 Smart Data Handling (List & Map Support) 🔥🔥🔥
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
void _initializeData() {
|
||||
var args = Get.arguments;
|
||||
print("📦 Order Controller Received Type: ${args.runtimeType}");
|
||||
print("📦 Order Controller Data: $args");
|
||||
|
||||
if (args != null) {
|
||||
// الحالة 1: قائمة مباشرة (Legacy / Some Firebase formats)
|
||||
if (args is List) {
|
||||
myList = args;
|
||||
}
|
||||
// الحالة 2: خريطة (Map)
|
||||
else if (args is Map) {
|
||||
// أ) هل هي قادمة من Firebase وتحتوي على DriverList؟
|
||||
if (args.containsKey('DriverList')) {
|
||||
var listData = args['DriverList'];
|
||||
if (listData is List) {
|
||||
myList = listData;
|
||||
} else if (listData is String) {
|
||||
// أحياناً تصل كنص مشفر داخل الـ Map
|
||||
try {
|
||||
myList = jsonDecode(listData);
|
||||
} catch (e) {
|
||||
print("Error decoding DriverList: $e");
|
||||
}
|
||||
}
|
||||
}
|
||||
// ب) هل هي قادمة من Socket بالمفاتيح الرقمية ("0", "1", ...)؟
|
||||
else {
|
||||
myMapData = args;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// تعبئة الإحداثيات باستخدام الدالة الذكية _getValueAt
|
||||
latPassenger = _parseCoord(_getValueAt(0));
|
||||
lngPassenger = _parseCoord(_getValueAt(1));
|
||||
latDestination = _parseCoord(_getValueAt(3));
|
||||
lngDestination = _parseCoord(_getValueAt(4));
|
||||
|
||||
print(
|
||||
"📍 Parsed Coordinates: Pax($latPassenger, $lngPassenger) -> Dest($latDestination, $lngDestination)");
|
||||
}
|
||||
|
||||
/// 🔥 دالة ذكية تجلب القيمة سواء كانت البيانات في List أو Map
|
||||
dynamic _getValueAt(int index) {
|
||||
// الأولوية للقائمة
|
||||
if (myList != null && index < myList!.length) {
|
||||
return myList![index];
|
||||
}
|
||||
// ثم الخريطة (السوكيت) - المفاتيح عبارة عن String
|
||||
if (myMapData != null && myMapData!.containsKey(index.toString())) {
|
||||
return myMapData![index.toString()];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// الدالة التي يستخدمها باقي الكود لجلب البيانات كنصوص
|
||||
String _safeGet(int index) {
|
||||
var val = _getValueAt(index);
|
||||
if (val != null) {
|
||||
return val.toString();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
double _parseCoord(dynamic val) {
|
||||
if (val == null) return 0.0;
|
||||
String s = val.toString().replaceAll(',', '').trim();
|
||||
if (s.contains(' ')) s = s.split(' ')[0];
|
||||
return double.tryParse(s) ?? 0.0;
|
||||
}
|
||||
|
||||
void _parseExtraData() {
|
||||
passengerRating = _safeGet(33).isEmpty ? "5.0" : _safeGet(33);
|
||||
tripType = _safeGet(31);
|
||||
totalTripDistance = _safeGet(5);
|
||||
totalTripDuration = _safeGet(19);
|
||||
tripPrice = _safeGet(2);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// 🔥🔥🔥 Core Logic: Concurrent API Calls & Bounds 🔥🔥🔥
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
Future<void> _calculateFullJourney() async {
|
||||
try {
|
||||
Position driverPos = await Geolocator.getCurrentPosition(
|
||||
desiredAccuracy: LocationAccuracy.high);
|
||||
LatLng driverLatLng = LatLng(driverPos.latitude, driverPos.longitude);
|
||||
|
||||
updateDriverLocation(driverLatLng, driverPos.heading);
|
||||
|
||||
var pickupFuture = _fetchRouteData(
|
||||
start: driverLatLng,
|
||||
end: LatLng(latPassenger, lngPassenger),
|
||||
color: Colors.amber,
|
||||
id: 'pickup_route');
|
||||
|
||||
var tripFuture = _fetchRouteData(
|
||||
start: LatLng(latPassenger, lngPassenger),
|
||||
end: LatLng(latDestination, lngDestination),
|
||||
color: Colors.green,
|
||||
id: 'trip_route',
|
||||
isDashed: true);
|
||||
|
||||
var results = await Future.wait([pickupFuture, tripFuture]);
|
||||
|
||||
var pickupResult = results[0];
|
||||
var tripResult = results[1];
|
||||
|
||||
if (pickupResult != null) {
|
||||
distanceToPassenger = pickupResult['distance_text'];
|
||||
timeToPassenger = pickupResult['duration_text'];
|
||||
polylines.add(pickupResult['polyline']);
|
||||
}
|
||||
|
||||
if (tripResult != null) {
|
||||
totalTripDistance = tripResult['distance_text'];
|
||||
totalTripDuration = tripResult['duration_text'];
|
||||
polylines.add(tripResult['polyline']);
|
||||
}
|
||||
|
||||
await _updateMarkers(
|
||||
paxTime: timeToPassenger,
|
||||
paxDist: distanceToPassenger,
|
||||
destTime: totalTripDuration,
|
||||
destDist: totalTripDistance);
|
||||
|
||||
zoomToFitRide(driverLatLng);
|
||||
|
||||
update();
|
||||
} catch (e) {
|
||||
print("❌ Error in Journey Calculation: $e");
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>?> _fetchRouteData(
|
||||
{required LatLng start,
|
||||
required LatLng end,
|
||||
required Color color,
|
||||
required String id,
|
||||
bool isDashed = false}) async {
|
||||
try {
|
||||
// حماية من الإحداثيات الصفرية
|
||||
if (start.latitude == 0 || end.latitude == 0) return null;
|
||||
|
||||
String apiUrl = "https://routesy.intaleq.xyz/route/v1/driving";
|
||||
String coords =
|
||||
"${start.longitude},${start.latitude};${end.longitude},${end.latitude}";
|
||||
String url = "$apiUrl/$coords?steps=false&overview=full";
|
||||
|
||||
var response = await http.get(Uri.parse(url));
|
||||
if (response.statusCode == 200) {
|
||||
var json = jsonDecode(response.body);
|
||||
if (json['code'] == 'Ok' && json['routes'].isNotEmpty) {
|
||||
var route = json['routes'][0];
|
||||
|
||||
double distM = double.parse(route['distance'].toString());
|
||||
double durS = double.parse(route['duration'].toString());
|
||||
|
||||
String distText = "${(distM / 1000).toStringAsFixed(1)} كم";
|
||||
String durText = "${(durS / 60).toStringAsFixed(0)} دقيقة";
|
||||
|
||||
String geometry = route['geometry'];
|
||||
List<LatLng> points = await compute(decodePolylineIsolate, geometry);
|
||||
|
||||
Polyline polyline = Polyline(
|
||||
polylineId: PolylineId(id),
|
||||
color: color,
|
||||
width: 5,
|
||||
points: points,
|
||||
patterns:
|
||||
isDashed ? [PatternItem.dash(10), PatternItem.gap(5)] : [],
|
||||
startCap: Cap.roundCap,
|
||||
endCap: Cap.roundCap,
|
||||
);
|
||||
|
||||
return {
|
||||
'distance_text': distText,
|
||||
'duration_text': durText,
|
||||
'polyline': polyline
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print("Route Fetch Error: $e");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void zoomToFitRide(LatLng driverPos) {
|
||||
if (mapController == null) return;
|
||||
|
||||
// حماية من النقاط الصفرية
|
||||
if (latPassenger == 0 || latDestination == 0) return;
|
||||
|
||||
List<LatLng> points = [
|
||||
driverPos,
|
||||
LatLng(latPassenger, lngPassenger),
|
||||
LatLng(latDestination, lngDestination),
|
||||
];
|
||||
|
||||
double minLat = points.first.latitude;
|
||||
double maxLat = points.first.latitude;
|
||||
double minLng = points.first.longitude;
|
||||
double maxLng = points.first.longitude;
|
||||
|
||||
for (var p in points) {
|
||||
if (p.latitude < minLat) minLat = p.latitude;
|
||||
if (p.latitude > maxLat) maxLat = p.latitude;
|
||||
if (p.longitude < minLng) minLng = p.longitude;
|
||||
if (p.longitude > maxLng) maxLng = p.longitude;
|
||||
}
|
||||
|
||||
mapController!.animateCamera(CameraUpdate.newLatLngBounds(
|
||||
LatLngBounds(
|
||||
southwest: LatLng(minLat, minLng),
|
||||
northeast: LatLng(maxLat, maxLng),
|
||||
),
|
||||
100.0,
|
||||
));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Markers & Setup
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
Future<void> _prepareDriverIcon() async {
|
||||
driverIcon = await MarkerGenerator.createDriverMarker();
|
||||
}
|
||||
|
||||
Future<void> _updateMarkers(
|
||||
{required String paxTime,
|
||||
required String paxDist,
|
||||
String? destTime,
|
||||
String? destDist}) async {
|
||||
// حماية إذا لم يتم جلب الإحداثيات
|
||||
if (latPassenger == 0 || latDestination == 0) return;
|
||||
|
||||
final BitmapDescriptor pickupIcon =
|
||||
await MarkerGenerator.createCustomMarkerBitmap(
|
||||
title: paxTime,
|
||||
subtitle: paxDist,
|
||||
color: Colors.green.shade700,
|
||||
iconData: Icons.person_pin_circle,
|
||||
);
|
||||
|
||||
final BitmapDescriptor dropoffIcon =
|
||||
await MarkerGenerator.createCustomMarkerBitmap(
|
||||
title: destTime ?? totalTripDuration,
|
||||
subtitle: destDist ?? totalTripDistance,
|
||||
color: Colors.red.shade800,
|
||||
iconData: Icons.flag,
|
||||
);
|
||||
|
||||
markersMap[const MarkerId('pax')] = Marker(
|
||||
markerId: const MarkerId('pax'),
|
||||
position: LatLng(latPassenger, lngPassenger),
|
||||
icon: pickupIcon,
|
||||
anchor: const Offset(0.5, 0.85),
|
||||
);
|
||||
|
||||
markersMap[const MarkerId('dest')] = Marker(
|
||||
markerId: const MarkerId('dest'),
|
||||
position: LatLng(latDestination, lngDestination),
|
||||
icon: dropoffIcon,
|
||||
anchor: const Offset(0.5, 0.85),
|
||||
);
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
void _initialMapSetup() async {
|
||||
Position driverPos = await Geolocator.getCurrentPosition();
|
||||
LatLng driverLatLng = LatLng(driverPos.latitude, driverPos.longitude);
|
||||
|
||||
if (driverIcon != null) {
|
||||
markersMap[const MarkerId('driver')] = Marker(
|
||||
markerId: const MarkerId('driver'),
|
||||
position: driverLatLng,
|
||||
icon: driverIcon!,
|
||||
rotation: driverPos.heading,
|
||||
anchor: const Offset(0.5, 0.5),
|
||||
flat: true,
|
||||
zIndex: 10);
|
||||
}
|
||||
|
||||
if (latPassenger != 0 && lngPassenger != 0) {
|
||||
polylines.add(Polyline(
|
||||
polylineId: const PolylineId('temp_line'),
|
||||
points: [driverLatLng, LatLng(latPassenger, lngPassenger)],
|
||||
color: Colors.grey,
|
||||
width: 2,
|
||||
patterns: [PatternItem.dash(10), PatternItem.gap(10)],
|
||||
));
|
||||
|
||||
zoomToFitRide(driverLatLng);
|
||||
}
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
void updateDriverLocation(LatLng newPos, double heading) {
|
||||
if (driverIcon != null) {
|
||||
markersMap[const MarkerId('driver')] = Marker(
|
||||
markerId: const MarkerId('driver'),
|
||||
position: newPos,
|
||||
icon: driverIcon!,
|
||||
rotation: heading,
|
||||
anchor: const Offset(0.5, 0.5),
|
||||
flat: true,
|
||||
zIndex: 10,
|
||||
);
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
void onMapCreated(GoogleMapController controller) {
|
||||
mapController = controller;
|
||||
}
|
||||
|
||||
// --- قبول الطلب وإدارة التايمر ---
|
||||
void startTimer() {
|
||||
_timer?.cancel();
|
||||
remainingTime = duration;
|
||||
_playAudio();
|
||||
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
if (remainingTime <= 0) {
|
||||
timer.cancel();
|
||||
_stopAudio();
|
||||
if (!applied) Get.back();
|
||||
} else {
|
||||
remainingTime--;
|
||||
progress = remainingTime / duration;
|
||||
update();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void endTimer() => _timer?.cancel();
|
||||
void changeApplied() => applied = true;
|
||||
|
||||
void _playAudio() async {
|
||||
try {
|
||||
await audioPlayer.setAsset('assets/order.mp3', preload: true);
|
||||
await audioPlayer.setLoopMode(LoopMode.one);
|
||||
await audioPlayer.play();
|
||||
} catch (e) {
|
||||
print(e);
|
||||
}
|
||||
}
|
||||
|
||||
void _stopAudio() => audioPlayer.stop();
|
||||
|
||||
void _listenForRideTaken() {
|
||||
if (locationController.socket != null) {
|
||||
locationController.socket!.off('ride_taken');
|
||||
locationController.socket!.on('ride_taken', (data) {
|
||||
if (_isRideTakenHandled) return;
|
||||
String takenRideId = data['ride_id'].toString();
|
||||
String myCurrentRideId = _safeGet(16);
|
||||
String whoTookIt = data['taken_by_driver_id'].toString();
|
||||
String myDriverId = box.read(BoxName.driverID).toString();
|
||||
|
||||
if (takenRideId == myCurrentRideId && whoTookIt != myDriverId) {
|
||||
_isRideTakenHandled = true;
|
||||
endTimer();
|
||||
// 1. حذف الإشعار من شريط التنبيهات فوراً
|
||||
NotificationController().cancelOrderNotification();
|
||||
if (Get.isSnackbarOpen) Get.closeCurrentSnackbar();
|
||||
if (Get.isDialogOpen ?? false) Get.back();
|
||||
Get.back();
|
||||
Get.snackbar("تنبيه", "تم قبول الطلب من قبل سائق آخر",
|
||||
backgroundColor: Colors.orange, colorText: Colors.white);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Lifecycle
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
super.didChangeAppLifecycleState(state);
|
||||
if (state == AppLifecycleState.paused ||
|
||||
state == AppLifecycleState.detached) {
|
||||
isInBackground = true;
|
||||
} else if (state == AppLifecycleState.resumed) {
|
||||
isInBackground = false;
|
||||
FlutterOverlayWindow.closeOverlay();
|
||||
}
|
||||
}
|
||||
|
||||
void _checkOverlay() async {
|
||||
if (Platform.isAndroid && await FlutterOverlayWindow.isActive()) {
|
||||
await FlutterOverlayWindow.closeOverlay();
|
||||
}
|
||||
}
|
||||
|
||||
// Accept Order Logic
|
||||
Future<void> acceptOrder() async {
|
||||
endTimer();
|
||||
_stopAudio();
|
||||
|
||||
// 1. إرسال الطلب
|
||||
var res = await CRUD()
|
||||
.post(link: "${AppLink.ride}/rides/acceptRide.php", payload: {
|
||||
'id': _safeGet(16),
|
||||
'rideTimeStart': DateTime.now().toString(),
|
||||
'status': 'Apply',
|
||||
'passengerToken': _safeGet(9),
|
||||
'driver_id': box.read(BoxName.driverID),
|
||||
});
|
||||
|
||||
Log.print('res from orderrequestpage: ${res}');
|
||||
|
||||
// ============================================================
|
||||
// تصحيح: فحص الرد بدقة (Map أو String)
|
||||
// ============================================================
|
||||
bool isFailure = false;
|
||||
|
||||
if (res is Map && res['status'] == 'failure') {
|
||||
isFailure = true;
|
||||
} else if (res == 'failure') {
|
||||
isFailure = true;
|
||||
}
|
||||
|
||||
if (isFailure) {
|
||||
// ⛔ حالة الفشل: الطلب مأخوذ
|
||||
MyDialog().getDialog("عذراً، الطلب أخذه سائق آخر.", '', () {
|
||||
Get.back(); // إغلاق الديالوج
|
||||
Get.back(); // العودة للصفحة الرئيسية (إغلاق صفحة الطلب)
|
||||
});
|
||||
} else {
|
||||
// ✅ حالة النجاح
|
||||
|
||||
// حماية من الكراش: التأكد من وجود HomeCaptainController قبل استخدامه
|
||||
if (!Get.isRegistered<HomeCaptainController>()) {
|
||||
Get.put(HomeCaptainController());
|
||||
} else {
|
||||
Get.find<HomeCaptainController>().changeRideId();
|
||||
}
|
||||
|
||||
box.write(BoxName.statusDriverLocation, 'on');
|
||||
changeApplied();
|
||||
|
||||
var rideArgs = {
|
||||
'passengerLocation': '${_safeGet(0)},${_safeGet(1)}',
|
||||
'passengerDestination': '${_safeGet(3)},${_safeGet(4)}',
|
||||
'Duration': totalTripDuration,
|
||||
'totalCost': _safeGet(26),
|
||||
'Distance': totalTripDistance,
|
||||
'name': _safeGet(8),
|
||||
'phone': _safeGet(10),
|
||||
'email': _safeGet(28),
|
||||
'WalletChecked': _safeGet(13),
|
||||
'tokenPassenger': _safeGet(9),
|
||||
'direction':
|
||||
'https://www.google.com/maps/dir/${_safeGet(0)}/${_safeGet(1)}/',
|
||||
'DurationToPassenger': timeToPassenger,
|
||||
'rideId': _safeGet(16),
|
||||
'passengerId': _safeGet(7),
|
||||
'driverId': _safeGet(18),
|
||||
'durationOfRideValue': totalTripDuration,
|
||||
'paymentAmount': _safeGet(2),
|
||||
'paymentMethod': _safeGet(13) == 'true' ? 'visa' : 'cash',
|
||||
'isHaveSteps': _safeGet(20),
|
||||
'step0': _safeGet(21),
|
||||
'step1': _safeGet(22),
|
||||
'step2': _safeGet(23),
|
||||
'step3': _safeGet(24),
|
||||
'step4': _safeGet(25),
|
||||
'passengerWalletBurc': _safeGet(26),
|
||||
'timeOfOrder': DateTime.now().toString(),
|
||||
'totalPassenger': _safeGet(2),
|
||||
'carType': _safeGet(31),
|
||||
'kazan': _safeGet(32),
|
||||
'startNameLocation': _safeGet(29),
|
||||
'endNameLocation': _safeGet(30),
|
||||
};
|
||||
|
||||
box.write(BoxName.rideArguments, rideArgs);
|
||||
|
||||
// الانتقال النهائي
|
||||
Get.off(() => PassengerLocationMapPage(), arguments: rideArgs);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
locationController.socket?.off('ride_taken');
|
||||
audioPlayer.dispose();
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_timer?.cancel();
|
||||
mapController?.dispose();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class MyMenuController extends GetxController {
|
||||
bool isDrawerOpen = true;
|
||||
|
||||
void getDrawerMenu() {
|
||||
if (isDrawerOpen == true) {
|
||||
isDrawerOpen = false;
|
||||
} else {
|
||||
isDrawerOpen = true;
|
||||
}
|
||||
update();
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
|
||||
// تم تعديل الدالة لتقبل وسيط من نوع `dynamic` لحل مشكلة عدم تطابق الأنواع مع دالة `compute`.
|
||||
// هذه الدالة لا تزال تعمل كدالة من المستوى الأعلى (Top-level function)
|
||||
// وهو شرط أساسي لاستخدامها مع دالة compute.
|
||||
List<LatLng> decodePolylineIsolate(dynamic encodedMessage) {
|
||||
// التأكد من أن الرسالة المستقبلة هي من نوع String
|
||||
if (encodedMessage is! String) {
|
||||
// إرجاع قائمة فارغة أو إظهار خطأ إذا كان النوع غير صحيح
|
||||
return [];
|
||||
}
|
||||
final String encoded = encodedMessage;
|
||||
|
||||
List<LatLng> points = [];
|
||||
int index = 0, len = encoded.length;
|
||||
int lat = 0, lng = 0;
|
||||
|
||||
while (index < len) {
|
||||
int b, shift = 0, result = 0;
|
||||
do {
|
||||
b = encoded.codeUnitAt(index++) - 63;
|
||||
result |= (b & 0x1f) << shift;
|
||||
shift += 5;
|
||||
} while (b >= 0x20);
|
||||
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
|
||||
lat += dlat;
|
||||
|
||||
shift = 0;
|
||||
result = 0;
|
||||
do {
|
||||
b = encoded.codeUnitAt(index++) - 63;
|
||||
result |= (b & 0x1f) << shift;
|
||||
shift += 5;
|
||||
} while (b >= 0x20);
|
||||
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
|
||||
lng += dlng;
|
||||
|
||||
points.add(LatLng(lat / 1E5, lng / 1E5));
|
||||
}
|
||||
return points;
|
||||
}
|
||||
@@ -1,705 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:sefer_driver/constant/colors.dart';
|
||||
import 'package:sefer_driver/controller/functions/crud.dart';
|
||||
|
||||
import '../../../constant/box_name.dart';
|
||||
import '../../../constant/country_polygons.dart';
|
||||
import '../../../constant/links.dart';
|
||||
import '../../../env/env.dart';
|
||||
import '../../../main.dart';
|
||||
import '../../../print.dart';
|
||||
import '../../functions/tts.dart';
|
||||
import 'decode_polyline_isolate.dart';
|
||||
|
||||
class NavigationController extends GetxController {
|
||||
// --- متغيرات الحالة العامة ---
|
||||
bool isLoading = false;
|
||||
GoogleMapController? mapController;
|
||||
final TextEditingController placeDestinationController =
|
||||
TextEditingController();
|
||||
|
||||
// --- متغيرات الخريطة والموقع ---
|
||||
LatLng? myLocation;
|
||||
double heading = 0.0;
|
||||
final Set<Marker> markers = {};
|
||||
final Set<Polyline> polylines = {};
|
||||
|
||||
BitmapDescriptor carIcon = BitmapDescriptor.defaultMarker;
|
||||
BitmapDescriptor destinationIcon = BitmapDescriptor.defaultMarker;
|
||||
|
||||
// --- متغيرات النظام الذكي للتحديث ---
|
||||
Timer? _locationUpdateTimer;
|
||||
// تحديث كل ثانية لضمان سلاسة الحركة
|
||||
Duration _currentUpdateInterval = const Duration(seconds: 1);
|
||||
LatLng? _lastRecordedLocation;
|
||||
|
||||
// --- متغيرات البحث ---
|
||||
List<dynamic> placesDestination = [];
|
||||
Timer? _debounce;
|
||||
|
||||
// --- متغيرات الملاحة (Navigation) ---
|
||||
LatLng? _finalDestination;
|
||||
List<Map<String, dynamic>> routeSteps = [];
|
||||
|
||||
List<LatLng> _fullRouteCoordinates = [];
|
||||
int _lastTraveledIndexInFullRoute = 0;
|
||||
|
||||
bool _nextInstructionSpoken = false;
|
||||
String currentInstruction = "";
|
||||
String nextInstruction = "";
|
||||
int currentStepIndex = 0;
|
||||
|
||||
double currentSpeed = 0.0;
|
||||
String distanceToNextStep = "";
|
||||
|
||||
// الرابط الجديد
|
||||
static const String _routeApiBaseUrl =
|
||||
"https://routesy.intaleq.xyz/route/v1/driving";
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
_initialize();
|
||||
}
|
||||
|
||||
Future<void> _initialize() async {
|
||||
await _loadCustomIcons();
|
||||
await _getCurrentLocationAndStartUpdates();
|
||||
if (!Get.isRegistered<TextToSpeechController>()) {
|
||||
Get.put(TextToSpeechController());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_locationUpdateTimer?.cancel();
|
||||
mapController?.dispose();
|
||||
_debounce?.cancel();
|
||||
placeDestinationController.dispose();
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// ✅ دوال الخريطة الأساسية
|
||||
// =======================================================================
|
||||
|
||||
void onMapCreated(GoogleMapController controller) {
|
||||
mapController = controller;
|
||||
if (myLocation != null) {
|
||||
animateCameraToPosition(myLocation!);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> onMapLongPressed(LatLng tappedPoint) async {
|
||||
Get.dialog(
|
||||
AlertDialog(
|
||||
title: const Text('بدء الملاحة؟'),
|
||||
content: const Text('هل تريد الذهاب إلى هذا الموقع المحدد؟'),
|
||||
actionsAlignment: MainAxisAlignment.spaceBetween,
|
||||
actions: [
|
||||
TextButton(
|
||||
child: const Text('إلغاء', style: TextStyle(color: Colors.grey)),
|
||||
onPressed: () => Get.back(),
|
||||
),
|
||||
TextButton(
|
||||
child: const Text('اذهب الآن'),
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
startNavigationTo(tappedPoint, infoWindowTitle: 'الموقع المحدد');
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// ١. النظام الذكي للموقع (Optimized)
|
||||
// =======================================================================
|
||||
|
||||
Future<void> _getCurrentLocationAndStartUpdates() async {
|
||||
try {
|
||||
Position position = await Geolocator.getCurrentPosition(
|
||||
desiredAccuracy: LocationAccuracy.high);
|
||||
myLocation = LatLng(position.latitude, position.longitude);
|
||||
getLocationArea(myLocation!.latitude, myLocation!.longitude);
|
||||
update();
|
||||
animateCameraToPosition(myLocation!);
|
||||
_startLocationTimer();
|
||||
} catch (e) {
|
||||
Log.print("Error getting initial location: $e");
|
||||
}
|
||||
}
|
||||
|
||||
void _startLocationTimer() {
|
||||
_locationUpdateTimer?.cancel();
|
||||
_locationUpdateTimer = Timer.periodic(_currentUpdateInterval, (timer) {
|
||||
_updateLocationAndProcess();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _updateLocationAndProcess() async {
|
||||
try {
|
||||
final position = await Geolocator.getCurrentPosition(
|
||||
desiredAccuracy: LocationAccuracy.high);
|
||||
|
||||
final newLoc = LatLng(position.latitude, position.longitude);
|
||||
|
||||
// فلتر الاهتزاز (Jitter Filter)
|
||||
if (_lastRecordedLocation != null) {
|
||||
double dist = Geolocator.distanceBetween(
|
||||
newLoc.latitude,
|
||||
newLoc.longitude,
|
||||
_lastRecordedLocation!.latitude,
|
||||
_lastRecordedLocation!.longitude);
|
||||
if (dist < 2.0) return; // تجاهل الحركة الأقل من 2 متر
|
||||
}
|
||||
|
||||
myLocation = newLoc;
|
||||
_lastRecordedLocation = newLoc;
|
||||
heading = position.heading;
|
||||
currentSpeed = position.speed * 3.6;
|
||||
|
||||
_updateCarMarker();
|
||||
|
||||
if (polylines.isNotEmpty && _fullRouteCoordinates.isNotEmpty) {
|
||||
animateCameraToPosition(
|
||||
myLocation!,
|
||||
bearing: heading,
|
||||
zoom: 18.0,
|
||||
);
|
||||
|
||||
_updateTraveledPolylineSmart(myLocation!);
|
||||
_checkNavigationStep(myLocation!);
|
||||
}
|
||||
|
||||
update();
|
||||
} catch (e) {
|
||||
// Log.print("Loc update error: $e");
|
||||
}
|
||||
}
|
||||
|
||||
void _updateCarMarker() {
|
||||
if (myLocation == null) return;
|
||||
markers.removeWhere((m) => m.markerId.value == 'myLocation');
|
||||
markers.add(
|
||||
Marker(
|
||||
markerId: const MarkerId('myLocation'),
|
||||
position: myLocation!,
|
||||
icon: carIcon,
|
||||
rotation: heading,
|
||||
anchor: const Offset(0.5, 0.5),
|
||||
flat: true,
|
||||
zIndex: 2,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void animateCameraToPosition(LatLng position,
|
||||
{double zoom = 17.0, double bearing = 0.0}) {
|
||||
mapController?.animateCamera(
|
||||
CameraUpdate.newCameraPosition(
|
||||
CameraPosition(
|
||||
target: position, zoom: zoom, bearing: bearing, tilt: 45.0),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// ٢. خوارزمية رسم المسار الذكية (Sliding Window) - مخففة للجهاز
|
||||
// =======================================================================
|
||||
|
||||
void _updateTraveledPolylineSmart(LatLng currentPos) {
|
||||
if (_fullRouteCoordinates.isEmpty) return;
|
||||
|
||||
// نبحث فقط في الـ 60 نقطة القادمة لتخفيف الحمل على المعالج
|
||||
int searchWindow = 60;
|
||||
int startIndex = _lastTraveledIndexInFullRoute;
|
||||
int endIndex = min(startIndex + searchWindow, _fullRouteCoordinates.length);
|
||||
|
||||
double minDistance = double.infinity;
|
||||
int closestIndex = startIndex;
|
||||
bool foundCloser = false;
|
||||
|
||||
for (int i = startIndex; i < endIndex; i++) {
|
||||
final point = _fullRouteCoordinates[i];
|
||||
final dist = Geolocator.distanceBetween(currentPos.latitude,
|
||||
currentPos.longitude, point.latitude, point.longitude);
|
||||
|
||||
if (dist < minDistance) {
|
||||
minDistance = dist;
|
||||
closestIndex = i;
|
||||
foundCloser = true;
|
||||
}
|
||||
}
|
||||
|
||||
// شرط التحديث: وجدنا نقطة أقرب، وهي أمامنا (وليست خلفنا)، والمسافة منطقية
|
||||
if (foundCloser &&
|
||||
minDistance < 50 &&
|
||||
closestIndex > _lastTraveledIndexInFullRoute) {
|
||||
_lastTraveledIndexInFullRoute = closestIndex;
|
||||
|
||||
// استخدام sublist وهو سريع جداً في Dart
|
||||
final remaining =
|
||||
_fullRouteCoordinates.sublist(_lastTraveledIndexInFullRoute);
|
||||
final traveled =
|
||||
_fullRouteCoordinates.sublist(0, _lastTraveledIndexInFullRoute + 1);
|
||||
|
||||
_updatePolylinesSets(traveled, remaining);
|
||||
}
|
||||
}
|
||||
|
||||
void _updatePolylinesSets(List<LatLng> traveled, List<LatLng> remaining) {
|
||||
// إزالة الخطوط القديمة وإضافة الجديدة بدلاً من تحديث الكل
|
||||
polylines.removeWhere((p) => p.polylineId.value == 'remaining_route');
|
||||
polylines.removeWhere((p) => p.polylineId.value == 'traveled_route');
|
||||
|
||||
// المسار المتبقي (أزرق واضح)
|
||||
polylines.add(Polyline(
|
||||
polylineId: const PolylineId('remaining_route'),
|
||||
points: remaining,
|
||||
color: const Color(0xFF0D47A1),
|
||||
width: 6,
|
||||
startCap: Cap.roundCap,
|
||||
endCap: Cap.roundCap,
|
||||
jointType: JointType.round,
|
||||
));
|
||||
|
||||
// المسار المقطوع (رمادي)
|
||||
polylines.add(Polyline(
|
||||
polylineId: const PolylineId('traveled_route'),
|
||||
points: traveled,
|
||||
color: Colors.grey.shade400,
|
||||
width: 6,
|
||||
jointType: JointType.round,
|
||||
));
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// ٣. التحكم في التوجيهات
|
||||
// =======================================================================
|
||||
|
||||
void _checkNavigationStep(LatLng currentPosition) {
|
||||
if (routeSteps.isEmpty || currentStepIndex >= routeSteps.length) return;
|
||||
|
||||
final step = routeSteps[currentStepIndex];
|
||||
// في OSRM، يجب التأكد من وجود maneuver location
|
||||
final maneuver = step['maneuver'];
|
||||
final List<dynamic> location = maneuver['location']; // [lng, lat]
|
||||
final endLatLng = LatLng(location[1], location[0]);
|
||||
|
||||
final distance = Geolocator.distanceBetween(
|
||||
currentPosition.latitude,
|
||||
currentPosition.longitude,
|
||||
endLatLng.latitude,
|
||||
endLatLng.longitude,
|
||||
);
|
||||
|
||||
distanceToNextStep = distance > 1000
|
||||
? "${(distance / 1000).toStringAsFixed(1)} كم"
|
||||
: "${distance.toStringAsFixed(0)} متر";
|
||||
|
||||
// نطق التعليمات قبل 50 متر
|
||||
if (distance < 50 &&
|
||||
!_nextInstructionSpoken &&
|
||||
nextInstruction.isNotEmpty) {
|
||||
Get.find<TextToSpeechController>().speakText(nextInstruction);
|
||||
_nextInstructionSpoken = true;
|
||||
}
|
||||
|
||||
// الانتقال للخطوة التالية عند الاقتراب (20 متر)
|
||||
if (distance < 20) {
|
||||
_advanceStep();
|
||||
}
|
||||
}
|
||||
|
||||
void _advanceStep() {
|
||||
currentStepIndex++;
|
||||
if (currentStepIndex < routeSteps.length) {
|
||||
currentInstruction = routeSteps[currentStepIndex]['instruction_text'];
|
||||
|
||||
// تجهيز التعليمات القادمة
|
||||
if ((currentStepIndex + 1) < routeSteps.length) {
|
||||
nextInstruction =
|
||||
"ثم ${routeSteps[currentStepIndex + 1]['instruction_text']}";
|
||||
} else {
|
||||
nextInstruction = "ستصل إلى وجهتك";
|
||||
}
|
||||
|
||||
_nextInstructionSpoken = false;
|
||||
update();
|
||||
} else {
|
||||
_finishNavigation();
|
||||
}
|
||||
}
|
||||
|
||||
void _finishNavigation() {
|
||||
currentInstruction = "لقد وصلت إلى وجهتك";
|
||||
nextInstruction = "";
|
||||
distanceToNextStep = "";
|
||||
Get.find<TextToSpeechController>().speakText(currentInstruction);
|
||||
update();
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// ٤. جلب المسار (🔥 تم التحديث للرابط الجديد 🔥)
|
||||
// =======================================================================
|
||||
|
||||
Future<void> getRoute(LatLng origin, LatLng destination) async {
|
||||
// 🔥 بناء الرابط حسب التنسيق: /driving/lng,lat;lng,lat
|
||||
String coords =
|
||||
"${origin.longitude},${origin.latitude};${destination.longitude},${destination.latitude}";
|
||||
|
||||
// 🔥 تفعيل steps=true لجلب الخطوات
|
||||
String url =
|
||||
"$_routeApiBaseUrl/$coords?steps=true&overview=full&geometries=polyline";
|
||||
|
||||
try {
|
||||
// الرابط الجديد قد لا يحتاج API Key في الهيدر، ولكن نتركه إذا كان السيرفر يطلبه
|
||||
// إذا كان الرابط عام، يمكن إزالة الهيدر
|
||||
final response = await http.get(Uri.parse(url));
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
Get.snackbar('تنبيه', 'تعذر الاتصال بخدمة التوجيه.');
|
||||
return;
|
||||
}
|
||||
|
||||
final responseData = jsonDecode(response.body);
|
||||
|
||||
// التحقق حسب هيكلية OSRM
|
||||
if (responseData['code'] != 'Ok' ||
|
||||
(responseData['routes'] as List).isEmpty) {
|
||||
Get.snackbar('عذراً', 'لم يتم العثور على مسار.');
|
||||
return;
|
||||
}
|
||||
|
||||
var route = responseData['routes'][0];
|
||||
|
||||
// 1. فك تشفير Polyline
|
||||
final pointsString = route['geometry'];
|
||||
_fullRouteCoordinates = await compute(
|
||||
decodePolylineIsolate as ComputeCallback<dynamic, List<LatLng>>,
|
||||
pointsString);
|
||||
|
||||
// تهيئة الرسم
|
||||
_lastTraveledIndexInFullRoute = 0;
|
||||
_updatePolylinesSets([], _fullRouteCoordinates);
|
||||
|
||||
// 2. استخراج الخطوات (داخل Legs في OSRM)
|
||||
var legs = route['legs'] as List;
|
||||
if (legs.isNotEmpty) {
|
||||
var steps = legs[0]['steps'] as List;
|
||||
routeSteps = List<Map<String, dynamic>>.from(steps);
|
||||
} else {
|
||||
routeSteps = [];
|
||||
}
|
||||
|
||||
// 3. معالجة النصوص العربية للخطوات
|
||||
for (var step in routeSteps) {
|
||||
step['instruction_text'] = _createInstructionFromManeuver(step);
|
||||
}
|
||||
|
||||
// 4. بدء الملاحة
|
||||
currentStepIndex = 0;
|
||||
_nextInstructionSpoken = false;
|
||||
if (routeSteps.isNotEmpty) {
|
||||
currentInstruction = routeSteps[0]['instruction_text'];
|
||||
if (routeSteps.length > 1) {
|
||||
nextInstruction = "ثم ${routeSteps[1]['instruction_text']}";
|
||||
} else {
|
||||
nextInstruction = "الوجهة النهائية";
|
||||
}
|
||||
Get.find<TextToSpeechController>().speakText(currentInstruction);
|
||||
}
|
||||
|
||||
// 5. ضبط الكاميرا
|
||||
if (_fullRouteCoordinates.isNotEmpty) {
|
||||
final bounds = _boundsFromLatLngList(_fullRouteCoordinates);
|
||||
mapController
|
||||
?.animateCamera(CameraUpdate.newLatLngBounds(bounds, 80.0));
|
||||
}
|
||||
|
||||
update();
|
||||
} catch (e) {
|
||||
Log.print("GetRoute Error: $e");
|
||||
Get.snackbar('خطأ', 'حدث خطأ غير متوقع.');
|
||||
}
|
||||
}
|
||||
|
||||
// 🔥 تحويل تعليمات OSRM إلى العربية
|
||||
String _createInstructionFromManeuver(Map<String, dynamic> step) {
|
||||
if (step['maneuver'] == null) return "تابع المسير";
|
||||
|
||||
final maneuver = step['maneuver'];
|
||||
final type = maneuver['type'] ?? 'continue';
|
||||
final modifier = maneuver['modifier'] ?? 'straight';
|
||||
final name = step['name'] ?? ''; // اسم الشارع
|
||||
|
||||
String instruction = "";
|
||||
|
||||
switch (type) {
|
||||
case 'depart':
|
||||
instruction = "انطلق";
|
||||
break;
|
||||
case 'arrive':
|
||||
return "لقد وصلت إلى وجهتك، $name";
|
||||
case 'turn':
|
||||
case 'fork':
|
||||
case 'roundabout':
|
||||
case 'merge':
|
||||
case 'on ramp':
|
||||
case 'off ramp':
|
||||
case 'end of road':
|
||||
instruction = _getTurnInstruction(modifier);
|
||||
break;
|
||||
case 'new name':
|
||||
instruction = "تابع المسير";
|
||||
break;
|
||||
default:
|
||||
instruction = "تابع المسير";
|
||||
}
|
||||
|
||||
if (name.isNotEmpty) {
|
||||
if (type == 'new name' || type == 'continue') {
|
||||
instruction += " على $name";
|
||||
} else {
|
||||
instruction += " نحو $name";
|
||||
}
|
||||
}
|
||||
return instruction;
|
||||
}
|
||||
|
||||
String _getTurnInstruction(String modifier) {
|
||||
switch (modifier) {
|
||||
case 'uturn':
|
||||
return "قم بالاستدارة والعودة";
|
||||
case 'sharp right':
|
||||
return "انعطف يميناً بحدة";
|
||||
case 'right':
|
||||
return "انعطف يميناً";
|
||||
case 'slight right':
|
||||
return "انعطف يميناً قليلاً";
|
||||
case 'straight':
|
||||
return "استمر للأمام";
|
||||
case 'slight left':
|
||||
return "انعطف يساراً قليلاً";
|
||||
case 'left':
|
||||
return "انعطف يساراً";
|
||||
case 'sharp left':
|
||||
return "انعطف يساراً بحدة";
|
||||
default:
|
||||
return "اتجه";
|
||||
}
|
||||
}
|
||||
|
||||
// =======================================================================
|
||||
// ٥. أدوات مساعدة
|
||||
// =======================================================================
|
||||
|
||||
Future<void> startNavigationTo(LatLng destination,
|
||||
{String infoWindowTitle = ''}) async {
|
||||
isLoading = true;
|
||||
update();
|
||||
try {
|
||||
_finalDestination = destination;
|
||||
clearRoute(isNewRoute: true);
|
||||
|
||||
markers.add(Marker(
|
||||
markerId: const MarkerId('destination'),
|
||||
position: destination,
|
||||
icon: destinationIcon,
|
||||
infoWindow: InfoWindow(title: infoWindowTitle),
|
||||
));
|
||||
|
||||
await getRoute(myLocation!, destination);
|
||||
} finally {
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> recalculateRoute() async {
|
||||
if (myLocation == null || _finalDestination == null || isLoading) return;
|
||||
isLoading = true;
|
||||
update();
|
||||
Get.snackbar('إعادة التوجيه', 'جاري حساب مسار جديد...',
|
||||
backgroundColor: AppColor.goldenBronze);
|
||||
await getRoute(myLocation!, _finalDestination!);
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
void clearRoute({bool isNewRoute = false}) {
|
||||
if (!isNewRoute) {
|
||||
markers.removeWhere((m) => m.markerId.value == 'destination');
|
||||
_finalDestination = null;
|
||||
polylines.clear();
|
||||
}
|
||||
routeSteps.clear();
|
||||
_fullRouteCoordinates.clear();
|
||||
_lastTraveledIndexInFullRoute = 0;
|
||||
currentInstruction = "";
|
||||
nextInstruction = "";
|
||||
distanceToNextStep = "";
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> _loadCustomIcons() async {
|
||||
carIcon = await BitmapDescriptor.fromAssetImage(
|
||||
const ImageConfiguration(size: Size(40, 40)), 'assets/images/car.png');
|
||||
destinationIcon = await BitmapDescriptor.fromAssetImage(
|
||||
const ImageConfiguration(size: Size(30, 30)), 'assets/images/b.png');
|
||||
}
|
||||
|
||||
Future<void> getPlaces() async {
|
||||
final q = placeDestinationController.text.trim();
|
||||
if (q.length < 3) {
|
||||
placesDestination = [];
|
||||
update();
|
||||
return;
|
||||
}
|
||||
|
||||
if (myLocation == null) return;
|
||||
|
||||
final lat = myLocation!.latitude;
|
||||
final lng = myLocation!.longitude;
|
||||
const radiusKm = 200.0;
|
||||
final latDelta = _kmToLatDelta(radiusKm);
|
||||
final lngDelta = _kmToLngDelta(radiusKm, lat);
|
||||
|
||||
final payload = {
|
||||
'query': q,
|
||||
'lat_min': (lat - latDelta).toString(),
|
||||
'lat_max': (lat + latDelta).toString(),
|
||||
'lng_min': (lng - lngDelta).toString(),
|
||||
'lng_max': (lng + lngDelta).toString(),
|
||||
};
|
||||
|
||||
try {
|
||||
final response =
|
||||
await CRUD().post(link: AppLink.getPlacesSyria, payload: payload);
|
||||
final responseData = (response);
|
||||
|
||||
List list;
|
||||
if (responseData is Map && responseData['status'] == 'success') {
|
||||
list = List.from(responseData['message'] as List);
|
||||
} else if (responseData is List) {
|
||||
list = List.from(responseData);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
for (final p in list) {
|
||||
final plat = double.tryParse(p['latitude']?.toString() ?? '0.0') ?? 0.0;
|
||||
final plng =
|
||||
double.tryParse(p['longitude']?.toString() ?? '0.0') ?? 0.0;
|
||||
final distance = _haversineKm(lat, lng, plat, plng);
|
||||
p['distanceKm'] = distance;
|
||||
}
|
||||
|
||||
list.sort((a, b) =>
|
||||
(a['distanceKm'] as double).compareTo(b['distanceKm'] as double));
|
||||
placesDestination = list;
|
||||
update();
|
||||
} catch (e) {
|
||||
print('Exception in getPlaces: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> selectDestination(dynamic place) async {
|
||||
placeDestinationController.clear();
|
||||
placesDestination = [];
|
||||
final double lat = double.parse(place['latitude'].toString());
|
||||
final double lng = double.parse(place['longitude'].toString());
|
||||
await startNavigationTo(LatLng(lat, lng),
|
||||
infoWindowTitle: place['name'] ?? 'وجهة');
|
||||
}
|
||||
|
||||
void onSearchChanged(String query) {
|
||||
if (_debounce?.isActive ?? false) _debounce!.cancel();
|
||||
_debounce = Timer(const Duration(milliseconds: 700), () => getPlaces());
|
||||
}
|
||||
|
||||
// --- دوال مساعدة للحسابات ---
|
||||
double _haversineKm(double lat1, double lon1, double lat2, double lon2) {
|
||||
const R = 6371.0;
|
||||
final dLat = (lat2 - lat1) * (pi / 180.0);
|
||||
final dLon = (lon2 - lon1) * (pi / 180.0);
|
||||
final a = sin(dLat / 2) * sin(dLat / 2) +
|
||||
cos(lat1 * pi / 180) *
|
||||
cos(lat2 * pi / 180) *
|
||||
sin(dLon / 2) *
|
||||
sin(dLon / 2);
|
||||
return R * 2 * atan2(sqrt(a), sqrt(1 - a));
|
||||
}
|
||||
|
||||
double _kmToLatDelta(double km) => km / 111.32;
|
||||
double _kmToLngDelta(double km, double lat) =>
|
||||
km / (111.32 * cos(lat * pi / 180));
|
||||
|
||||
LatLngBounds _boundsFromLatLngList(List<LatLng> list) {
|
||||
double? x0, x1, y0, y1;
|
||||
for (LatLng latLng in list) {
|
||||
if (x0 == null) {
|
||||
x0 = x1 = latLng.latitude;
|
||||
y0 = y1 = latLng.longitude;
|
||||
} else {
|
||||
if (latLng.latitude > x1!) x1 = latLng.latitude;
|
||||
if (latLng.latitude < x0) x0 = latLng.latitude;
|
||||
if (latLng.longitude > y1!) y1 = latLng.longitude;
|
||||
if (latLng.longitude < y0!) y0 = latLng.longitude;
|
||||
}
|
||||
}
|
||||
return LatLngBounds(
|
||||
northeast: LatLng(x1!, y1!), southwest: LatLng(x0!, y0!));
|
||||
}
|
||||
|
||||
// --- دوال التحقق من الدولة ---
|
||||
String getLocationArea(double latitude, double longitude) {
|
||||
LatLng p = LatLng(latitude, longitude);
|
||||
if (isPointInPolygon(p, CountryPolygons.jordanBoundary)) {
|
||||
box.write(BoxName.countryCode, 'Jordan');
|
||||
return 'Jordan';
|
||||
}
|
||||
if (isPointInPolygon(p, CountryPolygons.syriaBoundary)) {
|
||||
box.write(BoxName.countryCode, 'Syria');
|
||||
return 'Syria';
|
||||
}
|
||||
if (isPointInPolygon(p, CountryPolygons.egyptBoundary)) {
|
||||
box.write(BoxName.countryCode, 'Egypt');
|
||||
return 'Egypt';
|
||||
}
|
||||
return 'Unknown';
|
||||
}
|
||||
|
||||
bool isPointInPolygon(LatLng point, List<LatLng> polygon) {
|
||||
int intersections = 0;
|
||||
for (int i = 0; i < polygon.length; i++) {
|
||||
LatLng vertex1 = polygon[i];
|
||||
LatLng vertex2 = polygon[(i + 1) % polygon.length];
|
||||
if (_rayIntersectsSegment(point, vertex1, vertex2)) intersections++;
|
||||
}
|
||||
return intersections % 2 != 0;
|
||||
}
|
||||
|
||||
bool _rayIntersectsSegment(LatLng point, LatLng vertex1, LatLng vertex2) {
|
||||
double px = point.longitude;
|
||||
double py = point.latitude;
|
||||
double v1x = vertex1.longitude;
|
||||
double v1y = vertex1.latitude;
|
||||
double v2x = vertex2.longitude;
|
||||
double v2y = vertex2.latitude;
|
||||
|
||||
if ((py < v1y && py < v2y) || (py > v1y && py > v2y)) return false;
|
||||
double intersectX = v1x + (py - v1y) * (v2x - v1x) / (v2y - v1y);
|
||||
return intersectX > px;
|
||||
}
|
||||
}
|
||||
@@ -1,425 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'dart:ui'; // For BackdropFilter
|
||||
|
||||
import 'navigation_controller.dart';
|
||||
|
||||
// ملاحظة: افترضتُ أن لديك لوناً أساسياً في هذا الملف
|
||||
// import 'package:sefer_driver/constant/colors.dart';
|
||||
// سأستخدم اللون الأزرق كبديل مؤقت
|
||||
const Color kPrimaryColor = Color(0xFF0D47A1);
|
||||
|
||||
class NavigationView extends StatelessWidget {
|
||||
const NavigationView({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// استخدام Get.find() بدلاً من Get.put() لضمان أن الكونترولر مُهيأ مسبقاً
|
||||
// إذا كانت هذه هي نقطة الدخول، Get.put() صحيح.
|
||||
final NavigationController controller = Get.put(NavigationController());
|
||||
|
||||
return Scaffold(
|
||||
body: GetBuilder<NavigationController>(
|
||||
builder: (_) => Stack(
|
||||
children: [
|
||||
// --- الخريطة ---
|
||||
GoogleMap(
|
||||
onMapCreated: controller.onMapCreated,
|
||||
onLongPress: controller.onMapLongPressed,
|
||||
initialCameraPosition: CameraPosition(
|
||||
target: controller.myLocation ??
|
||||
const LatLng(33.5138, 36.2765), // Default to Damascus
|
||||
zoom: 16.0,
|
||||
),
|
||||
markers: controller.markers,
|
||||
polylines: controller.polylines,
|
||||
myLocationEnabled: false,
|
||||
myLocationButtonEnabled: false,
|
||||
compassEnabled: false,
|
||||
zoomControlsEnabled: false, buildingsEnabled: false,
|
||||
// تعديل الـ padding لإعطاء مساحة للعناصر العلوية والسفلية
|
||||
// مساحة أكبر في الأعلى للبحث + النتائج، ومساحة أكبر بالأسفل للملاحة
|
||||
padding: EdgeInsets.only(
|
||||
bottom: controller.currentInstruction.isNotEmpty ? 170 : 0,
|
||||
top: 150,
|
||||
),
|
||||
),
|
||||
|
||||
// --- واجهة البحث (تصميم زجاجي) ---
|
||||
_buildGlassSearchUI(controller),
|
||||
|
||||
// --- إرشادات الملاحة (تصميم عائم) ---
|
||||
if (controller.currentInstruction.isNotEmpty)
|
||||
_buildFloatingNavigationUI(controller),
|
||||
|
||||
// --- أزرار التحكم (تصميم عائم) ---
|
||||
_buildFloatingMapControls(controller),
|
||||
|
||||
// --- مؤشر التحميل ---
|
||||
if (controller.isLoading)
|
||||
Container(
|
||||
color: Colors.black.withOpacity(0.5),
|
||||
child: const Center(
|
||||
child: CircularProgressIndicator(
|
||||
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
|
||||
strokeWidth: 3,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// --- 1. واجهة البحث بالتصميم الزجاجي المطور ---
|
||||
Widget _buildGlassSearchUI(NavigationController controller) {
|
||||
return Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
|
||||
child: Column(
|
||||
children: [
|
||||
// --- شريط البحث ---
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(28.0),
|
||||
child: BackdropFilter(
|
||||
filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
|
||||
child: Container(
|
||||
height: 56,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.85),
|
||||
borderRadius: BorderRadius.circular(28.0),
|
||||
border: Border.all(color: Colors.white.withOpacity(0.4)),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.05),
|
||||
blurRadius: 15,
|
||||
offset: const Offset(0, 5),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(left: 18.0, right: 10.0),
|
||||
child: Icon(Icons.search,
|
||||
color: kPrimaryColor, size: 24),
|
||||
),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: controller.placeDestinationController,
|
||||
onChanged: controller.onSearchChanged,
|
||||
textInputAction: TextInputAction.search,
|
||||
style: const TextStyle(
|
||||
fontSize: 16, color: Colors.black87),
|
||||
decoration: InputDecoration(
|
||||
hintText: 'إلى أين تريد الذهاب؟',
|
||||
hintStyle: const TextStyle(
|
||||
color: Colors.black45, fontSize: 16),
|
||||
border: InputBorder.none,
|
||||
contentPadding: const EdgeInsets.only(bottom: 2),
|
||||
),
|
||||
),
|
||||
),
|
||||
// زر المسح أو إلغاء المسار
|
||||
if (controller
|
||||
.placeDestinationController.text.isNotEmpty)
|
||||
_buildClearButton(controller)
|
||||
else if (controller.polylines.isNotEmpty)
|
||||
_buildCancelRouteButton(controller),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
|
||||
// --- قائمة النتائج ---
|
||||
if (controller.placesDestination.isNotEmpty)
|
||||
_buildSearchResultsList(controller),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildClearButton(NavigationController controller) {
|
||||
return IconButton(
|
||||
icon: const Icon(Icons.clear, color: Colors.grey, size: 22),
|
||||
onPressed: () {
|
||||
controller.placeDestinationController.clear();
|
||||
controller.placesDestination = [];
|
||||
controller.update();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCancelRouteButton(NavigationController controller) {
|
||||
return IconButton(
|
||||
tooltip: 'إلغاء المسار',
|
||||
icon: const Icon(Icons.close, color: Colors.redAccent, size: 22),
|
||||
onPressed: () => controller.clearRoute(),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSearchResultsList(NavigationController controller) {
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(24.0),
|
||||
child: BackdropFilter(
|
||||
filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
|
||||
child: Container(
|
||||
constraints: const BoxConstraints(maxHeight: 220),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.85),
|
||||
borderRadius: BorderRadius.circular(24.0),
|
||||
border: Border.all(color: Colors.white.withOpacity(0.4)),
|
||||
),
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0),
|
||||
itemCount: controller.placesDestination.length,
|
||||
itemBuilder: (context, index) {
|
||||
final place = controller.placesDestination[index];
|
||||
final distance = place['distanceKm'] as double?;
|
||||
final address = (place['address'] ?? '').toString();
|
||||
|
||||
return Material(
|
||||
color: Colors.transparent,
|
||||
child: InkWell(
|
||||
onTap: () => controller.selectDestination(place),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0, vertical: 12.0),
|
||||
child: Row(
|
||||
children: [
|
||||
// أيقونة الموقع
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: kPrimaryColor.withOpacity(0.1),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: const Icon(Icons.location_on_outlined,
|
||||
color: kPrimaryColor, size: 20),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
// الاسم والعنوان
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
place['name'] ?? 'اسم غير معروف',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 16,
|
||||
color: Colors.black87),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
if (address.isNotEmpty)
|
||||
Text(
|
||||
address,
|
||||
style: const TextStyle(
|
||||
color: Colors.black54, fontSize: 13),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
// المسافة
|
||||
if (distance != null)
|
||||
Text(
|
||||
'${distance.toStringAsFixed(1)} كم',
|
||||
style: const TextStyle(
|
||||
color: kPrimaryColor,
|
||||
fontWeight: FontWeight.w500,
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// --- 2. أزرار التحكم بالتصميم العائم ---
|
||||
Widget _buildFloatingMapControls(NavigationController controller) {
|
||||
return Positioned(
|
||||
// اجعلها تطفو فوق لوحة الملاحة
|
||||
bottom: controller.currentInstruction.isNotEmpty ? 190 : 24,
|
||||
right: 16,
|
||||
child: Column(
|
||||
children: [
|
||||
if (controller.polylines.isNotEmpty) ...[
|
||||
FloatingActionButton(
|
||||
heroTag: 'rerouteBtn',
|
||||
backgroundColor: Colors.white,
|
||||
elevation: 6,
|
||||
onPressed: () => controller.recalculateRoute(),
|
||||
tooltip: 'إعادة حساب المسار',
|
||||
child: const Icon(Icons.sync_alt, color: kPrimaryColor, size: 24),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
FloatingActionButton(
|
||||
heroTag: 'gpsBtn',
|
||||
backgroundColor: Colors.white,
|
||||
elevation: 6,
|
||||
onPressed: () {
|
||||
if (controller.myLocation != null) {
|
||||
controller.animateCameraToPosition(
|
||||
controller.myLocation!,
|
||||
bearing: controller.heading,
|
||||
zoom: 18.5,
|
||||
);
|
||||
}
|
||||
},
|
||||
child: const Icon(Icons.gps_fixed, color: Colors.black54, size: 24),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// --- 3. واجهة الملاحة بالتصميم العائم المطور ---
|
||||
Widget _buildFloatingNavigationUI(NavigationController controller) {
|
||||
return Positioned(
|
||||
bottom: 16,
|
||||
left: 16,
|
||||
right: 16,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: const LinearGradient(
|
||||
colors: [Color(0xFF1E88E5), Color(0xFF0D47A1)], // أزرق متدرج
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(28),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.3),
|
||||
blurRadius: 25,
|
||||
offset: const Offset(0, 10),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(22, 20, 22, 22),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// --- الصف العلوي: الإرشاد والمسافة ---
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// الأيقونة
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.2),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: const Icon(Icons.navigation_rounded,
|
||||
color: Colors.white, size: 28),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
// الإرشاد
|
||||
Expanded(
|
||||
child: Text(
|
||||
controller.currentInstruction,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.bold,
|
||||
height: 1.3,
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
// المسافة
|
||||
Text(
|
||||
controller.distanceToNextStep,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 32,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
// --- فاصل ---
|
||||
if (controller.nextInstruction.isNotEmpty ||
|
||||
controller.currentSpeed > 0)
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 14.0),
|
||||
child: Divider(color: Colors.white30, height: 1),
|
||||
),
|
||||
|
||||
// --- الصف السفلي: الإرشاد التالي والسرعة ---
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
// الإرشاد التالي
|
||||
Expanded(
|
||||
child: controller.nextInstruction.isNotEmpty
|
||||
? Text(
|
||||
'التالي: ${controller.nextInstruction}',
|
||||
style: const TextStyle(
|
||||
color: Colors.white70,
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
)
|
||||
: const SizedBox(), // يترك مساحة فارغة إذا لم يكن هناك إرشاد تالي
|
||||
),
|
||||
|
||||
// السرعة
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
controller.currentSpeed.toStringAsFixed(0),
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
const Text(
|
||||
'كم/س',
|
||||
style: TextStyle(
|
||||
color: Colors.white70,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
// lib/controllers/navigation/route_matcher_worker.dart
|
||||
import 'dart:async';
|
||||
import 'dart:isolate';
|
||||
import 'dart:typed_data';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'dart:math';
|
||||
|
||||
/// Worker entrypoint (spawnUri/spawn).
|
||||
/// Messages:
|
||||
/// - init: {'type':'init','coords': Float64List}
|
||||
/// - match: {'type':'match','id': int, 'lat': double, 'lng': double, 'lastIndex': int, 'window': int}
|
||||
/// - dispose: {'type':'dispose'}
|
||||
///
|
||||
/// Responses are sent back as Map via SendPort:
|
||||
/// - {'type':'ready'}
|
||||
/// - {'type':'matchResult','id': id, 'index': overallIndex, 'lat': lat, 'lng': lng, 'dist': meters}
|
||||
void routeMatcherIsolateEntry(SendPort sendPort) {
|
||||
final ReceivePort port = ReceivePort();
|
||||
sendPort.send({'type': 'ready', 'port': port.sendPort});
|
||||
|
||||
Float64List? flat; // [lat,lng,lat,lng,...]
|
||||
int nPoints = 0;
|
||||
|
||||
port.listen((dynamic message) {
|
||||
try {
|
||||
if (message is Map<String, dynamic>) {
|
||||
final type = message['type'] as String? ?? '';
|
||||
if (type == 'init') {
|
||||
final data = message['coords'] as Float64List?;
|
||||
if (data != null) {
|
||||
flat = data;
|
||||
nPoints = flat!.length ~/ 2;
|
||||
sendPort.send({'type': 'inited', 'points': nPoints});
|
||||
} else {
|
||||
sendPort.send({'type': 'error', 'message': 'init missing coords'});
|
||||
}
|
||||
} else if (type == 'match') {
|
||||
if (flat == null) {
|
||||
sendPort.send({'type': 'error', 'message': 'not inited'});
|
||||
return;
|
||||
}
|
||||
final int id = message['id'] as int;
|
||||
final double lat = (message['lat'] as num).toDouble();
|
||||
final double lng = (message['lng'] as num).toDouble();
|
||||
final int lastIndex = (message['lastIndex'] as int?) ?? 0;
|
||||
final int window = (message['window'] as int?) ?? 120;
|
||||
|
||||
final result =
|
||||
_findClosestWindowInternal(flat!, lat, lng, lastIndex, window);
|
||||
sendPort.send({
|
||||
'type': 'matchResult',
|
||||
'id': id,
|
||||
'index': result['index'],
|
||||
'lat': result['lat'],
|
||||
'lng': result['lng'],
|
||||
'dist': result['dist']
|
||||
});
|
||||
} else if (type == 'dispose') {
|
||||
port.close();
|
||||
sendPort.send({'type': 'disposed'});
|
||||
} else {
|
||||
sendPort.send({'type': 'error', 'message': 'unknown message type'});
|
||||
}
|
||||
}
|
||||
} catch (e, st) {
|
||||
sendPort.send(
|
||||
{'type': 'error', 'message': e.toString(), 'stack': st.toString()});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Internal helper: projection on segments, windowed search.
|
||||
/// Returns Map {index, lat, lng, dist}
|
||||
Map<String, dynamic> _findClosestWindowInternal(
|
||||
Float64List flat, double lat, double lng, int lastIndex, int window) {
|
||||
final int n = flat.length ~/ 2;
|
||||
final int start = max(0, lastIndex - window);
|
||||
final int end = min(n - 1, lastIndex + window);
|
||||
|
||||
double minDist = double.infinity;
|
||||
int bestIdx = lastIndex;
|
||||
double bestLat = flat[lastIndex * 2];
|
||||
double bestLng = flat[lastIndex * 2 + 1];
|
||||
|
||||
for (int i = start; i < end; i++) {
|
||||
final double aLat = flat[i * 2];
|
||||
final double aLng = flat[i * 2 + 1];
|
||||
final double bLat = flat[(i + 1) * 2];
|
||||
final double bLng = flat[(i + 1) * 2 + 1];
|
||||
|
||||
final proj = _closestPointOnSegmentLatLng(lat, lng, aLat, aLng, bLat, bLng);
|
||||
final double d = proj['dist'] as double;
|
||||
if (d < minDist) {
|
||||
minDist = d;
|
||||
bestLat = proj['lat'] as double;
|
||||
bestLng = proj['lng'] as double;
|
||||
// choose overall index: i or i+1 depending on t
|
||||
final double t = proj['t'] as double;
|
||||
bestIdx = i + (t > 0.5 ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
return {'index': bestIdx, 'lat': bestLat, 'lng': bestLng, 'dist': minDist};
|
||||
}
|
||||
|
||||
/// Projection math on geodetic points approximated in degrees (good for short distances).
|
||||
Map<String, dynamic> _closestPointOnSegmentLatLng(
|
||||
double px, double py, double ax, double ay, double bx, double by) {
|
||||
// Here px=lat, py=lng; ax=lat, ay=lng, etc.
|
||||
final double x0 = px;
|
||||
final double y0 = py;
|
||||
final double x1 = ax;
|
||||
final double y1 = ay;
|
||||
final double x2 = bx;
|
||||
final double y2 = by;
|
||||
|
||||
final double dx = x2 - x1;
|
||||
final double dy = y2 - y1;
|
||||
double t = 0.0;
|
||||
final double len2 = dx * dx + dy * dy;
|
||||
if (len2 > 0) {
|
||||
t = ((x0 - x1) * dx + (y0 - y1) * dy) / len2;
|
||||
if (t < 0) t = 0;
|
||||
if (t > 1) t = 1;
|
||||
}
|
||||
final double projX = x1 + t * dx;
|
||||
final double projY = y1 + t * dy;
|
||||
|
||||
final double distMeters = _haversineDistanceMeters(x0, y0, projX, projY);
|
||||
return {'lat': projX, 'lng': projY, 't': t, 'dist': distMeters};
|
||||
}
|
||||
|
||||
/// Haversine distance (meters)
|
||||
double _haversineDistanceMeters(
|
||||
double lat1, double lng1, double lat2, double lng2) {
|
||||
final double R = 6371000.0;
|
||||
final double dLat = _deg2rad(lat2 - lat1);
|
||||
final double dLon = _deg2rad(lng2 - lng1);
|
||||
final double a = sin(dLat / 2) * sin(dLat / 2) +
|
||||
cos(_deg2rad(lat1)) * cos(_deg2rad(lat2)) * sin(dLon / 2) * sin(dLon / 2);
|
||||
final double c = 2 * atan2(sqrt(a), sqrt(1 - a));
|
||||
return R * c;
|
||||
}
|
||||
|
||||
double _deg2rad(double deg) => deg * pi / 180.0;
|
||||
@@ -1,358 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:local_auth/local_auth.dart';
|
||||
import 'package:sefer_driver/constant/style.dart';
|
||||
import 'package:sefer_driver/controller/firebase/firbase_messge.dart';
|
||||
import 'package:sefer_driver/controller/firebase/local_notification.dart';
|
||||
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
|
||||
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
|
||||
import 'package:flutter/material.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 '../../../views/widgets/mydialoug.dart';
|
||||
import '../../firebase/notification_service.dart';
|
||||
|
||||
class CaptainWalletController extends GetxController {
|
||||
bool isLoading = false;
|
||||
final formKeyTransfer = GlobalKey<FormState>();
|
||||
final formKeyAccount = GlobalKey<FormState>();
|
||||
Map walletDate = {};
|
||||
Map walletDateVisa = {};
|
||||
Map walletDriverPointsDate = {};
|
||||
final formKey = GlobalKey<FormState>();
|
||||
String totalAmount = '0';
|
||||
double kazan = 0;
|
||||
String totalAmountVisa = '0';
|
||||
String totalPoints = '0';
|
||||
final amountFromBudgetController = TextEditingController();
|
||||
final newDriverPhoneController = TextEditingController();
|
||||
final phoneWallet = TextEditingController();
|
||||
final cardBank = TextEditingController();
|
||||
final bankCode = TextEditingController();
|
||||
|
||||
payFromBudget() async {
|
||||
if (formKey.currentState!.validate()) {
|
||||
var pointFromBudget = int.parse((amountFromBudgetController.text));
|
||||
|
||||
// await getPaymentId('fromBudgetToPoints',
|
||||
// int.parse((amountFromBudgetController.text)) * -1);
|
||||
var paymentToken3 =
|
||||
await generateToken((pointFromBudget * -1).toString());
|
||||
var paymentID = await getPaymentId(
|
||||
'fromBudgetToPoints', (pointFromBudget * -1).toString());
|
||||
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
|
||||
'amount': (pointFromBudget * -1).toString(),
|
||||
'rideId': paymentID.toString(),
|
||||
'payment_method': 'myBudget',
|
||||
'passengerID': 'myBudgetToPoint',
|
||||
'token': paymentToken3,
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
});
|
||||
Future.delayed(const Duration(seconds: 1));
|
||||
await addDriverWallet(
|
||||
'fromBudget', pointFromBudget.toString(), pointFromBudget.toString());
|
||||
update();
|
||||
Get.back();
|
||||
await refreshCaptainWallet();
|
||||
NotificationController().showNotification(
|
||||
'You have successfully charged your account'.tr,
|
||||
'$pointFromBudget ${'has been added to your budget'.tr}',
|
||||
'tone1',
|
||||
'',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// متغيرات الحالة (تأكد من تعريفها في الـ Controller)
|
||||
bool isError = false;
|
||||
int morningCount = 0;
|
||||
int afternoonCount = 0;
|
||||
String lastWeekIncome = '0';
|
||||
String bankAccount = '';
|
||||
Future<void> refreshCaptainWallet() async {
|
||||
// 1. تفعيل حالة التحميل مرة واحدة فقط
|
||||
isLoading = true;
|
||||
isError = false;
|
||||
update(); // تحديث الواجهة لإظهار اللودر
|
||||
|
||||
try {
|
||||
// 2. طلب واحد فقط للسيرفر الموحد (The Aggregated Endpoint)
|
||||
var response = await CRUD().getWallet(
|
||||
link:
|
||||
"${AppLink.paymentServer}/ride/driverWallet/get_wallet_summary.php",
|
||||
payload: {'driverID': box.read(BoxName.driverID).toString()},
|
||||
);
|
||||
|
||||
isLoading = false;
|
||||
|
||||
if (response != 'failure') {
|
||||
var body = jsonDecode(response);
|
||||
if (body['status'] == "success") {
|
||||
var data = body['message'];
|
||||
walletDate = data;
|
||||
// تفكيك البيانات من الرد الموحد
|
||||
// التعامل مع القيم كـ String أو num لتجنب مشاكل الـ Parsing
|
||||
totalAmount = (data['cash_balance'] ?? 0).toString();
|
||||
|
||||
// الفيزا + التحويلات مدموجة وجاهزة من السيرفر
|
||||
totalAmountVisa = (data['wallet_balance'] ?? 0).toString();
|
||||
|
||||
// النقاط
|
||||
double p = double.tryParse(data['points_balance'].toString()) ?? 0.0;
|
||||
totalPoints = p.toStringAsFixed(0);
|
||||
|
||||
// بيانات الرحلات (تأتي من RID Server)
|
||||
morningCount = int.tryParse(data['morning_count'].toString()) ?? 0;
|
||||
afternoonCount =
|
||||
int.tryParse(data['afternoon_count'].toString()) ?? 0;
|
||||
lastWeekIncome = (data['weekly_income'] ?? 0).toString();
|
||||
|
||||
bankAccount = data['bank_account'] ?? "";
|
||||
|
||||
// حفظ بيانات البنك لوكالي لاستخدامها لاحقاً دون طلب
|
||||
if (bankAccount.isNotEmpty) {
|
||||
box.write(BoxName.accountIdStripeConnect, bankAccount);
|
||||
}
|
||||
} else {
|
||||
isError = true;
|
||||
mySnackeBarError("Failed to fetch wallet data");
|
||||
}
|
||||
} else {
|
||||
isError = true;
|
||||
}
|
||||
} catch (e) {
|
||||
isLoading = false;
|
||||
isError = true;
|
||||
print("Wallet Refresh Error: $e");
|
||||
}
|
||||
|
||||
// 3. تحديث نهائي واحد للواجهة
|
||||
update();
|
||||
}
|
||||
|
||||
List amountToNewDriverMap = [];
|
||||
bool isNewTransfer = false;
|
||||
Future detectNewDriverFromMyBudget() async {
|
||||
if (formKeyTransfer.currentState!.validate()) {
|
||||
if (int.parse(amountFromBudgetController.text) <
|
||||
double.parse(totalAmountVisa) &&
|
||||
int.parse(amountFromBudgetController.text) > 10) {
|
||||
//get new driver details
|
||||
isNewTransfer = true;
|
||||
update();
|
||||
var res = await CRUD().get(
|
||||
link: AppLink.getDriverDetails,
|
||||
payload: {'driver_phone': '+2${newDriverPhoneController.text}'});
|
||||
isNewTransfer = false;
|
||||
update();
|
||||
if (res != 'failure') {
|
||||
var d = jsonDecode(res);
|
||||
amountToNewDriverMap = d['data'];
|
||||
// update();
|
||||
} else {
|
||||
mySnackeBarError("This driver is not registered".tr);
|
||||
}
|
||||
} else {
|
||||
mySnackeBarError('Your Budget less than needed'.tr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String paymentToken = '';
|
||||
Future<String> generateToken(String amount) async {
|
||||
var res =
|
||||
await CRUD().postWallet(link: AppLink.addPaymentTokenDriver, payload: {
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
'amount': amount.toString(),
|
||||
});
|
||||
var d = (res);
|
||||
return d['message'];
|
||||
}
|
||||
|
||||
// late String paymentID;
|
||||
Future<String> getPaymentId(String paymentMethod, amount) async {
|
||||
// paymentToken = await generateToken(amount);
|
||||
var res =
|
||||
await CRUD().postWallet(link: AppLink.addDriverPaymentPoints, payload: {
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
'amount': amount.toString(),
|
||||
'payment_method': paymentMethod.toString(),
|
||||
});
|
||||
var d = (res);
|
||||
// paymentID = d['message'].toString();
|
||||
return d['message'];
|
||||
}
|
||||
|
||||
Future addDriverWallet(String paymentMethod, point, count) async {
|
||||
paymentToken = await generateToken(count);
|
||||
var paymentID = await getPaymentId(paymentMethod, point.toString());
|
||||
await CRUD().postWallet(link: AppLink.addDriversWalletPoints, payload: {
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
'paymentID': paymentID.toString(),
|
||||
'amount': point,
|
||||
'token': paymentToken,
|
||||
'paymentMethod': paymentMethod.toString(),
|
||||
});
|
||||
}
|
||||
|
||||
Future addDriverPayment(String paymentMethod, point, wayPay) async {
|
||||
paymentToken = await generateToken(point);
|
||||
var paymentID = await getPaymentId(paymentMethod, point.toString());
|
||||
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
|
||||
'amount': point.toString(),
|
||||
'rideId': paymentID.toString(),
|
||||
'payment_method': paymentMethod,
|
||||
'passengerID': wayPay,
|
||||
'token': paymentToken,
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
});
|
||||
}
|
||||
|
||||
Future addDriverWalletFromPromo(String paymentMethod, point) async {
|
||||
var resPromotion =
|
||||
await CRUD().postWallet(link: AppLink.addpromotionDriver, payload: {
|
||||
'driver_id': box.read(BoxName.driverID).toString(),
|
||||
'payment_amount': point,
|
||||
'timePromo': paymentMethod,
|
||||
});
|
||||
if (resPromotion != 'failure') {
|
||||
paymentToken = await generateToken(point);
|
||||
var paymentID = await getPaymentId(paymentMethod, point.toString());
|
||||
var res =
|
||||
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
|
||||
'amount': point,
|
||||
'rideId': paymentID.toString(),
|
||||
'payment_method': paymentMethod.toString(),
|
||||
'passengerID': paymentMethod,
|
||||
'token': paymentToken,
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
});
|
||||
if (res != 'failure') {
|
||||
String title = 'wallet_updated'.tr; // Notification title
|
||||
String message = '${'wallet_credited_message'.tr} $point';
|
||||
String tone = 'default_tone'.tr; // Notification tone or sound
|
||||
String payLoad =
|
||||
'wallet_updated'; // Additional data payload for the notification
|
||||
|
||||
Get.find<NotificationController>()
|
||||
.showNotification(title, message, tone, payLoad);
|
||||
}
|
||||
} else {
|
||||
Get.back();
|
||||
mySnackeBarError(
|
||||
"A promotion record for this driver already exists for today.".tr);
|
||||
}
|
||||
}
|
||||
|
||||
Future addDriverWalletToInvitor(String paymentMethod, driverID, point) async {
|
||||
paymentToken = await generateToken(point);
|
||||
var paymentID = await getPaymentId(paymentMethod, point.toString());
|
||||
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
|
||||
'driverID': driverID,
|
||||
'amount': point,
|
||||
'token': paymentToken,
|
||||
'rideId': paymentID.toString(),
|
||||
'payment_method': paymentMethod.toString(),
|
||||
'passengerID': paymentMethod,
|
||||
});
|
||||
await addTripzWallet(paymentMethod,
|
||||
(double.parse(point) * -2).toString()); // deduct 2 from Tripz wallet
|
||||
}
|
||||
|
||||
Future addTripzWallet(String paymentMethod, String point) async {
|
||||
var TripzToken = await generateToken(point.toString());
|
||||
await CRUD().postWallet(link: AppLink.addTripzWallet, payload: {
|
||||
'amount': point.toString(),
|
||||
'paymentMethod': paymentMethod,
|
||||
'passengerId': 'driver',
|
||||
'token': TripzToken,
|
||||
'driverId': box.read(BoxName.driverID).toString(),
|
||||
});
|
||||
}
|
||||
|
||||
Future addTransferDriversWallet(String paymentMethod1, paymentMethod2) async {
|
||||
var paymentID =
|
||||
await getPaymentId(paymentMethod1, amountFromBudgetController.text);
|
||||
paymentToken = await generateToken(
|
||||
(int.parse(amountFromBudgetController.text) * -1).toString());
|
||||
|
||||
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
|
||||
'amount': (int.parse(amountFromBudgetController.text) * -1).toString(),
|
||||
'rideId': paymentID.toString(),
|
||||
'payment_method': paymentMethod1,
|
||||
'passengerID': 'To ${amountToNewDriverMap[0]['id']}',
|
||||
'token': paymentToken,
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
});
|
||||
|
||||
paymentID = await getPaymentId(paymentMethod2,
|
||||
(int.parse(amountFromBudgetController.text) - 5).toString());
|
||||
paymentToken = await generateToken(amountFromBudgetController.text);
|
||||
var res1 =
|
||||
await CRUD().postWallet(link: AppLink.addDriversWalletPoints, payload: {
|
||||
'driverID': amountToNewDriverMap[0]['id'].toString(),
|
||||
'paymentID': paymentID.toString(),
|
||||
'amount': ((int.parse(amountFromBudgetController.text) - 5))
|
||||
// kazan) // double.parse(kazan) .08 for egypt
|
||||
.toStringAsFixed(
|
||||
0), // this will convert buddget to poitns by kazan .08
|
||||
|
||||
'token': paymentToken,
|
||||
'paymentMethod': paymentMethod2.toString(),
|
||||
});
|
||||
if (res1 != 'failure') {
|
||||
NotificationService.sendNotification(
|
||||
target: amountToNewDriverMap[0]['token'].toString(),
|
||||
title: 'Transfer'.tr,
|
||||
body: '${'You have transfer to your wallet from'.tr}'
|
||||
'${box.read(BoxName.nameDriver)}',
|
||||
|
||||
isTopic: false, // Important: this is a token
|
||||
tone: 'ding',
|
||||
driverList: [], category: 'Transfer',
|
||||
);
|
||||
await addTripzWallet('payout fee', '5');
|
||||
|
||||
Get.defaultDialog(
|
||||
title: 'transfer Successful'.tr,
|
||||
middleText: '',
|
||||
titleStyle: AppStyle.title,
|
||||
confirm: MyElevatedButton(
|
||||
title: 'Ok'.tr,
|
||||
onPressed: () async {
|
||||
Get.back();
|
||||
Get.back();
|
||||
|
||||
await refreshCaptainWallet();
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
//check if account bank is created or not
|
||||
Future checkAccountCaptainBank() async {
|
||||
isLoading = true;
|
||||
update();
|
||||
if (box.read(BoxName.accountIdStripeConnect).toString().isEmpty) {
|
||||
var res = await CRUD().get(link: AppLink.getAccount, payload: {
|
||||
'id': box.read(BoxName.driverID).toString(),
|
||||
});
|
||||
var d = jsonDecode(res);
|
||||
if (d['status'] != 'failure') {
|
||||
box.write(BoxName.accountIdStripeConnect,
|
||||
d['message'][0]['accountBank'].toString());
|
||||
}
|
||||
}
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() async {
|
||||
await refreshCaptainWallet();
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../constant/box_name.dart';
|
||||
import '../../functions/digit_obsecur_formate.dart';
|
||||
import '../../functions/secure_storage.dart';
|
||||
|
||||
class CreditCardController extends GetxController {
|
||||
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
|
||||
final TextEditingController cardNumberController = TextEditingController();
|
||||
final TextEditingController cardHolderNameController =
|
||||
TextEditingController();
|
||||
final TextEditingController expiryDateController = TextEditingController();
|
||||
final TextEditingController cvvCodeController = TextEditingController();
|
||||
openPayment() async {
|
||||
String? cardNumber = await SecureStorage().readData(BoxName.cardNumber);
|
||||
String? cardHolderName =
|
||||
await SecureStorage().readData(BoxName.cardHolderName);
|
||||
String? expiryDate = await SecureStorage().readData(BoxName.expiryDate);
|
||||
String? cvvCode = await SecureStorage().readData(BoxName.cvvCode);
|
||||
|
||||
if (cvvCode != null && cvvCode.isNotEmpty) {
|
||||
final maskedCardNumber = DigitObscuringFormatter()
|
||||
.formatEditUpdate(
|
||||
TextEditingValue.empty,
|
||||
TextEditingValue(text: cardNumber ?? ''),
|
||||
)
|
||||
.text;
|
||||
|
||||
cardNumberController.text = maskedCardNumber;
|
||||
cardHolderNameController.text = cardHolderName ?? '';
|
||||
expiryDateController.text = expiryDate ?? '';
|
||||
cvvCodeController.text = cvvCode;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() async {
|
||||
super.onInit();
|
||||
openPayment();
|
||||
// String? cardNumber = await SecureStorage().readData(BoxName.cardNumber);
|
||||
// String? cardHolderName =
|
||||
// await SecureStorage().readData(BoxName.cardHolderName);
|
||||
// String? expiryDate = await SecureStorage().readData(BoxName.expiryDate);
|
||||
// String? cvvCode = await SecureStorage().readData(BoxName.cvvCode);
|
||||
|
||||
// if (cvvCode != null && cvvCode.isNotEmpty) {
|
||||
// final maskedCardNumber = DigitObscuringFormatter()
|
||||
// .formatEditUpdate(
|
||||
// TextEditingValue.empty,
|
||||
// TextEditingValue(text: cardNumber ?? ''),
|
||||
// )
|
||||
// .text;
|
||||
|
||||
// cardNumberController.text = maskedCardNumber;
|
||||
// cardHolderNameController.text = cardHolderName ?? '';
|
||||
// expiryDateController.text = expiryDate ?? '';
|
||||
// cvvCodeController.text = cvvCode;
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
class CreditCardModel {
|
||||
String cardNumber;
|
||||
String cardHolderName;
|
||||
String expiryDate;
|
||||
String cvvCode;
|
||||
|
||||
CreditCardModel({
|
||||
required this.cardNumber,
|
||||
required this.cardHolderName,
|
||||
required this.expiryDate,
|
||||
required this.cvvCode,
|
||||
});
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:local_auth/local_auth.dart';
|
||||
import 'package:sefer_driver/constant/box_name.dart';
|
||||
import 'package:sefer_driver/controller/payment/smsPaymnet/payment_services.dart';
|
||||
import 'package:sefer_driver/main.dart';
|
||||
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../../constant/links.dart';
|
||||
import '../../../views/widgets/mydialoug.dart';
|
||||
import '../../functions/crud.dart';
|
||||
import 'captain_wallet_controller.dart';
|
||||
|
||||
class PaymobPayout extends GetxController {
|
||||
bool isLoading = false;
|
||||
String dropdownValue = 'etisalat';
|
||||
|
||||
int payOutFee = 5;
|
||||
payToDriverWallet(String amount, String issuer, String msisdn) async {
|
||||
bool isAvailable = await LocalAuthentication().isDeviceSupported();
|
||||
if (isAvailable) {
|
||||
// Authenticate the user
|
||||
bool didAuthenticate = await LocalAuthentication().authenticate(
|
||||
localizedReason: 'Use Touch ID or Face ID to confirm payment',
|
||||
options: AuthenticationOptions(
|
||||
biometricOnly: true,
|
||||
sensitiveTransaction: true,
|
||||
));
|
||||
if (didAuthenticate) {
|
||||
var dec = await CRUD()
|
||||
.postWallet(link: AppLink.paymobPayoutDriverWallet, payload: {
|
||||
"issuer": issuer,
|
||||
"method": "wallet",
|
||||
"amount": amount, //9.0,
|
||||
"full_name":
|
||||
'${box.read(BoxName.nameDriver)} ${box.read(BoxName.lastNameDriver)}',
|
||||
"msisdn": msisdn, //"01010101010",
|
||||
"bank_transaction_type": "cash_transfer"
|
||||
});
|
||||
if (dec['disbursement_status'] == 'successful') {
|
||||
var paymentToken = await Get.find<CaptainWalletController>()
|
||||
.generateToken(
|
||||
((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
|
||||
.toStringAsFixed(0));
|
||||
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
|
||||
'rideId': DateTime.now().toIso8601String(),
|
||||
'amount':
|
||||
((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
|
||||
.toStringAsFixed(0),
|
||||
'payment_method': 'payout',
|
||||
'passengerID': 'myself',
|
||||
'token': paymentToken,
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
});
|
||||
await Get.find<CaptainWalletController>()
|
||||
.addTripzWallet('payout fee myself', payOutFee.toString());
|
||||
await updatePaymentToPaid(box.read(BoxName.driverID).toString());
|
||||
await sendEmail(
|
||||
box.read(BoxName.driverID).toString(),
|
||||
amount,
|
||||
box.read(BoxName.phoneDriver).toString(),
|
||||
box.read(BoxName.nameDriver).toString(),
|
||||
'Wallet',
|
||||
box.read(BoxName.emailDriver).toString());
|
||||
|
||||
mySnackbarSuccess('${'Transaction successful'.tr} ${dec['amount']}');
|
||||
|
||||
Get.find<CaptainWalletController>().refreshCaptainWallet();
|
||||
} else if (dec['disbursement_status'] == 'failed') {
|
||||
mySnackeBarError('Transaction failed'.tr);
|
||||
}
|
||||
} else {
|
||||
MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
|
||||
Get.back();
|
||||
});
|
||||
}
|
||||
} else {
|
||||
MyDialog().getDialog('Biometric Authentication'.tr,
|
||||
'You should use Touch ID or Face ID to confirm payment'.tr, () {
|
||||
Get.back();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future updatePaymentToPaid(String driverID) async {
|
||||
await CRUD().postWallet(link: AppLink.updatePaymetToPaid, payload: {
|
||||
'driverID': driverID.toString(),
|
||||
});
|
||||
}
|
||||
|
||||
Future sendEmail(
|
||||
String driverId, amount, phone, name, bankCardNumber, email) async {
|
||||
await CRUD().sendEmail(AppLink.sendEmailToDrivertransaction, {
|
||||
"driverID": driverId,
|
||||
"total_amount": amount,
|
||||
"phone": phone,
|
||||
"name_arabic": name,
|
||||
"accountBank": bankCardNumber,
|
||||
"email": email
|
||||
});
|
||||
}
|
||||
|
||||
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 {}
|
||||
}
|
||||
|
||||
payToDriverBankAccount(
|
||||
String amount, String bankCardNumber, String bankCode) async {
|
||||
bool isAvailable = await LocalAuthentication().isDeviceSupported();
|
||||
if (isAvailable) {
|
||||
// Authenticate the user
|
||||
bool didAuthenticate = await LocalAuthentication().authenticate(
|
||||
localizedReason: 'Use Touch ID or Face ID to confirm payment',
|
||||
options: AuthenticationOptions(
|
||||
biometricOnly: true,
|
||||
sensitiveTransaction: true,
|
||||
));
|
||||
if (didAuthenticate) {
|
||||
var body = {
|
||||
"issuer": "bank_card",
|
||||
"method": "bank_card",
|
||||
"amount": amount, //9.0,
|
||||
"full_name":
|
||||
'${box.read(BoxName.nameDriver)} ${box.read(BoxName.lastNameDriver)}',
|
||||
"bank_card_number": bankCardNumber, //"1111-2222-3333-4444",
|
||||
"bank_code": bankCode, //"CIB",
|
||||
"bank_transaction_type": "cash_transfer"
|
||||
};
|
||||
var dec = await CRUD().postWallet(
|
||||
link:
|
||||
'wl.tripz-egypt.com/v1/main/ride/payMob/paymob_driver/paymob_payout.php',
|
||||
payload: body,
|
||||
);
|
||||
if (dec['disbursement_status'] == 'successful') {
|
||||
var paymentToken = await Get.find<CaptainWalletController>()
|
||||
.generateToken(
|
||||
((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
|
||||
.toStringAsFixed(0));
|
||||
await CRUD().postWallet(link: AppLink.addDrivePayment, payload: {
|
||||
'rideId': DateTime.now().toIso8601String(),
|
||||
'amount':
|
||||
((-1) * (double.parse(dec['amount'].toString())) - payOutFee)
|
||||
.toStringAsFixed(0),
|
||||
'payment_method': 'payout',
|
||||
'passengerID': 'myself',
|
||||
'token': paymentToken,
|
||||
'driverID': box.read(BoxName.driverID).toString(),
|
||||
});
|
||||
await Get.find<CaptainWalletController>()
|
||||
.addTripzWallet('payout fee myself', payOutFee.toString());
|
||||
await updatePaymentToPaid(box.read(BoxName.driverID).toString());
|
||||
await sendEmail(
|
||||
box.read(BoxName.driverID).toString(),
|
||||
amount,
|
||||
box.read(BoxName.phoneDriver).toString(),
|
||||
box.read(BoxName.nameDriver).toString(),
|
||||
'Wallet',
|
||||
box.read(BoxName.emailDriver).toString());
|
||||
|
||||
mySnackbarSuccess('${'Transaction successful'.tr} ${dec['amount']}');
|
||||
Get.find<CaptainWalletController>().refreshCaptainWallet();
|
||||
} else if (dec['disbursement_status'] == 'failed') {
|
||||
mySnackeBarError('Transaction failed'.tr);
|
||||
}
|
||||
} else {
|
||||
MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
|
||||
Get.back();
|
||||
});
|
||||
}
|
||||
} else {
|
||||
MyDialog().getDialog('Biometric Authentication'.tr,
|
||||
'You should use Touch ID or Face ID to confirm payment'.tr, () {
|
||||
Get.back();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future payToWalletDriverAll(
|
||||
String amount, String issuer, String msisdn) async {
|
||||
bool isAvailable = await LocalAuthentication().isDeviceSupported();
|
||||
if (isAvailable) {
|
||||
// Authenticate the user
|
||||
bool didAuthenticate = await LocalAuthentication().authenticate(
|
||||
localizedReason: 'Use Touch ID or Face ID to confirm payment',
|
||||
options: AuthenticationOptions(
|
||||
biometricOnly: true,
|
||||
sensitiveTransaction: true,
|
||||
));
|
||||
if (didAuthenticate) {
|
||||
await payToDriverWallet(amount, issuer, msisdn);
|
||||
} else {
|
||||
MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
|
||||
Get.back();
|
||||
});
|
||||
}
|
||||
} else {
|
||||
MyDialog().getDialog('Biometric Authentication'.tr,
|
||||
'You should use Touch ID or Face ID to confirm payment'.tr, () {
|
||||
Get.back();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future payToBankDriverAll(
|
||||
String amount, String bankCardNumber, String bankCode) async {
|
||||
bool isAvailable = await LocalAuthentication().isDeviceSupported();
|
||||
if (isAvailable) {
|
||||
// Authenticate the user
|
||||
bool didAuthenticate = await LocalAuthentication().authenticate(
|
||||
localizedReason: 'Use Touch ID or Face ID to confirm payment',
|
||||
options: AuthenticationOptions(
|
||||
biometricOnly: true,
|
||||
sensitiveTransaction: true,
|
||||
));
|
||||
if (didAuthenticate) {
|
||||
await payToDriverBankAccount(amount, bankCardNumber, bankCode);
|
||||
} else {
|
||||
MyDialog().getDialog('Authentication failed'.tr, ''.tr, () {
|
||||
Get.back();
|
||||
});
|
||||
}
|
||||
} else {
|
||||
MyDialog().getDialog('Biometric Authentication'.tr,
|
||||
'You should use Touch ID or Face ID to confirm payment'.tr, () {
|
||||
Get.back();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'package:sefer_driver/constant/style.dart';
|
||||
|
||||
import '../../constant/api_key.dart';
|
||||
import '../../constant/links.dart';
|
||||
import '../functions/crud.dart';
|
||||
import '../functions/location_controller.dart';
|
||||
|
||||
class PointsForRiderController extends GetxController {
|
||||
List<String> locations = [];
|
||||
String hintTextDestinationPoint = 'Search for your destination'.tr;
|
||||
TextEditingController placeStartController = TextEditingController();
|
||||
|
||||
void addLocation(String location) {
|
||||
locations.add(location);
|
||||
update();
|
||||
}
|
||||
|
||||
void getTextFromList(String location) {
|
||||
locations.add(location);
|
||||
update();
|
||||
Get.back();
|
||||
}
|
||||
|
||||
void removeLocation(int index) {
|
||||
locations.removeAt(index);
|
||||
update();
|
||||
}
|
||||
|
||||
void onReorder(int oldIndex, int newIndex) {
|
||||
if (newIndex > oldIndex) {
|
||||
newIndex -= 1;
|
||||
update();
|
||||
}
|
||||
|
||||
final item = locations.removeAt(oldIndex);
|
||||
locations.insert(newIndex, item);
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
class LocationModel {
|
||||
String name;
|
||||
double lat, lon;
|
||||
|
||||
LocationModel({required this.name, required this.lat, required this.lon});
|
||||
}
|
||||
|
||||
class WayPointController extends GetxController {
|
||||
// A list of text editing controllers for each text field
|
||||
// final textFields = [TextEditingController()].obs;
|
||||
List<String> wayPoints = [];
|
||||
List<List<dynamic>> placeListResponse = [];
|
||||
double wayPointHeight = 400;
|
||||
String hintTextDestinationPoint = 'Search for your destination'.tr;
|
||||
TextEditingController textSearchCotroller = TextEditingController();
|
||||
// A list of places corresponding to each text field
|
||||
final places = <String>[];
|
||||
|
||||
final hintTextPointList = <String>[];
|
||||
late LatLng myLocation;
|
||||
|
||||
void addWayPoints() {
|
||||
String wayPoint = 'Add a Stop'.tr;
|
||||
|
||||
if (wayPoints.length < 5) {
|
||||
wayPoints.add(wayPoint);
|
||||
update();
|
||||
} else {
|
||||
Get.defaultDialog(
|
||||
title: 'This is most WayPoints',
|
||||
titleStyle: AppStyle.title,
|
||||
middleText: '');
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
void removeTextField(int index) {
|
||||
wayPoints.removeAt(index);
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
// A method to reorder the text fields and the places
|
||||
void reorderTextFields(int oldIndex, int newIndex) {
|
||||
if (newIndex > oldIndex) {
|
||||
newIndex -= 1;
|
||||
}
|
||||
final wayPoint = wayPoints.removeAt(oldIndex);
|
||||
wayPoints.insert(newIndex, wayPoint);
|
||||
update();
|
||||
}
|
||||
|
||||
void updatePlace(int index, String input) async {
|
||||
var url =
|
||||
'${AppLink.googleMapsLink}place/nearbysearch/json?keyword=$input&location=${myLocation.latitude},${myLocation.longitude}&radius=50000&language=en&key=${AK.mapAPIKEY.toString()}';
|
||||
var response = await CRUD().getGoogleApi(link: url, payload: {});
|
||||
// final place = input;
|
||||
// if (index == 0) {
|
||||
List<dynamic> newList = [];
|
||||
placeListResponse.add(newList);
|
||||
newList = response['results'];
|
||||
placeListResponse[index].add(newList);
|
||||
update();
|
||||
// }
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
Get.put(LocationController());
|
||||
addWayPoints();
|
||||
myLocation = Get.find<LocationController>().myLocation;
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
|
||||
class PlaceList extends StatelessWidget {
|
||||
// Get the controller instance
|
||||
final controller = Get.put(WayPointController());
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Use the Obx widget to rebuild the widget when the controller changes
|
||||
return Obx(() {
|
||||
// Use the ListView widget to display the list of places
|
||||
return ListView(
|
||||
// The children of the list are the places
|
||||
children: [
|
||||
// Loop through the places in the controller
|
||||
for (final place in controller.places)
|
||||
// Create a text widget for each place
|
||||
Text(
|
||||
// Use the place as the text
|
||||
place,
|
||||
|
||||
// Add some style and padding
|
||||
style: const TextStyle(fontSize: 18.0),
|
||||
),
|
||||
],
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:sefer_driver/constant/box_name.dart';
|
||||
import 'package:sefer_driver/constant/colors.dart';
|
||||
import 'package:sefer_driver/constant/links.dart';
|
||||
import 'package:sefer_driver/constant/style.dart';
|
||||
import 'package:sefer_driver/controller/functions/crud.dart';
|
||||
import 'package:sefer_driver/main.dart';
|
||||
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
|
||||
|
||||
class FeedBackController extends GetxController {
|
||||
bool isLoading = false;
|
||||
final formKey = GlobalKey<FormState>();
|
||||
final feedbackController = TextEditingController();
|
||||
|
||||
void addFeedBack() async {
|
||||
isLoading = true;
|
||||
update();
|
||||
var res = await CRUD().post(link: AppLink.addFeedBack, payload: {
|
||||
'passengerId': box.read(BoxName.passengerID).toString(),
|
||||
'feedBack': feedbackController.text
|
||||
});
|
||||
var d = jsonDecode(res);
|
||||
if (d['status'].toString() == 'success') {
|
||||
Get.defaultDialog(
|
||||
title: 'Success'.tr,
|
||||
titleStyle: AppStyle.title,
|
||||
middleText: 'Feedback data saved successfully'.tr,
|
||||
middleTextStyle: AppStyle.title,
|
||||
confirm: MyElevatedButton(
|
||||
kolor: AppColor.greenColor,
|
||||
title: 'Ok'.tr,
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
Get.back();
|
||||
}));
|
||||
}
|
||||
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
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';
|
||||
|
||||
class OrderHistoryController extends GetxController {
|
||||
List<dynamic> orderHistoryListPassenger = [];
|
||||
bool isloading = true;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
getOrderHistoryByPassenger();
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
Future getOrderHistoryByPassenger() async {
|
||||
var res = await CRUD().get(link: AppLink.getRides, payload: {
|
||||
'passenger_id': box.read(BoxName.passengerID).toString(),
|
||||
});
|
||||
if (res.toString() == 'failure') {
|
||||
// Get.snackbar('failure', 'message');
|
||||
isloading = false;
|
||||
update();
|
||||
} else {
|
||||
var jsonDecoded = jsonDecode(res);
|
||||
|
||||
orderHistoryListPassenger = jsonDecoded['data'];
|
||||
isloading = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:sefer_driver/constant/links.dart';
|
||||
import 'package:sefer_driver/constant/style.dart';
|
||||
import 'package:sefer_driver/controller/functions/crud.dart';
|
||||
import 'package:sefer_driver/views/widgets/elevated_btn.dart';
|
||||
|
||||
class PromosController extends GetxController {
|
||||
List<dynamic> promoList = [];
|
||||
bool isLoading = true;
|
||||
late String promos;
|
||||
@override
|
||||
void onInit() {
|
||||
getPromoByToday();
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
Future getPromoByToday() async {
|
||||
var res = await CRUD().get(link: AppLink.getPromoBytody, payload: {});
|
||||
if (res.toString() == 'failure') {
|
||||
Get.defaultDialog(
|
||||
title: 'No Promo for today .'.tr,
|
||||
middleText: '',
|
||||
titleStyle: AppStyle.title,
|
||||
confirm: MyElevatedButton(
|
||||
title: 'Back'.tr,
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
Get.back();
|
||||
}));
|
||||
isLoading = false;
|
||||
update();
|
||||
} else {
|
||||
var jsonDecoded = jsonDecode(res);
|
||||
|
||||
promoList = jsonDecoded['message'];
|
||||
isLoading = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
|
||||
import 'package:sefer_driver/views/auth/captin/login_captin.dart';
|
||||
import 'package:sefer_driver/views/home/on_boarding_page.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../main.dart';
|
||||
import '../../onbording_page.dart';
|
||||
import '../../print.dart';
|
||||
import '../functions/encrypt_decrypt.dart';
|
||||
import '../functions/package_info.dart';
|
||||
import '../functions/secure_storage.dart';
|
||||
import '../functions/security_checks.dart';
|
||||
|
||||
// Assuming you have a home page to navigate to after successful login.
|
||||
// If not, you might need to adjust the navigation target.
|
||||
// import 'package:sefer_driver/views/home/home_page.dart';
|
||||
|
||||
class SplashScreenController extends GetxController
|
||||
with GetTickerProviderStateMixin {
|
||||
late AnimationController _animationController;
|
||||
late Animation<double> animation;
|
||||
final progress = 0.0.obs;
|
||||
Timer? _progressTimer;
|
||||
|
||||
String packageInfo = '';
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
_setupAnimations();
|
||||
_initializeAndNavigate();
|
||||
checkSecurity();
|
||||
}
|
||||
|
||||
checkSecurity() async {
|
||||
final random = Random();
|
||||
|
||||
if (random.nextBool()) {
|
||||
await SecurityHelper.performSecurityChecks();
|
||||
} else {
|
||||
await SecurityChecks.isDeviceRootedFromNative(Get.context!);
|
||||
}
|
||||
}
|
||||
|
||||
void _setupAnimations() {
|
||||
_animationController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 1500),
|
||||
);
|
||||
animation =
|
||||
CurvedAnimation(parent: _animationController, curve: Curves.easeInOut);
|
||||
_animationController.forward();
|
||||
}
|
||||
|
||||
/// This is the core function that initializes the app.
|
||||
/// It runs two tasks simultaneously and navigates only when necessary.
|
||||
Future<void> _initializeAndNavigate() async {
|
||||
// Start getting package info, no need to wait for it.
|
||||
_getPackageInfo();
|
||||
|
||||
const minSplashDurationMs = 4000;
|
||||
_animateProgressBar(minSplashDurationMs);
|
||||
|
||||
// Define the two concurrent tasks
|
||||
final minDuration =
|
||||
Future.delayed(const Duration(milliseconds: minSplashDurationMs));
|
||||
final navigationTargetFuture = _getNavigationTarget();
|
||||
|
||||
// Wait for both tasks to complete
|
||||
await Future.wait([minDuration, navigationTargetFuture]);
|
||||
|
||||
// The future now returns a nullable Widget (Widget?)
|
||||
final Widget? targetPage = await navigationTargetFuture;
|
||||
|
||||
// *** FIX: Only navigate if the targetPage is not null. ***
|
||||
// This prevents navigating again if the login function already handled it.
|
||||
if (targetPage != null) {
|
||||
Get.off(() => targetPage,
|
||||
transition: Transition.fadeIn,
|
||||
duration: const Duration(milliseconds: 500));
|
||||
} else {
|
||||
Log.print(
|
||||
"Navigation was handled internally by the login process. Splash screen will not navigate.");
|
||||
}
|
||||
}
|
||||
|
||||
/// Animates the progress bar over a given duration.
|
||||
void _animateProgressBar(int totalMilliseconds) {
|
||||
const interval = 50;
|
||||
int elapsed = 0;
|
||||
_progressTimer?.cancel();
|
||||
_progressTimer =
|
||||
Timer.periodic(const Duration(milliseconds: interval), (timer) {
|
||||
elapsed += interval;
|
||||
progress.value = (elapsed / totalMilliseconds).clamp(0.0, 1.0);
|
||||
if (elapsed >= totalMilliseconds) {
|
||||
timer.cancel();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Determines the correct page to navigate to, or returns null if navigation
|
||||
/// is expected to be handled by an internal process (like login).
|
||||
Future<Widget?> _getNavigationTarget() async {
|
||||
try {
|
||||
// 1) Onboarding
|
||||
final doneOnboarding = box.read(BoxName.onBoarding) == 'yes';
|
||||
if (!doneOnboarding) {
|
||||
// الأفضل: رجّع الواجهة بدل Get.off داخل الدالة
|
||||
return OnBoardingPage();
|
||||
}
|
||||
|
||||
// 2) Login
|
||||
final isDriverDataAvailable = box.read(BoxName.phoneDriver) != null;
|
||||
if (!isDriverDataAvailable) {
|
||||
return LoginCaptin();
|
||||
}
|
||||
|
||||
final loginController = Get.put(LoginDriverController());
|
||||
|
||||
final AppInitializer initializer = AppInitializer();
|
||||
await initializer.initializeApp();
|
||||
await EncryptionHelper.initialize();
|
||||
|
||||
await loginController.loginWithGoogleCredential(
|
||||
box.read(BoxName.driverID).toString(),
|
||||
box.read(BoxName.emailDriver).toString(),
|
||||
);
|
||||
|
||||
return null; // لأن loginWithGoogleCredential يوجّه
|
||||
} catch (e) {
|
||||
Log.print("Error during navigation logic: $e");
|
||||
return LoginCaptin();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _getPackageInfo() async {
|
||||
try {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
packageInfo = info.version;
|
||||
await box.write(BoxName.packagInfo, packageInfo);
|
||||
update(); // To update any UI element that might be listening
|
||||
} catch (e) {
|
||||
Log.print("Could not get package info: $e");
|
||||
packageInfo = '1.0.0'; // Default value
|
||||
await box.write(BoxName.packagInfo, packageInfo);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_progressTimer?.cancel();
|
||||
_animationController.dispose();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user