Initial commit: Uruk Prize Platform architecture, backend core, mobile app, gateway caller & deployment pipeline

This commit is contained in:
Hamza-Ayed
2026-09-18 17:12:05 +03:00
commit 879dd36f1b
1149 changed files with 97122 additions and 0 deletions
@@ -0,0 +1,15 @@
class AppConstants {
static const String appName = 'جائزة أوروك الدولية';
static const String appTagline = 'الهوية الرقمية الموحدة للرعاية الصحية والتعليم';
// Base API URL (can be customized for production server)
static const String defaultBaseUrl = 'https://api.urukprize.iq';
// Storage Keys
static const String keyToken = 'uruk_session_token';
static const String keyUserId = 'uruk_user_id';
static const String keyDeviceSecret = 'uruk_device_secret';
static const String keyFingerprint = 'uruk_device_fingerprint';
static const String keySalt = 'uruk_device_salt';
static const String keyUserData = 'uruk_user_data';
}
+117
View File
@@ -0,0 +1,117 @@
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as http;
import 'package:uuid/uuid.dart';
import '../constants/app_constants.dart';
import '../security/fingerprint_service.dart';
class ApiClient {
final String baseUrl;
final http.Client _httpClient;
final FingerprintService _fingerprintService;
ApiClient({
String? baseUrl,
http.Client? httpClient,
FingerprintService? fingerprintService,
}) : baseUrl = baseUrl ?? AppConstants.defaultBaseUrl,
_httpClient = httpClient ?? http.Client(),
_fingerprintService = fingerprintService ?? FingerprintService();
/// Executes an HTTP request with automatic header, device fingerprint, and HMAC signature injection.
Future<Map<String, dynamic>> sendRequest({
required String method,
required String path,
Map<String, dynamic>? body,
Map<String, String>? queryParams,
bool requiresAuth = true,
}) async {
Uri uri = Uri.parse('$baseUrl$path');
if (queryParams != null && queryParams.isNotEmpty) {
uri = uri.replace(queryParameters: queryParams);
}
final headers = <String, String>{
'Content-Type': 'application/json',
'Accept': 'application/json',
};
final rawBody = body != null ? jsonEncode(body) : '';
if (requiresAuth) {
final userId = await _fingerprintService.getUserId();
final token = await _fingerprintService.getSessionToken();
final deviceSecret = await _fingerprintService.getDeviceSecret();
final fingerprint = await _fingerprintService.getDeviceFingerprint();
final timestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();
final nonce = const Uuid().v4();
if (userId != null) {
headers['X-User-Id'] = userId.toString();
}
headers['X-Device-Fingerprint'] = fingerprint;
headers['X-Timestamp'] = timestamp;
headers['X-Nonce'] = nonce;
if (token != null) {
headers['Authorization'] = 'Bearer $token';
}
// Calculate HMAC-SHA256 signature
if (deviceSecret != null) {
final bodyHash = sha256.convert(utf8.encode(rawBody)).toString();
final signaturePayload = '$method\n$path\n$timestamp\n$nonce\n$bodyHash';
final hmacSha256 = Hmac(sha256, utf8.encode(deviceSecret));
final signature = hmacSha256.convert(utf8.encode(signaturePayload)).toString();
headers['X-Signature'] = signature;
}
}
http.Response response;
switch (method.toUpperCase()) {
case 'GET':
response = await _httpClient.get(uri, headers: headers);
break;
case 'POST':
response = await _httpClient.post(uri, headers: headers, body: rawBody.isNotEmpty ? rawBody : null);
break;
case 'PUT':
response = await _httpClient.put(uri, headers: headers, body: rawBody.isNotEmpty ? rawBody : null);
break;
case 'DELETE':
response = await _httpClient.delete(uri, headers: headers, body: rawBody.isNotEmpty ? rawBody : null);
break;
default:
throw UnsupportedError('HTTP method $method not supported');
}
final decoded = jsonDecode(utf8.decode(response.bodyBytes)) as Map<String, dynamic>;
if (response.statusCode >= 200 && response.statusCode < 300) {
return decoded;
} else {
final msg = decoded['message'] ?? 'Request failed with status ${response.statusCode}';
throw ApiException(msg, response.statusCode);
}
}
Future<Map<String, dynamic>> get(String path, {Map<String, String>? queryParams, bool requiresAuth = true}) {
return sendRequest(method: 'GET', path: path, queryParams: queryParams, requiresAuth: requiresAuth);
}
Future<Map<String, dynamic>> post(String path, {Map<String, dynamic>? body, bool requiresAuth = true}) {
return sendRequest(method: 'POST', path: path, body: body, requiresAuth: requiresAuth);
}
}
class ApiException implements Exception {
final String message;
final int statusCode;
ApiException(this.message, this.statusCode);
@override
String toString() => 'ApiException [$statusCode]: $message';
}
@@ -0,0 +1,132 @@
import 'dart:convert';
import 'dart:io';
import 'package:crypto/crypto.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:uuid/uuid.dart';
import '../constants/app_constants.dart';
class FingerprintService {
final FlutterSecureStorage _storage;
final DeviceInfoPlugin _deviceInfo;
static const MethodChannel _nativeChannel = MethodChannel('iq.urukprize.uruk_prize/device_fingerprint');
FingerprintService({
FlutterSecureStorage? storage,
DeviceInfoPlugin? deviceInfo,
}) : _storage = storage ?? const FlutterSecureStorage(),
_deviceInfo = deviceInfo ?? DeviceInfoPlugin();
String? _cachedFingerprint;
/// Retrieves or generates a tamper-proof hardware-bound device fingerprint.
/// Prioritizes Native MethodChannel (Kotlin on Android / Swift on iOS with Keychain persistence).
Future<String> getDeviceFingerprint() async {
if (_cachedFingerprint != null) {
return _cachedFingerprint!;
}
// 1. Check if previously generated and stored securely
String? storedFp = await _storage.read(key: AppConstants.keyFingerprint);
if (storedFp != null && storedFp.length == 64) {
_cachedFingerprint = storedFp;
return storedFp;
}
// 2. Fetch or create persistent random cryptographic salt
String? salt = await _storage.read(key: AppConstants.keySalt);
if (salt == null) {
salt = const Uuid().v4() + DateTime.now().microsecondsSinceEpoch.toString();
await _storage.write(key: AppConstants.keySalt, value: salt);
}
// 3. Extract hardware parameters via Native MethodChannel first
String hardwareData = '';
try {
final String? nativeRaw = await _nativeChannel.invokeMethod<String>('getHardwareRawData');
if (nativeRaw != null && nativeRaw.isNotEmpty) {
hardwareData = nativeRaw;
}
} catch (_) {
// MethodChannel fallback to device_info_plus
}
if (hardwareData.isEmpty) {
try {
if (Platform.isAndroid) {
final androidInfo = await _deviceInfo.androidInfo;
hardwareData = '${androidInfo.brand}-${androidInfo.model}-${androidInfo.id}-${androidInfo.hardware}-${androidInfo.manufacturer}';
} else if (Platform.isIOS) {
final iosInfo = await _deviceInfo.iosInfo;
hardwareData = '${iosInfo.name}-${iosInfo.model}-${iosInfo.systemName}-${iosInfo.identifierForVendor}';
} else {
hardwareData = 'generic-client-uruk';
}
} catch (_) {
hardwareData = 'fallback-hardware-id';
}
}
// 4. Generate SHA-256 Digest
final combinedBytes = utf8.encode('$hardwareData::$salt::uruk_prize_secure');
final digest = sha256.convert(combinedBytes);
final fingerprint = digest.toString();
// 5. Store permanently
await _storage.write(key: AppConstants.keyFingerprint, value: fingerprint);
_cachedFingerprint = fingerprint;
return fingerprint;
}
Future<String> getDeviceModel() async {
try {
final String? nativeModel = await _nativeChannel.invokeMethod<String>('getDeviceModel');
if (nativeModel != null && nativeModel.isNotEmpty) {
return nativeModel;
}
} catch (_) {}
try {
if (Platform.isAndroid) {
final info = await _deviceInfo.androidInfo;
return '${info.manufacturer} ${info.model}';
} else if (Platform.isIOS) {
final info = await _deviceInfo.iosInfo;
return info.utsname.machine;
}
} catch (_) {}
return 'Unknown Device';
}
Future<void> saveAuthSession({
required int userId,
required String token,
required String deviceSecret,
}) async {
await _storage.write(key: AppConstants.keyUserId, value: userId.toString());
await _storage.write(key: AppConstants.keyToken, value: token);
await _storage.write(key: AppConstants.keyDeviceSecret, value: deviceSecret);
}
Future<int?> getUserId() async {
final val = await _storage.read(key: AppConstants.keyUserId);
return val != null ? int.tryParse(val) : null;
}
Future<String?> getSessionToken() async {
return await _storage.read(key: AppConstants.keyToken);
}
Future<String?> getDeviceSecret() async {
return await _storage.read(key: AppConstants.keyDeviceSecret);
}
Future<void> clearSession() async {
await _storage.delete(key: AppConstants.keyUserId);
await _storage.delete(key: AppConstants.keyToken);
await _storage.delete(key: AppConstants.keyDeviceSecret);
await _storage.delete(key: AppConstants.keyUserData);
}
}
+53
View File
@@ -0,0 +1,53 @@
import 'package:flutter/material.dart';
class AppTheme {
// Primary Palette
static const Color primaryDark = Color(0xFF0F172A); // Midnight Navy
static const Color cardDark = Color(0xFF1E293B); // Slate Navy
static const Color goldAccent = Color(0xFFD4AF37); // Uruk Metallic Gold
static const Color goldLight = Color(0xFFF3E5AB); // Pale Gold
static const Color emeraldGreen = Color(0xFF10B981);// Active Green
static const Color crimsonRed = Color(0xFFEF4444); // Expired / Warning Red
static const Color textMuted = Color(0xFF94A3B8); // Muted Slate Text
static ThemeData get darkTheme {
return ThemeData(
useMaterial3: true,
brightness: Brightness.dark,
scaffoldBackgroundColor: primaryDark,
primaryColor: goldAccent,
cardColor: cardDark,
appBarTheme: const AppBarTheme(
backgroundColor: primaryDark,
elevation: 0,
centerTitle: true,
titleTextStyle: TextStyle(
color: goldLight,
fontSize: 18,
fontWeight: FontWeight.bold,
letterSpacing: 0.5,
),
),
colorScheme: const ColorScheme.dark(
primary: goldAccent,
secondary: goldLight,
surface: cardDark,
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: goldAccent,
foregroundColor: primaryDark,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
textStyle: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
);
}
}
@@ -0,0 +1,283 @@
import 'package:flutter/material.dart';
import '../../../core/network/api_client.dart';
import '../../../core/theme/app_theme.dart';
class InAppAdminModal {
static void show(BuildContext context) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (modalCtx) => const _AdminSheetContent(),
);
}
}
class _AdminSheetContent extends StatefulWidget {
const _AdminSheetContent();
@override
State<_AdminSheetContent> createState() => _AdminSheetContentState();
}
class _AdminSheetContentState extends State<_AdminSheetContent> with SingleTickerProviderStateMixin {
late TabController _tabController;
final _client = ApiClient();
// Add Partner Form Controllers
final _nameController = TextEditingController();
final _cityController = TextEditingController(text: 'بغداد');
final _countryController = TextEditingController(text: 'العراق');
final _discountController = TextEditingController(text: '50');
final _phoneController = TextEditingController();
final _addressController = TextEditingController();
String _partnerType = 'HOSPITAL';
bool _isAdding = false;
@override
void initState() {
super.initState();
_tabController = TabController(length: 2, vsync: this);
}
@override
void dispose() {
_tabController.dispose();
_nameController.dispose();
_cityController.dispose();
_countryController.dispose();
_discountController.dispose();
_phoneController.dispose();
_addressController.dispose();
super.dispose();
}
Future<void> _submitNewPartner() async {
final name = _nameController.text.trim();
if (name.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('يرجى كتابة اسم المستشفى أو الفندق.')));
return;
}
setState(() => _isAdding = true);
try {
await _client.post('/api/v1/admin/partners/add', body: {
'name_ar': name,
'type': _partnerType,
'city': _cityController.text.trim(),
'country': _countryController.text.trim(),
'discount_percentage': double.tryParse(_discountController.text.trim()) ?? 50.0,
'phone': _phoneController.text.trim(),
'address': _addressController.text.trim(),
});
if (mounted) {
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('تمت إضافة الشريك بنجاح ومتاح فورياً لجميع المشتركين!'),
backgroundColor: AppTheme.emeraldGreen,
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('حدث خطأ: $e'), backgroundColor: AppTheme.crimsonRed));
}
} finally {
if (mounted) setState(() => _isAdding = false);
}
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Container(
height: MediaQuery.of(context).size.height * 0.85,
padding: const EdgeInsets.all(20),
decoration: const BoxDecoration(
color: AppTheme.primaryDark,
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
),
child: Column(
children: [
Container(width: 40, height: 4, decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2))),
const SizedBox(height: 16),
const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.admin_panel_settings, color: AppTheme.goldAccent, size: 24),
SizedBox(width: 8),
Text(
'لوحة إدارة جائزة أوروك (خاص بالإدارة)',
style: TextStyle(color: AppTheme.goldLight, fontSize: 17, fontWeight: FontWeight.bold),
),
],
),
const SizedBox(height: 14),
TabBar(
controller: _tabController,
indicatorColor: AppTheme.goldAccent,
labelColor: AppTheme.goldLight,
unselectedLabelColor: AppTheme.textMuted,
tabs: const [
Tab(text: 'إضافة مستشفى / فندق'),
Tab(text: 'الحوالات المعلقة'),
],
),
const SizedBox(height: 14),
Expanded(
child: TabBarView(
controller: _tabController,
children: [
// Tab 1: Add Partner Form
_buildAddPartnerTab(),
// Tab 2: Pending Payments
_buildPendingPaymentsTab(),
],
),
),
],
),
),
);
}
Widget _buildAddPartnerTab() {
return SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: RadioListTile<String>(
title: const Text('مستشفى (50%)', style: TextStyle(color: Colors.white, fontSize: 13)),
value: 'HOSPITAL',
groupValue: _partnerType,
activeColor: AppTheme.goldAccent,
onChanged: (v) => setState(() {
_partnerType = v!;
_discountController.text = '50';
}),
),
),
Expanded(
child: RadioListTile<String>(
title: const Text('فندق (سياحي)', style: TextStyle(color: Colors.white, fontSize: 13)),
value: 'HOTEL',
groupValue: _partnerType,
activeColor: AppTheme.goldAccent,
onChanged: (v) => setState(() {
_partnerType = v!;
_discountController.text = '45';
}),
),
),
],
),
const SizedBox(height: 8),
_buildTextField(_nameController, 'اسم الشريك (مثال: مستشفى الشرق الأوسط / فندق بابل)', Icons.business),
const SizedBox(height: 12),
Row(
children: [
Expanded(child: _buildTextField(_cityController, 'المدينة (بغداد، أربيل، عمان..)', Icons.location_city)),
const SizedBox(width: 8),
Expanded(child: _buildTextField(_countryController, 'الدولة', Icons.public)),
],
),
const SizedBox(height: 12),
Row(
children: [
Expanded(child: _buildTextField(_discountController, 'نسبة الخصم %', Icons.percent, isNumber: true)),
const SizedBox(width: 8),
Expanded(child: _buildTextField(_phoneController, 'رقم الهاتف', Icons.phone)),
],
),
const SizedBox(height: 12),
_buildTextField(_addressController, 'العنوان التفصيلي', Icons.map),
const SizedBox(height: 20),
SizedBox(
height: 50,
child: ElevatedButton(
onPressed: _isAdding ? null : _submitNewPartner,
child: _isAdding
? const CircularProgressIndicator(color: AppTheme.primaryDark)
: const Text('حفظ ونشر الشريك فورياً لجميع المشتركين'),
),
),
],
),
);
}
Widget _buildPendingPaymentsTab() {
return FutureBuilder<Map<String, dynamic>>(
future: _client.get('/api/v1/admin/payments/pending'),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator(color: AppTheme.goldAccent));
}
if (snapshot.hasError) {
return Center(child: Text('خطأ: ${snapshot.error}', style: const TextStyle(color: AppTheme.textMuted)));
}
final list = (snapshot.data?['data'] as List<dynamic>?) ?? [];
if (list.isEmpty) {
return const Center(
child: Text('لا توجد حوالات معلقة حالياً.', style: TextStyle(color: AppTheme.textMuted)),
);
}
return ListView.builder(
itemCount: list.length,
itemBuilder: (ctx, i) {
final item = list[i] as Map<String, dynamic>;
return Card(
color: AppTheme.cardDark,
margin: const EdgeInsets.only(bottom: 10),
child: ListTile(
title: Text(item['full_name'] ?? 'مشترك جديد', style: const TextStyle(color: Colors.white)),
subtitle: Text(
'${item['method']} • رقم الحركة: ${item['reference_number']}',
style: const TextStyle(color: AppTheme.textMuted, fontSize: 12),
),
trailing: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: AppTheme.emeraldGreen,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
),
onPressed: () async {
await _client.post('/api/v1/admin/payments/approve', body: {'transaction_id': item['id']});
setState(() {});
},
child: const Text('تفعيل', style: TextStyle(fontSize: 12)),
),
),
);
},
);
},
);
}
Widget _buildTextField(TextEditingController controller, String label, IconData icon, {bool isNumber = false}) {
return TextField(
controller: controller,
keyboardType: isNumber ? TextInputType.number : TextInputType.text,
style: const TextStyle(color: Colors.white, fontSize: 14),
decoration: InputDecoration(
labelText: label,
labelStyle: const TextStyle(color: AppTheme.textMuted, fontSize: 13),
prefixIcon: Icon(icon, color: AppTheme.goldAccent, size: 20),
filled: true,
fillColor: AppTheme.cardDark,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none),
contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
),
);
}
}
@@ -0,0 +1,104 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/network/api_client.dart';
import '../../../core/security/fingerprint_service.dart';
import 'auth_state.dart';
class AuthCubit extends Cubit<AuthState> {
final ApiClient _apiClient;
final FingerprintService _fingerprintService;
AuthCubit({
ApiClient? apiClient,
FingerprintService? fingerprintService,
}) : _apiClient = apiClient ?? ApiClient(),
_fingerprintService = fingerprintService ?? FingerprintService(),
super(AuthInitial());
Future<void> checkExistingSession() async {
try {
final token = await _fingerprintService.getSessionToken();
final userId = await _fingerprintService.getUserId();
final fingerprint = await _fingerprintService.getDeviceFingerprint();
if (token != null && userId != null) {
emit(Authenticated(
user: {'id': userId, 'full_name': 'عضو أوروك'},
token: token,
deviceFingerprint: fingerprint,
));
} else {
emit(Unauthenticated());
}
} catch (_) {
emit(Unauthenticated());
}
}
Future<void> requestOtp(String phone) async {
emit(AuthLoading());
try {
final response = await _apiClient.post(
'/api/v1/auth/request-otp',
body: {'phone': phone},
requiresAuth: false,
);
final data = response['data'] as Map<String, dynamic>?;
emit(AuthOtpSent(
phone: phone,
mockOtp: data?['mock_otp'] as String?,
));
} catch (e) {
emit(AuthFailure(e.toString()));
}
}
Future<void> verifyOtpAndBindDevice({
required String phone,
required String otp,
String? fullName,
}) async {
emit(AuthLoading());
try {
final fingerprint = await _fingerprintService.getDeviceFingerprint();
final model = await _fingerprintService.getDeviceModel();
final response = await _apiClient.post(
'/api/v1/auth/verify-otp',
body: {
'phone': phone,
'otp': otp,
'device_fingerprint': fingerprint,
'device_model': model,
if (fullName != null && fullName.isNotEmpty) 'full_name': fullName,
},
requiresAuth: false,
);
final data = response['data'] as Map<String, dynamic>;
final user = data['user'] as Map<String, dynamic>;
final token = data['token'] as String;
final secret = data['device_secret'] as String;
final userId = user['id'] as int;
await _fingerprintService.saveAuthSession(
userId: userId,
token: token,
deviceSecret: secret,
);
emit(Authenticated(
user: user,
token: token,
deviceFingerprint: fingerprint,
));
} catch (e) {
emit(AuthFailure(e.toString()));
}
}
Future<void> logout() async {
await _fingerprintService.clearSession();
emit(Unauthenticated());
}
}
@@ -0,0 +1,48 @@
import 'package:equatable/equatable.dart';
abstract class AuthState extends Equatable {
const AuthState();
@override
List<Object?> get props => [];
}
class AuthInitial extends AuthState {}
class AuthLoading extends AuthState {}
class AuthOtpSent extends AuthState {
final String phone;
final String? mockOtp;
const AuthOtpSent({required this.phone, this.mockOtp});
@override
List<Object?> get props => [phone, mockOtp];
}
class Authenticated extends AuthState {
final Map<String, dynamic> user;
final String token;
final String deviceFingerprint;
const Authenticated({
required this.user,
required this.token,
required this.deviceFingerprint,
});
@override
List<Object?> get props => [user, token, deviceFingerprint];
}
class Unauthenticated extends AuthState {}
class AuthFailure extends AuthState {
final String errorMessage;
const AuthFailure(this.errorMessage);
@override
List<Object?> get props => [errorMessage];
}
@@ -0,0 +1,252 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/theme/app_theme.dart';
import '../cubit/auth_cubit.dart';
import '../cubit/auth_state.dart';
class PhoneAuthScreen extends StatefulWidget {
const PhoneAuthScreen({super.key});
@override
State<PhoneAuthScreen> createState() => _PhoneAuthScreenState();
}
class _PhoneAuthScreenState extends State<PhoneAuthScreen> {
final _phoneController = TextEditingController();
final _otpController = TextEditingController();
final _nameController = TextEditingController();
bool _isOtpStage = false;
@override
void dispose() {
_phoneController.dispose();
_otpController.dispose();
_nameController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xFF0B1120), Color(0xFF020617)],
),
),
child: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 28),
child: BlocConsumer<AuthCubit, AuthState>(
listener: (context, state) {
if (state is AuthOtpSent) {
setState(() {
_isOtpStage = true;
if (state.mockOtp != null) {
_otpController.text = state.mockOtp!;
}
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('تم إرسال رمز التحقق عبر واتساب / الرسائل القصيرة.'),
backgroundColor: AppTheme.emeraldGreen,
),
);
} else if (state is AuthFailure) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.errorMessage),
backgroundColor: AppTheme.crimsonRed,
),
);
}
},
builder: (context, state) {
final isLoading = state is AuthLoading;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// Uruk Prize Emblem / Emblem Placeholder
Container(
width: 90,
height: 90,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: AppTheme.goldAccent, width: 2),
boxShadow: [
BoxShadow(
color: AppTheme.goldAccent.withOpacity(0.25),
blurRadius: 20,
spreadRadius: 3,
),
],
),
child: const Center(
child: Icon(
Icons.workspace_premium,
color: AppTheme.goldAccent,
size: 46,
),
),
),
const SizedBox(height: 20),
const Text(
'جائزة أوروك الدولية',
style: TextStyle(
color: AppTheme.goldLight,
fontSize: 26,
fontWeight: FontWeight.bold,
letterSpacing: 0.5,
),
),
const SizedBox(height: 6),
const Text(
'الهوية الرقمية الموحدة للمزايا الصحية والتدريبية',
style: TextStyle(
color: AppTheme.textMuted,
fontSize: 14,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 36),
if (!_isOtpStage) ...[
// Full Name
TextField(
controller: _nameController,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: 'الاسم الكامل',
labelStyle: const TextStyle(color: AppTheme.textMuted),
prefixIcon: const Icon(Icons.person, color: AppTheme.goldAccent),
filled: true,
fillColor: AppTheme.cardDark,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none,
),
),
),
const SizedBox(height: 16),
// Phone Number
TextField(
controller: _phoneController,
keyboardType: TextInputType.phone,
textDirection: TextDirection.ltr,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: 'رقم الهاتف (مع الرمز الدولي)',
labelStyle: const TextStyle(color: AppTheme.textMuted),
hintText: '+964 770 000 0000',
hintStyle: const TextStyle(color: Colors.white24),
prefixIcon: const Icon(Icons.phone_android, color: AppTheme.goldAccent),
filled: true,
fillColor: AppTheme.cardDark,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none,
),
),
),
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
height: 52,
child: ElevatedButton(
onPressed: isLoading
? null
: () {
final phone = _phoneController.text.trim();
if (phone.isNotEmpty) {
context.read<AuthCubit>().requestOtp(phone);
}
},
child: isLoading
? const CircularProgressIndicator(color: AppTheme.primaryDark)
: const Text('إرسال رمز التحقق'),
),
),
] else ...[
// OTP Input
TextField(
controller: _otpController,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
maxLength: 6,
style: const TextStyle(
color: AppTheme.goldLight,
fontSize: 24,
letterSpacing: 10,
fontWeight: FontWeight.bold,
),
decoration: InputDecoration(
labelText: 'رمز التحقق السري (OTP)',
labelStyle: const TextStyle(color: AppTheme.textMuted),
counterText: '',
filled: true,
fillColor: AppTheme.cardDark,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none,
),
),
),
const SizedBox(height: 12),
Text(
'تم الإرسال إلى ${_phoneController.text}',
style: const TextStyle(color: AppTheme.textMuted, fontSize: 13),
),
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
height: 52,
child: ElevatedButton(
onPressed: isLoading
? null
: () {
final otp = _otpController.text.trim();
if (otp.length == 6) {
context.read<AuthCubit>().verifyOtpAndBindDevice(
phone: _phoneController.text.trim(),
otp: otp,
fullName: _nameController.text.trim(),
);
}
},
child: isLoading
? const CircularProgressIndicator(color: AppTheme.primaryDark)
: const Text('تأكيد الدخول وربط الجهاز'),
),
),
const SizedBox(height: 14),
TextButton(
onPressed: () => setState(() => _isOtpStage = false),
child: const Text(
'تعديل رقم الهاتف',
style: TextStyle(color: AppTheme.goldAccent),
),
),
],
],
);
},
),
),
),
),
),
),
);
}
}
@@ -0,0 +1,45 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/network/api_client.dart';
import 'membership_state.dart';
class MembershipCubit extends Cubit<MembershipState> {
final ApiClient _apiClient;
MembershipCubit({ApiClient? apiClient})
: _apiClient = apiClient ?? ApiClient(),
super(MembershipInitial());
Future<void> fetchCardDetails() async {
emit(MembershipLoading());
try {
final res = await _apiClient.get('/api/v1/subscription/my-card');
final data = res['data'] as Map<String, dynamic>;
emit(MembershipLoaded(cardData: data));
} on ApiException catch (e) {
if (e.statusCode == 404) {
emit(MembershipNotSubscribed());
} else {
emit(MembershipFailure(e.message));
}
} catch (e) {
emit(MembershipFailure(e.toString()));
}
}
Future<void> refreshDynamicQr() async {
if (state is! MembershipLoaded) return;
final current = state as MembershipLoaded;
try {
final res = await _apiClient.get('/api/v1/qr/dynamic-token');
final data = res['data'] as Map<String, dynamic>;
emit(current.copyWith(
dynamicQrToken: data['token'] as String?,
qrValidUntil: data['valid_until'] as int?,
));
} catch (e) {
emit(MembershipFailure('تعذر تحديث كود التحقق: $e'));
}
}
}
@@ -0,0 +1,52 @@
import 'package:equatable/equatable.dart';
abstract class MembershipState extends Equatable {
const MembershipState();
@override
List<Object?> get props => [];
}
class MembershipInitial extends MembershipState {}
class MembershipLoading extends MembershipState {}
class MembershipLoaded extends MembershipState {
final Map<String, dynamic> cardData;
final String? dynamicQrToken;
final int? qrValidUntil;
const MembershipLoaded({
required this.cardData,
this.dynamicQrToken,
this.qrValidUntil,
});
bool get isActive => cardData['status'] == 'ACTIVE';
MembershipLoaded copyWith({
Map<String, dynamic>? cardData,
String? dynamicQrToken,
int? qrValidUntil,
}) {
return MembershipLoaded(
cardData: cardData ?? this.cardData,
dynamicQrToken: dynamicQrToken ?? this.dynamicQrToken,
qrValidUntil: qrValidUntil ?? this.qrValidUntil,
);
}
@override
List<Object?> get props => [cardData, dynamicQrToken, qrValidUntil];
}
class MembershipNotSubscribed extends MembershipState {}
class MembershipFailure extends MembershipState {
final String message;
const MembershipFailure(this.message);
@override
List<Object?> get props => [message];
}
@@ -0,0 +1,431 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../../../core/theme/app_theme.dart';
import '../../admin/presentation/in_app_admin_modal.dart';
import '../../subscription/presentation/subscription_checkout_screen.dart';
import '../cubit/membership_cubit.dart';
import '../cubit/membership_state.dart';
class DigitalCardScreen extends StatefulWidget {
const DigitalCardScreen({super.key});
@override
State<DigitalCardScreen> createState() => _DigitalCardScreenState();
}
class _DigitalCardScreenState extends State<DigitalCardScreen> {
@override
void initState() {
super.initState();
context.read<MembershipCubit>().fetchCardDetails();
}
void _showDynamicQrModal(BuildContext context, String token, int? validUntil) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (modalCtx) => _DynamicQrSheet(
token: token,
validUntil: validUntil,
onRefresh: () => context.read<MembershipCubit>().refreshDynamicQr(),
),
);
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
appBar: AppBar(
title: const Text('بطاقة العضوية الذكية'),
actions: [
IconButton(
icon: const Icon(Icons.refresh, color: AppTheme.goldAccent),
onPressed: () => context.read<MembershipCubit>().fetchCardDetails(),
),
],
),
body: BlocBuilder<MembershipCubit, MembershipState>(
builder: (context, state) {
if (state is MembershipLoading) {
return const Center(child: CircularProgressIndicator(color: AppTheme.goldAccent));
}
if (state is MembershipNotSubscribed) {
return _buildNotSubscribedView(context);
}
if (state is MembershipLoaded) {
final card = state.cardData;
final isActive = state.isActive;
return SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Digital Executive Card Widget
_buildExecutiveCard(context, card, isActive),
const SizedBox(height: 24),
// Actions
if (isActive)
ElevatedButton.icon(
icon: const Icon(Icons.qr_code_2, size: 28),
label: const Text('إبراز رمز التحقق في المستشفى / الفندق'),
style: ElevatedButton.styleFrom(
backgroundColor: AppTheme.goldAccent,
foregroundColor: AppTheme.primaryDark,
padding: const EdgeInsets.symmetric(vertical: 16),
),
onPressed: () async {
final cubit = context.read<MembershipCubit>();
await cubit.refreshDynamicQr();
if (!mounted) return;
final updated = cubit.state;
if (updated is MembershipLoaded && updated.dynamicQrToken != null) {
_showDynamicQrModal(context, updated.dynamicQrToken!, updated.qrValidUntil);
}
},
)
else
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.amber.withOpacity(0.12),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.amber.withOpacity(0.4)),
),
child: const Row(
children: [
Icon(Icons.info_outline, color: Colors.amber),
SizedBox(width: 12),
Expanded(
child: Text(
'طلب العضوية قيد التحقق المالي. سيتم تفعيل البطاقة ورمز QR فور التأكد من الحوالة.',
style: TextStyle(color: Colors.white70, fontSize: 13),
),
),
],
),
),
const SizedBox(height: 24),
// Benefits Summary List
_buildBenefitsSection(),
],
),
);
}
return Center(
child: ElevatedButton(
onPressed: () => context.read<MembershipCubit>().fetchCardDetails(),
child: const Text('إعادة المحاولة'),
),
);
},
),
),
);
}
Widget _buildExecutiveCard(BuildContext context, Map<String, dynamic> card, bool isActive) {
return GestureDetector(
// Secret Long-Press (5 seconds) to trigger Hidden Admin Modal for Dr. Thamer!
onLongPress: () {
InAppAdminModal.show(context);
},
child: Container(
height: 220,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
gradient: const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFF1E293B), Color(0xFF0F172A), Color(0xFF020617)],
),
border: Border.all(color: AppTheme.goldAccent.withOpacity(0.6), width: 1.5),
boxShadow: [
BoxShadow(
color: AppTheme.goldAccent.withOpacity(0.15),
blurRadius: 25,
spreadRadius: 2,
offset: const Offset(0, 10),
),
],
),
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Row(
children: [
Icon(Icons.workspace_premium, color: AppTheme.goldAccent, size: 30),
SizedBox(width: 8),
Text(
'جائزة أوروك الدولية',
style: TextStyle(
color: AppTheme.goldLight,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
],
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: isActive ? AppTheme.emeraldGreen.withOpacity(0.2) : Colors.amber.withOpacity(0.2),
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: isActive ? AppTheme.emeraldGreen : Colors.amber,
width: 1,
),
),
child: Text(
isActive ? 'عضوية معتمدة' : 'قيد التدقيق',
style: TextStyle(
color: isActive ? AppTheme.emeraldGreen : Colors.amber,
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
card['full_name'] ?? 'عضو جائزة أوروك',
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
letterSpacing: 0.5,
),
),
const SizedBox(height: 6),
Text(
card['membership_number'] ?? 'URUK-2026-PENDING',
style: const TextStyle(
color: AppTheme.goldLight,
fontSize: 14,
letterSpacing: 2,
fontFamily: 'Courier',
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'صالحة لغاية: ${card['expires_at'] ?? '2028-01-01'}',
style: const TextStyle(color: AppTheme.textMuted, fontSize: 12),
),
const Text(
'خصم 50% صحي | 30 دورة',
style: TextStyle(color: AppTheme.goldAccent, fontSize: 11, fontWeight: FontWeight.w600),
),
],
),
],
),
),
);
}
Widget _buildNotSubscribedView(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.card_membership, color: AppTheme.goldAccent, size: 70),
const SizedBox(height: 16),
const Text(
'لا توجد عضوية نشطة حالياً',
style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
const Text(
'اشترك الآن في عضوية جائزة أوروك الدولية وتمتع بخصم 50% في المستشفيات وأكثر من 30 تخصصاً تدريبياً لمدة سنتين.',
textAlign: TextAlign.center,
style: TextStyle(color: AppTheme.textMuted, fontSize: 14),
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const SubscriptionCheckoutScreen()),
);
},
child: const Text('طلب الاشتراك الآن (100 دولار / سنتان)'),
),
],
),
),
);
}
Widget _buildBenefitsSection() {
return Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
color: AppTheme.cardDark,
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'المزايا المشمولة في بطاقتك:',
style: TextStyle(color: AppTheme.goldLight, fontSize: 16, fontWeight: FontWeight.bold),
),
const SizedBox(height: 12),
_buildBenefitRow(Icons.local_hospital, 'خصم 50% في المستشفيات والمراكز التخصصية (بغداد، أربيل، عمان، القاهرة، بيروت)'),
_buildBenefitRow(Icons.hotel, 'خصم من 40% إلى 60% في الفنادق السياحية الفاخرة المتعاقد معها'),
_buildBenefitRow(Icons.school, 'حضور أكثر من 30 دورة تدريبية تخصصية مجاناً مع شهادات معتمدة'),
_buildBenefitRow(Icons.verified_user, 'تغطية مستمرة لمدة سنتين كاملتين تبدأ من 1/1'),
],
),
);
}
Widget _buildBenefitRow(IconData icon, String text) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, color: AppTheme.goldAccent, size: 18),
const SizedBox(width: 10),
Expanded(
child: Text(text, style: const TextStyle(color: Colors.white70, fontSize: 13, height: 1.4)),
),
],
),
);
}
}
class _DynamicQrSheet extends StatefulWidget {
final String token;
final int? validUntil;
final VoidCallback onRefresh;
const _DynamicQrSheet({required this.token, this.validUntil, required this.onRefresh});
@override
State<_DynamicQrSheet> createState() => _DynamicQrSheetState();
}
class _DynamicQrSheetState extends State<_DynamicQrSheet> {
Timer? _timer;
int _secondsRemaining = 90;
@override
void initState() {
super.initState();
_calculateRemaining();
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted) {
setState(() {
if (_secondsRemaining > 0) {
_secondsRemaining--;
} else {
widget.onRefresh();
_calculateRemaining();
}
});
}
});
}
void _calculateRemaining() {
if (widget.validUntil != null) {
final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
_secondsRemaining = widget.validUntil! - now;
if (_secondsRemaining < 0) _secondsRemaining = 0;
}
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(24),
decoration: const BoxDecoration(
color: AppTheme.primaryDark,
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(width: 40, height: 4, decoration: BoxDecoration(color: Colors.white24, borderRadius: BorderRadius.circular(2))),
const SizedBox(height: 18),
const Text(
'رمز التحقق المشفر (Dynamic QR)',
style: TextStyle(color: AppTheme.goldLight, fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 6),
const Text(
'أبرز هذا الرمز لموظف الاستقبال في المستشفى أو الفندق لتأكيد الخصم',
style: TextStyle(color: AppTheme.textMuted, fontSize: 13),
textAlign: TextAlign.center,
),
const SizedBox(height: 20),
// Dynamic QR Code Container
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(color: AppTheme.goldAccent.withOpacity(0.3), blurRadius: 20, spreadRadius: 2),
],
),
child: QrImageView(
data: widget.token,
version: QrVersions.auto,
size: 220,
backgroundColor: Colors.white,
),
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.timer_outlined, color: AppTheme.goldAccent, size: 20),
const SizedBox(width: 6),
Text(
'يتجدد الرمز خلال $_secondsRemaining ثانية',
style: const TextStyle(color: AppTheme.goldAccent, fontSize: 14, fontWeight: FontWeight.bold),
),
],
),
const SizedBox(height: 20),
],
),
);
}
}
@@ -0,0 +1,36 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/network/api_client.dart';
import 'partners_state.dart';
class PartnersCubit extends Cubit<PartnersState> {
final ApiClient _apiClient;
PartnersCubit({ApiClient? apiClient})
: _apiClient = apiClient ?? ApiClient(),
super(PartnersInitial());
Future<void> fetchPartners({String type = 'ALL', String country = 'ALL', String? search}) async {
emit(PartnersLoading());
try {
final queryParams = <String, String>{};
if (type != 'ALL') queryParams['type'] = type;
if (country != 'ALL') queryParams['country'] = country;
if (search != null && search.isNotEmpty) queryParams['search'] = search;
final res = await _apiClient.get(
'/api/v1/partners',
queryParams: queryParams,
requiresAuth: false,
);
final list = (res['data'] as List<dynamic>?) ?? [];
emit(PartnersLoaded(
partners: list,
selectedType: type,
selectedCountry: country,
));
} catch (e) {
emit(PartnersFailure(e.toString()));
}
}
}
@@ -0,0 +1,36 @@
import 'package:equatable/equatable.dart';
abstract class PartnersState extends Equatable {
const PartnersState();
@override
List<Object?> get props => [];
}
class PartnersInitial extends PartnersState {}
class PartnersLoading extends PartnersState {}
class PartnersLoaded extends PartnersState {
final List<dynamic> partners;
final String selectedType; // 'ALL', 'HOSPITAL', 'HOTEL'
final String selectedCountry;
const PartnersLoaded({
required this.partners,
this.selectedType = 'ALL',
this.selectedCountry = 'ALL',
});
@override
List<Object?> get props => [partners, selectedType, selectedCountry];
}
class PartnersFailure extends PartnersState {
final String error;
const PartnersFailure(this.error);
@override
List<Object?> get props => [error];
}
@@ -0,0 +1,210 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/theme/app_theme.dart';
import '../cubit/partners_cubit.dart';
import '../cubit/partners_state.dart';
class PartnersDirectoryScreen extends StatefulWidget {
const PartnersDirectoryScreen({super.key});
@override
State<PartnersDirectoryScreen> createState() => _PartnersDirectoryScreenState();
}
class _PartnersDirectoryScreenState extends State<PartnersDirectoryScreen> {
final _searchController = TextEditingController();
String _selectedType = 'ALL';
@override
void initState() {
super.initState();
context.read<PartnersCubit>().fetchPartners();
}
@override
void dispose() {
_searchController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
appBar: AppBar(
title: const Text('دليل الشركاء والخصومات'),
),
body: Column(
children: [
// Search Input
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: TextField(
controller: _searchController,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
hintText: 'ابحث عن مستشفى، مركز، أو فندق...',
hintStyle: const TextStyle(color: AppTheme.textMuted),
prefixIcon: const Icon(Icons.search, color: AppTheme.goldAccent),
filled: true,
fillColor: AppTheme.cardDark,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none),
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
),
onSubmitted: (val) {
context.read<PartnersCubit>().fetchPartners(type: _selectedType, search: val);
},
),
),
// Filter Chips (Hospitals 50% vs Hotels 40-60%)
SingleChildScrollView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
child: Row(
children: [
_buildFilterChip('الكل', 'ALL'),
const SizedBox(width: 8),
_buildFilterChip('المستشفيات (خصم 50%)', 'HOSPITAL'),
const SizedBox(width: 8),
_buildFilterChip('الفنادق (خصم 40%-60%)', 'HOTEL'),
],
),
),
// Partners List
Expanded(
child: BlocBuilder<PartnersCubit, PartnersState>(
builder: (context, state) {
if (state is PartnersLoading) {
return const Center(child: CircularProgressIndicator(color: AppTheme.goldAccent));
}
if (state is PartnersLoaded) {
final list = state.partners;
if (list.isEmpty) {
return const Center(
child: Text(
'لا توجد نتائج مطابقة لبحثك.',
style: TextStyle(color: AppTheme.textMuted),
),
);
}
return ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: list.length,
itemBuilder: (context, idx) {
final item = list[idx] as Map<String, dynamic>;
final isHospital = item['type'] == 'HOSPITAL';
final discount = item['discount_percentage'] ?? (isHospital ? '50%' : '40%');
return Card(
color: AppTheme.cardDark,
margin: const EdgeInsets.only(bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
side: BorderSide(color: AppTheme.goldAccent.withOpacity(0.2)),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
item['name_ar'] ?? 'مستشفى الشريك',
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: AppTheme.goldAccent.withOpacity(0.18),
borderRadius: BorderRadius.circular(8),
),
child: Text(
'خصم $discount%',
style: const TextStyle(
color: AppTheme.goldLight,
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
),
],
),
const SizedBox(height: 6),
Text(
'${item['category'] ?? 'عام'} • ${item['city'] ?? 'العراق'}',
style: const TextStyle(color: AppTheme.textMuted, fontSize: 13),
),
if (item['address'] != null) ...[
const SizedBox(height: 6),
Row(
children: [
const Icon(Icons.location_on_outlined, color: AppTheme.goldAccent, size: 16),
const SizedBox(width: 4),
Expanded(
child: Text(
item['address'],
style: const TextStyle(color: Colors.white70, fontSize: 12),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
],
],
),
),
);
},
);
}
return Center(
child: ElevatedButton(
onPressed: () => context.read<PartnersCubit>().fetchPartners(),
child: const Text('تحديث الدليل'),
),
);
},
),
),
],
),
),
);
}
Widget _buildFilterChip(String label, String type) {
final isSelected = _selectedType == type;
return ChoiceChip(
label: Text(label),
selected: isSelected,
selectedColor: AppTheme.goldAccent,
backgroundColor: AppTheme.cardDark,
labelStyle: TextStyle(
color: isSelected ? AppTheme.primaryDark : Colors.white,
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
fontSize: 12,
),
onSelected: (selected) {
if (selected) {
setState(() => _selectedType = type);
context.read<PartnersCubit>().fetchPartners(type: type, search: _searchController.text);
}
},
);
}
}
@@ -0,0 +1,252 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/network/api_client.dart';
import '../../../core/theme/app_theme.dart';
import '../../membership/cubit/membership_cubit.dart';
class SubscriptionCheckoutScreen extends StatefulWidget {
const SubscriptionCheckoutScreen({super.key});
@override
State<SubscriptionCheckoutScreen> createState() => _SubscriptionCheckoutScreenState();
}
class _SubscriptionCheckoutScreenState extends State<SubscriptionCheckoutScreen> {
String _selectedMethod = 'SUPER_QI';
final _refController = TextEditingController();
bool _isSubmitting = false;
@override
void dispose() {
_refController.dispose();
super.dispose();
}
Future<void> _submitPayment() async {
final ref = _refController.text.trim();
if (ref.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('يرجى كتابة رقم الحركة / المعاملة المسجل في إشعار التحويل.')),
);
return;
}
setState(() => _isSubmitting = true);
try {
final client = ApiClient();
final res = await client.post('/api/v1/subscription/submit', body: {
'method': _selectedMethod,
'reference_number': ref,
});
final data = res['data'] as Map<String, dynamic>;
final isActivated = data['status'] == 'ACTIVE';
if (mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (_) => Directionality(
textDirection: TextDirection.rtl,
child: AlertDialog(
backgroundColor: AppTheme.cardDark,
title: Row(
children: [
Icon(
isActivated ? Icons.check_circle : Icons.hourglass_top,
color: isActivated ? AppTheme.emeraldGreen : Colors.amber,
),
const SizedBox(width: 8),
Text(
isActivated ? 'تم تفعيل العضوية فورياً!' : 'تم استلام طلب العضوية',
style: const TextStyle(color: Colors.white, fontSize: 16),
),
],
),
content: Text(
data['message'] ?? 'تم تسجيل المعاملة بنجاح.',
style: const TextStyle(color: Colors.white70),
),
actions: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
context.read<MembershipCubit>().fetchCardDetails();
Navigator.of(context).pop();
},
child: const Text('العودة للبطاقة'),
),
],
),
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('حدث خطأ: $e'), backgroundColor: AppTheme.crimsonRed),
);
}
} finally {
if (mounted) setState(() => _isSubmitting = false);
}
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
appBar: AppBar(
title: const Text('الاشتراك وسداد الرسوم'),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Plan Summary Card
Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFF1E293B), Color(0xFF0F172A)],
),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: AppTheme.goldAccent.withOpacity(0.5)),
),
child: const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'عضوية جائزة أوروك الدولية (سنتان)',
style: TextStyle(color: AppTheme.goldLight, fontSize: 18, fontWeight: FontWeight.bold),
),
SizedBox(height: 8),
Text(
'قيمة الاشتراك: 100 دولار أمريكي (132,000 دينار عراقي)',
style: TextStyle(color: Colors.white, fontSize: 15, fontWeight: FontWeight.bold),
),
SizedBox(height: 6),
Text(
'تشمل: خصم 50% في المستشفيات، 40-60% في الفنادق، والوصول لأكثر من 30 تخصصاً تدريبياً مع شهادات معتمدة.',
style: TextStyle(color: AppTheme.textMuted, fontSize: 13),
),
],
),
),
const SizedBox(height: 24),
const Text(
'اختر وسيلة التحويل أو السداد المعتمدة:',
style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold),
),
const SizedBox(height: 12),
_buildMethodRadio('SUPER_QI', 'سوبر كي (SuperQi / كي كارد)', Icons.credit_card),
_buildMethodRadio('ZAIN_CASH', 'محفظة زين كاش (ZainCash)', Icons.phone_android),
_buildMethodRadio('CLIQ_JORDAN', 'نظام كليك (CliQ للأردن)', Icons.swap_horiz),
_buildMethodRadio('SWIFTPAY_IQ', 'دفع إلكتروني مباشر عبر فيزا / ماستركارد', Icons.payment),
const SizedBox(height: 18),
// Account details display box
_buildPaymentInstructionsBox(),
const SizedBox(height: 24),
// Reference Number Input
TextField(
controller: _refController,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: 'رقم الحركة / المعاملة (من إيصال التحويل)',
labelStyle: const TextStyle(color: AppTheme.textMuted),
hintText: 'مثال: 2026091810121420010100166521408745772',
hintStyle: const TextStyle(color: Colors.white24, fontSize: 12),
prefixIcon: const Icon(Icons.receipt_long, color: AppTheme.goldAccent),
filled: true,
fillColor: AppTheme.cardDark,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none),
),
),
const SizedBox(height: 24),
SizedBox(
height: 52,
child: ElevatedButton(
onPressed: _isSubmitting ? null : _submitPayment,
child: _isSubmitting
? const CircularProgressIndicator(color: AppTheme.primaryDark)
: const Text('تأكيد التحويل وإصدار البطاقة فورياً'),
),
),
],
),
),
),
);
}
Widget _buildMethodRadio(String value, String title, IconData icon) {
final isSelected = _selectedMethod == value;
return Container(
margin: const EdgeInsets.only(bottom: 8),
decoration: BoxDecoration(
color: AppTheme.cardDark,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: isSelected ? AppTheme.goldAccent : Colors.transparent,
width: 1.5,
),
),
child: RadioListTile<String>(
value: value,
groupValue: _selectedMethod,
activeColor: AppTheme.goldAccent,
secondary: Icon(icon, color: isSelected ? AppTheme.goldAccent : AppTheme.textMuted),
title: Text(
title,
style: TextStyle(
color: isSelected ? Colors.white : Colors.white70,
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
fontSize: 14,
),
),
onChanged: (val) {
if (val != null) setState(() => _selectedMethod = val);
},
),
);
}
Widget _buildPaymentInstructionsBox() {
String content = '';
if (_selectedMethod == 'SUPER_QI') {
content = 'قم بالتحويل عبر تطبيق SuperQi إلى رقم الحساب المعتمد:\n'
'• رقم الحساب المستلم: 6181121 705 (حساب د. ثامر)\n'
'• بعد إتمام الحوالة، انسخ "رقم الحركة" والصقه أدناه لتفعيل البطاقة آلياً.';
} else if (_selectedMethod == 'ZAIN_CASH') {
content = 'قم بالتحويل إلى محفظة زين كاش التجارية:\n'
'• رقم المحفظة: +964 780 000 0000\n'
'• الصق رقم العملية في الخانة أدناه.';
} else if (_selectedMethod == 'CLIQ_JORDAN') {
content = 'للمشتركين في الأردن:\n'
'• تحويل CliQ إلى الاسم المستعار: URUKPRIZE\n'
'• ضع رقم المعاملة البنكية أدناه.';
} else {
content = 'سيتم توجيهك إلى بوابة SwiftPayIQ الآمنة لسداد الرسوم عبر بطاقات الدفع.';
}
return Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: AppTheme.goldAccent.withOpacity(0.08),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: AppTheme.goldAccent.withOpacity(0.25)),
),
child: Text(
content,
style: const TextStyle(color: Colors.white70, fontSize: 13, height: 1.5),
),
);
}
}
+152
View File
@@ -0,0 +1,152 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'core/theme/app_theme.dart';
import 'features/auth/cubit/auth_cubit.dart';
import 'features/auth/cubit/auth_state.dart';
import 'features/auth/presentation/phone_auth_screen.dart';
import 'features/membership/cubit/membership_cubit.dart';
import 'features/membership/presentation/digital_card_screen.dart';
import 'features/partners/cubit/partners_cubit.dart';
import 'features/partners/presentation/partners_directory_screen.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const UrukPrizeApp());
}
class UrukPrizeApp extends StatelessWidget {
const UrukPrizeApp({super.key});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<AuthCubit>(
create: (context) => AuthCubit()..checkExistingSession(),
),
BlocProvider<MembershipCubit>(
create: (context) => MembershipCubit(),
),
BlocProvider<PartnersCubit>(
create: (context) => PartnersCubit(),
),
],
child: MaterialApp(
title: 'جائزة أوروك الدولية',
debugShowCheckedModeBanner: false,
theme: AppTheme.darkTheme,
home: const AppRootGate(),
),
);
}
}
class AppRootGate extends StatelessWidget {
const AppRootGate({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<AuthCubit, AuthState>(
builder: (context, state) {
if (state is Authenticated) {
return const MainNavigationShell();
}
if (state is AuthLoading || state is AuthOtpSent) {
return const PhoneAuthScreen();
}
return const PhoneAuthScreen();
},
);
}
}
class MainNavigationShell extends StatefulWidget {
const MainNavigationShell({super.key});
@override
State<MainNavigationShell> createState() => _MainNavigationShellState();
}
class _MainNavigationShellState extends State<MainNavigationShell> {
int _currentIndex = 0;
final _screens = const [
DigitalCardScreen(),
PartnersDirectoryScreen(),
_PlaceholderCoursesScreen(),
];
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
body: IndexedStack(
index: _currentIndex,
children: _screens,
),
bottomNavigationBar: NavigationBar(
selectedIndex: _currentIndex,
backgroundColor: AppTheme.primaryDark,
indicatorColor: AppTheme.goldAccent.withOpacity(0.2),
onDestinationSelected: (idx) => setState(() => _currentIndex = idx),
destinations: const [
NavigationDestination(
icon: Icon(Icons.badge_outlined, color: AppTheme.textMuted),
selectedIcon: Icon(Icons.badge, color: AppTheme.goldAccent),
label: 'الهوية الرقمية',
),
NavigationDestination(
icon: Icon(Icons.medical_services_outlined, color: AppTheme.textMuted),
selectedIcon: Icon(Icons.medical_services, color: AppTheme.goldAccent),
label: 'دليل الخصومات',
),
NavigationDestination(
icon: Icon(Icons.school_outlined, color: AppTheme.textMuted),
selectedIcon: Icon(Icons.school, color: AppTheme.goldAccent),
label: 'الأكاديمية',
),
],
),
),
);
}
}
class _PlaceholderCoursesScreen extends StatelessWidget {
const _PlaceholderCoursesScreen();
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
appBar: AppBar(title: const Text('أكاديمية أوروك (30 تخصصاً)')),
body: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.school, color: AppTheme.goldAccent, size: 70),
const SizedBox(height: 16),
const Text(
'أكثر من 30 تخصصاً تدريبياً معتمداً',
style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
const Text(
'تبدأ الدورات حضورياً في قاعات الفنادق الشريكة وأونلاين عبر منصة البث المباشر لأوروك مع بداية تفعيل العضوية في 1/1 مع شهادات معتمدة رسمياً.',
textAlign: TextAlign.center,
style: TextStyle(color: AppTheme.textMuted, fontSize: 13),
),
],
),
),
),
),
);
}
}