import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; import '../api.dart'; class WithdrawalScreen extends StatefulWidget { final Map order; const WithdrawalScreen({super.key, required this.order}); @override State createState() => _WithdrawalScreenState(); } class _WithdrawalScreenState extends State { File? image; Map? details; bool loading = true; String? token; int seconds = 0; Timer? timer; @override void initState() { super.initState(); print("🟢 initState: بدء تحميل الشاشة"); loadTokenAndFetch(); } @override void dispose() { print("🔴 dispose: إلغاء المؤقت"); timer?.cancel(); super.dispose(); } Future loadTokenAndFetch() async { print("🟡 loadTokenAndFetch: جلب التوكن من SharedPreferences"); final prefs = await SharedPreferences.getInstance(); token = prefs.getString('api_token'); print("TOKEN: $token"); if (token != null) { print("✅ التوكن موجود، سيتم جلب التفاصيل"); await fetchDetails(); } else { print("❌ لا يوجد توكن، إنهاء التحميل"); setState(() { loading = false; }); } } Future fetchDetails() async { print("🟡 fetchDetails: بدء جلب تفاصيل الطلب"); try { final orderId = widget.order['id']; print("📦 orderId: $orderId"); final url = Api.post("withdraw/details.php?order_id=$orderId"); print("🔗 DETAILS URL: $url"); final res = await http.get( Uri.parse(url), headers: {'Authorization': 'Bearer $token'}, ); print("📡 Response status: ${res.statusCode}"); print("📄 Response body: ${res.body}"); final data = jsonDecode(res.body); print("🔍 Parsed data: $data"); if (data['success'] == true) { print("✅ تم جلب التفاصيل بنجاح"); setState(() { details = data['data']; loading = false; }); print("📋 details: $details"); _startTimerFromDeadline(); } else { print("❌ فشل جلب التفاصيل: ${data['message']}"); setState(() { loading = false; }); } } catch (e) { print("🔥 خطأ في جلب التفاصيل: $e"); setState(() { loading = false; }); } } void _startTimerFromDeadline() { print("🟡 _startTimerFromDeadline: بدء تشغيل المؤقت"); if (details == null) { print("⚠️ details == null, لا يمكن بدء المؤقت"); return; } setState(() { seconds = details!['remaining_seconds'] ?? 0; print("⏱️ seconds المستلمة من API: $seconds"); if (seconds < 60) { seconds = 600; // 10 دقائق print("⚠️ seconds أقل من 60 -> تم ضبطه إلى 600 ثانية (10 دقائق)"); } print("⏱️ seconds النهائية: $seconds"); }); startTimer(); } void startTimer() { print("🟡 startTimer: بدء العد التنازلي"); timer?.cancel(); timer = Timer.periodic(const Duration(seconds: 1), (_) { if (seconds <= 0) { print("⏰ Timer: انتهى الوقت"); timer?.cancel(); if (mounted) { print("📢 عرض SnackBar انتهاء الوقت والخروج من الشاشة"); ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('انتهى الوقت المخصص للتحويل')), ); Navigator.pop(context); } } else { setState(() => seconds--); if (seconds % 10 == 0) print("⏳ Timer: $seconds ثانية متبقية"); } }); } String formatTime() { final m = seconds ~/ 60; final s = seconds % 60; return "$m:${s.toString().padLeft(2, '0')}"; } Future pickImage() async { print("🟡 pickImage: فتح المعرض لاختيار صورة"); final picked = await ImagePicker().pickImage( source: ImageSource.gallery, ); if (picked != null) { print("✅ تم اختيار الصورة: ${picked.path}"); setState(() { image = File(picked.path); }); } else { print("❌ لم يتم اختيار أي صورة"); } } // ✅ الدالة المعدلة حسب المطلوب Future confirmProof() async { print("🟡 confirmProof: بدء رفع الإثبات"); if (image == null) { print("⚠️ لا توجد صورة مرفوعة، لن يتم الرفع"); return; } print("📤 إعداد طلب Multipart..."); final request = http.MultipartRequest( 'POST', Uri.parse(Api.post("withdraw/upload-proof.php")), ); request.headers['Authorization'] = 'Bearer $token'; request.fields['order_id'] = widget.order['id'].toString(); print("➕ إضافة order_id: ${widget.order['id']}"); request.files.add( await http.MultipartFile.fromPath('proof', image!.path), ); print("➕ إضافة ملف proof من المسار: ${image!.path}"); print("🚀 إرسال الطلب..."); final res = await request.send(); final body = await res.stream.bytesToString(); print("📡 Response status: ${res.statusCode}"); print("📄 Response body: $body"); final data = jsonDecode(body); print("🔍 Parsed data: $data"); if (data['success'] == true) { print("✅ تم رفع الإثبات بنجاح"); // ✔ رسالة ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text("تم إرسال الإثبات")), ); // ✔ إيقاف المؤقت timer?.cancel(); // ✔ رجوع مباشر إلى OrdersScreen Navigator.pop(context, true); } else { print("❌ فشل رفع الإثبات: ${data['message']}"); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(data['message'])), ); } } @override Widget build(BuildContext context) { print( "🎨 build: إعادة بناء الواجهة (loading=$loading, details=${details != null})"); if (loading) { print("🔄 عرض شاشة التحميل"); return const Scaffold( body: Center(child: CircularProgressIndicator()), ); } if (details == null) { print("⚠️ عرض رسالة خطأ لعدم وجود details"); return Scaffold( body: Center(child: Text('حدث خطأ في تحميل تفاصيل الطلب')), ); } print("✅ عرض المحتوى الأساسي للشاشة"); return Scaffold( appBar: AppBar( title: const Text("Secure Withdrawal"), centerTitle: true, ), body: SingleChildScrollView( padding: const EdgeInsets.all(16), child: Column( children: [ box("ربحك من العملية", "${(details!['profit'] as num).toStringAsFixed(0)} IQD"), box("المبلغ", "${details!['amount'] ?? widget.order['amount']} IQD"), box("وسيلة الدفع", details!['method'] ?? "-"), box("رقم الحساب", details!['account_number'] ?? "-"), const SizedBox(height: 20), box( "الوقت المتبقي لإنهاء العملية", formatTime(), color: Colors.orange, ), const SizedBox(height: 10), ElevatedButton( onPressed: () { print("➕ ضغط على زر 'امنحني وقتاً إضافياً'"); setState(() { seconds += 60; print("⏱️ تم إضافة 60 ثانية، seconds الآن = $seconds"); }); if (timer == null || !timer!.isActive) { print("🔄 المؤقت غير نشط، إعادة تشغيله"); startTimer(); } }, child: const Text("امنحني وقتاً إضافياً"), ), const SizedBox(height: 20), GestureDetector( onTap: pickImage, child: Container( height: 150, decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(16), ), child: Center( child: image == null ? const Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.add, size: 40), SizedBox(height: 10), Text("اختر صورة إثبات التحويل"), ], ) : Image.file(image!, fit: BoxFit.cover), ), ), ), const SizedBox(height: 15), // ✅ إظهار زر التأكيد فقط عند اختيار صورة (بدون التحقق من status) if (image != null) ElevatedButton( onPressed: confirmProof, child: const Text("تأكيد إرسال الإثبات"), ), ], ), ), ); } Widget box(String title, String value, {Color? color}) { return Container( width: double.infinity, margin: const EdgeInsets.only(bottom: 12), padding: const EdgeInsets.all(16), decoration: BoxDecoration( color: Theme.of(context).brightness == Brightness.dark ? Colors.grey.shade900 : Colors.grey.shade200, borderRadius: BorderRadius.circular(16), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(title, style: TextStyle(color: Colors.grey.shade600)), const SizedBox(height: 5), Text( value, style: TextStyle( fontSize: 18, color: color ?? Theme.of(context).textTheme.bodyLarge?.color, fontWeight: FontWeight.bold, ), ), ], ), ); } }