import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:sefer_driver/constant/colors.dart'; import 'package:sefer_driver/constant/style.dart'; import 'package:sefer_driver/controller/home/payment/captain_wallet_controller.dart'; import 'package:sefer_driver/controller/payment/payment_controller.dart'; import 'package:sefer_driver/views/widgets/mydialoug.dart'; import 'package:webview_flutter/webview_flutter.dart'; import '../../../constant/box_name.dart'; import '../../../constant/links.dart'; import '../../../controller/functions/crud.dart'; import '../../../main.dart'; import '../../../print.dart'; import '../../widgets/elevated_btn.dart'; import '../../widgets/my_textField.dart'; class PointsCaptain extends StatelessWidget { PaymentController paymentController = Get.put(PaymentController()); CaptainWalletController captainWalletController = Get.put(CaptainWalletController()); PointsCaptain({ super.key, required this.kolor, required this.countPoint, required this.pricePoint, }); final Color kolor; final String countPoint; double pricePoint; @override Widget build(BuildContext context) { return InkWell( onTap: () async { box.read(BoxName.countryCode) == 'Egypt' ? Get.defaultDialog( title: 'Which method you will pay'.tr, titleStyle: AppStyle.title, content: Column( children: [ Text( '${'you can buy '.tr}$countPoint ${'LE'.tr}${'by '.tr}${'$pricePoint'.tr}', style: AppStyle.title, ), MyElevatedButton( title: 'Pay with Credit Card'.tr, onPressed: () async { Get.back(); var res = await CRUD().postWallet( // link: AppLink.payWithPayMobWalletPasenger, link: AppLink.payWithPayMobCardDriver, payload: { "amount": pricePoint.toStringAsFixed(2), "email": box.read(BoxName.emailDriver), "first_name": (box .read(BoxName.nameDriver) .toString() .split(' ')[0]) .toString(), "last_name": (box .read(BoxName.nameDriver) .toString() .split(' ')[1]) .toString(), "phone_number": (box.read(BoxName.phoneDriver)), }); // var d = jsonDecode(res); Navigator.push( context, MaterialPageRoute( builder: (context) => PaymentScreen( iframeUrl: res['message'], countPrice: countPoint.toString()), ), ); }, //51524 ), // Add some spacing between buttons MyElevatedButton( kolor: AppColor.redColor, title: 'Pay with Wallet'.tr, onPressed: () async { Get.back(); Get.defaultDialog( barrierDismissible: false, title: 'Insert Wallet phone number'.tr, content: Form( key: paymentController.formKey, child: MyTextForm( controller: paymentController.walletphoneController, label: 'Insert Wallet phone number'.tr, hint: 'Insert Wallet phone number'.tr, type: TextInputType.phone)), confirm: MyElevatedButton( title: 'OK'.tr, onPressed: () async { Get.back(); if (paymentController.formKey.currentState! .validate()) { box.write( BoxName.phoneWallet, paymentController .walletphoneController.text); var res = await CRUD().postWallet( // link: AppLink.payWithPayMobWalletPasenger, link: AppLink.payWithWallet, payload: { "amount": pricePoint.toStringAsFixed(2), "email": box.read(BoxName.emailDriver), "first_name": (box .read(BoxName.nameDriver) .toString() .split(' ')[0]) .toString(), "last_name": (box .read(BoxName.nameDriver) .toString() .split(' ')[1]) .toString(), "phone_number": (box.read(BoxName.phoneWallet)), }); Navigator.push( context, MaterialPageRoute( builder: (context) => PaymentScreenWallet( iframeUrl: res['message'], countPrice: countPoint.toString()), ), ); } // MyDialog().getDialog( // 'phone number is wrong'.tr, // '', // () { // Get.back(); // }, // ); // Get.back(); })); }, ), ], )) : await paymentController.makePaymentStripe(pricePoint, box.read(BoxName.countryCode) == 'Jordan' ? 'jod' : 'egp', () async { // await captainWalletController.getPaymentId( // 'visa-in', pricePoint); await captainWalletController.addDriverWallet( 'visa-in', countPoint, pricePoint); await captainWalletController.getCaptainWalletFromBuyPoints(); }); }, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 8), child: Container( width: Get.width * .22, height: Get.width * .22, margin: const EdgeInsets.all(4), decoration: BoxDecoration( gradient: LinearGradient( colors: [ kolor.withOpacity(0.3), kolor, kolor.withOpacity(0.7), kolor, ], begin: Alignment.topLeft, end: Alignment.bottomRight, ), border: Border.all(color: AppColor.accentColor), borderRadius: BorderRadius.circular(12), shape: BoxShape.rectangle, ), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Text( '$countPoint ${box.read(BoxName.countryCode) == 'Jordan' ? 'JOD'.tr : 'L.E'.tr}', style: AppStyle.subtitle .copyWith(color: AppColor.secondaryColor), ), Text( '$pricePoint ${box.read(BoxName.countryCode) == 'Jordan' ? 'JOD'.tr : 'L.E'.tr}', style: AppStyle.title.copyWith(color: AppColor.secondaryColor), textAlign: TextAlign.center, ), ], ), ), ), ), ); } } class PaymentScreen extends StatefulWidget { final String iframeUrl; final String countPrice; const PaymentScreen( {required this.iframeUrl, Key? key, required this.countPrice}) : super(key: key); @override State createState() => _PaymentScreenState(); } class _PaymentScreenState extends State { late final WebViewController _controller; final controller = Get.find(); @override void initState() { super.initState(); _controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setNavigationDelegate(NavigationDelegate( onPageFinished: (url) { if (url.contains("success")) { _fetchPaymentStatus(); // ✅ استدعاء الويب هوك بعد نجاح الدفع } else if (url.contains("failed")) { showCustomDialog( title: "Error".tr, message: 'Payment Failed'.tr, // يتم جلب رسالة الخطأ من الخادم isSuccess: false, ); } }, )) ..loadRequest(Uri.parse(widget.iframeUrl)); } Future _fetchPaymentStatus() async { final String userId = box.read(BoxName.phoneDriver); await Future.delayed(const Duration(seconds: 2)); try { final response = await CRUD().postWallet( link: AppLink.paymetVerifyDriver, payload: { 'user_id': userId, 'driverID': box.read(BoxName.driverID), 'paymentMethod': 'visa-in', }, ); if (response != 'failure' && response != 'token_expired') { if (response['status'] == 'success') { final payment = response['message']; final amount = payment['amount'].toString(); final bonus = payment['bonus'].toString(); final paymentID = payment['paymentID'].toString(); await controller.getCaptainWalletFromBuyPoints(); showCustomDialog( title: "payment_success".tr, message: "${"transaction_id".tr}: $paymentID\n${"amount_paid".tr}: $amount EGP\n${"bonus_added".tr}: $bonus ${"points".tr}", isSuccess: true, ); } else { showCustomDialog( title: "transaction_failed".tr, message: response['message'].toString(), isSuccess: false, ); } } else { showCustomDialog( title: "connection_failed".tr, message: response.toString(), isSuccess: false, ); } } catch (e) { showCustomDialog( title: "server_error".tr, message: "server_error_message".tr, isSuccess: false, ); } } void showCustomDialog({ required String title, required String message, required bool isSuccess, }) { showDialog( barrierDismissible: false, context: Get.context!, builder: (BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12.0), ), title: Row( children: [ Icon( isSuccess ? Icons.check_circle : Icons.error, color: isSuccess ? Colors.green : Colors.red, ), const SizedBox(width: 8), Text( title, style: TextStyle( color: isSuccess ? Colors.green : Colors.red, fontWeight: FontWeight.bold, ), ), ], ), content: Text( message, style: const TextStyle(fontSize: 16), ), actions: [ TextButton( onPressed: () { Navigator.pop(context); Navigator.pop(context); }, style: TextButton.styleFrom( backgroundColor: isSuccess ? Colors.green : Colors.red, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8.0), ), ), child: Text( "OK", style: const TextStyle(color: Colors.white), ), ), ], ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('إتمام الدفع')), body: WebViewWidget(controller: _controller), ); } } class PaymentScreenWallet extends StatefulWidget { final String iframeUrl; final String countPrice; const PaymentScreenWallet( {required this.iframeUrl, Key? key, required this.countPrice}) : super(key: key); @override State createState() => _PaymentScreenWalletState(); } class _PaymentScreenWalletState extends State { late final WebViewController _controller; final controller = Get.find(); @override void initState() { super.initState(); _controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setNavigationDelegate(NavigationDelegate( onPageFinished: (url) { if (url.contains("success")) { _fetchPaymentStatus(); // ✅ استدعاء الويب هوك بعد نجاح الدفع } else if (url.contains("failed")) { showCustomDialog( title: "Error".tr, message: 'Payment Failed'.tr, // يتم جلب رسالة الخطأ من الخادم isSuccess: false, ); } }, )) ..loadRequest(Uri.parse(widget.iframeUrl)); } Future _fetchPaymentStatus() async { final String userId = '+2' + box.read(BoxName.phoneWallet); await Future.delayed(const Duration(seconds: 2)); try { final response = await CRUD().postWallet( link: AppLink.paymetVerifyDriver, payload: { 'user_id': userId, 'driverID': box.read(BoxName.driverID), 'paymentMethod': 'visa-in', }, ); if (response != 'failure' && response != 'token_expired') { if (response['status'] == 'success') { final payment = response['message']; final amount = payment['amount'].toString(); final bonus = payment['bonus'].toString(); final paymentID = payment['paymentID'].toString(); await controller.getCaptainWalletFromBuyPoints(); showCustomDialog( title: "payment_success".tr, message: "${"transaction_id".tr}: $paymentID\n${"amount_paid".tr}: $amount EGP\n${"bonus_added".tr}: $bonus ${"points".tr}", isSuccess: true, ); } else { showCustomDialog( title: "transaction_failed".tr, message: response['message'].toString(), isSuccess: false, ); } } else { showCustomDialog( title: "connection_failed".tr, message: response.toString(), isSuccess: false, ); } } catch (e) { showCustomDialog( title: "server_error".tr, message: "server_error_message".tr, isSuccess: false, ); } } void showCustomDialog({ required String title, required String message, required bool isSuccess, }) { showDialog( barrierDismissible: false, context: Get.context!, builder: (BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12.0), ), title: Row( children: [ Icon( isSuccess ? Icons.check_circle : Icons.error, color: isSuccess ? Colors.green : Colors.red, ), const SizedBox(width: 8), Text( title, style: TextStyle( color: isSuccess ? Colors.green : Colors.red, fontWeight: FontWeight.bold, ), ), ], ), content: Text( message, style: const TextStyle(fontSize: 16), ), actions: [ TextButton( onPressed: () { Navigator.pop(context); Navigator.pop(context); }, style: TextButton.styleFrom( backgroundColor: isSuccess ? Colors.green : Colors.red, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8.0), ), ), child: Text( "OK", style: const TextStyle(color: Colors.white), ), ), ], ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('إتمام الدفع')), body: WebViewWidget(controller: _controller), ); } }