Update: 2026-06-21 18:58:05

This commit is contained in:
Hamza-Ayed
2026-06-21 18:58:13 +03:00
parent b492b5076b
commit e73be65a72
8755 changed files with 92977 additions and 99 deletions

View File

@@ -338,6 +338,14 @@ import 'box_name.dart';class AppLink {
static String addAdminUser = "$server/Admin/adminUser/add.php";
static String addStaff = "$server/Admin/Staff/add.php";
static String getdashbord = "$server/Admin/dashbord.php";
// Marketing & Price Anomalies Endpoints
static String getMarketAnomalies = "$server/Admin/marketing/get_market_anomalies.php";
static String triggerCampaign = "$server/Admin/marketing/trigger_campaign.php";
static String getCampaignsLog = "$server/Admin/marketing/get_campaigns_log.php";
static String getTelemetry = "$server/Admin/marketing/get_telemetry.php";
static String getPriceComparison = "$server/Admin/marketing/get_price_comparison.php";
static String saveDriverDestination = "$server/ride/location/save_driver_destination.php";
static String paymentServerV2 = 'https://walletintaleq.intaleq.xyz/v2/main';
static String realtimeDashboardV2 = "$server/Admin/v2/realtime_dashboard.php";
static String smartAlertsV2 = "$server/Admin/v2/smart_alerts.php";

View File

@@ -0,0 +1,190 @@
import 'package:get/get.dart';
import '../../constant/links.dart';
import '../functions/crud.dart';
class MarketingController extends GetxController {
bool isLoading = false;
List priceAnomalies = [];
List campaignsLog = [];
// --- Dynamic Dashboard Configurations ---
String selectedCountry = 'All'; // 'All', 'SY', 'JO', 'EG', 'IQ'
bool isAutopilotEnabled = true;
String systemPrompt = "أنت المحلل الذكي لتطبيق Siro لخدمات نقل الركاب. قمنا برصد قراءات أسعار المنافسين لتقديم عروض وحملات تسويقية ملائمة ومخصصة.";
// --- AI API Token & Cost Telemetry ---
int apiRequestsCount = 0;
int totalTokensUsed = 0;
double estimatedCostUSD = 0.0;
// --- Price Comparison Data ---
List hourlyPriceData = [];
List pciRegions = [];
Map siroBasePrices = {};
// --- Country Selection Handler ---
void changeCountry(String countryCode) {
selectedCountry = countryCode;
fetchAnomalies();
fetchCampaignsLog();
fetchPriceComparison();
}
// --- Autopilot Status Toggle ---
void toggleAutopilot(bool value) {
isAutopilotEnabled = value;
update();
Get.snackbar(
"Autopilot Updated".tr,
value ? "Full Autopilot mode enabled".tr : "Approval Mode enabled".tr,
snackPosition: SnackPosition.BOTTOM,
);
}
// --- System Prompt Configuration Saver ---
void savePrompt(String newPrompt) {
systemPrompt = newPrompt;
update();
Get.snackbar(
"Configuration Saved".tr,
"Gemini system instructions updated successfully".tr,
snackPosition: SnackPosition.BOTTOM,
);
}
Future<void> fetchAnomalies() async {
isLoading = true;
update();
try {
Map<String, dynamic> params = {};
if (selectedCountry != 'All') {
params['country_code'] = selectedCountry;
}
var res = await CRUD().post(
link: AppLink.getMarketAnomalies,
payload: params,
);
if (res is Map && res['status'] == 'success') {
priceAnomalies = res['message'] ?? [];
} else {
Get.snackbar("Error", "Failed to fetch price anomalies");
}
} catch (e) {
Get.snackbar("Error", "Network error while loading anomalies");
} finally {
isLoading = false;
update();
}
}
Future<void> fetchTelemetry() async {
try {
Map<String, dynamic> params = {};
if (selectedCountry != 'All') {
params['country_code'] = selectedCountry;
}
var res = await CRUD().post(
link: AppLink.getTelemetry,
payload: params,
);
if (res is Map && res['status'] == 'success') {
final data = res['message'];
if (data is Map) {
apiRequestsCount = data['api_requests_count'] ?? 0;
totalTokensUsed = data['total_tokens_used'] ?? 0;
estimatedCostUSD = (data['estimated_cost_usd'] ?? 0.0).toDouble();
update();
}
}
} catch (e) {
// Silently fail — telemetry is non-critical
}
}
Future<void> fetchCampaignsLog() async {
isLoading = true;
update();
try {
Map<String, dynamic> params = {};
if (selectedCountry != 'All') {
params['country_code'] = selectedCountry;
}
var res = await CRUD().post(
link: AppLink.getCampaignsLog,
payload: params,
);
if (res is Map && res['status'] == 'success') {
campaignsLog = res['message'] ?? [];
} else {
Get.snackbar("Error", "Failed to fetch campaign logs");
}
} catch (e) {
Get.snackbar("Error", "Network error while loading campaign logs");
} finally {
isLoading = false;
update();
}
}
Future<void> fetchPriceComparison() async {
try {
Map<String, dynamic> params = {};
if (selectedCountry != 'All') {
params['country_code'] = selectedCountry;
}
var res = await CRUD().post(
link: AppLink.getPriceComparison,
payload: params,
);
if (res is Map && res['status'] == 'success') {
final data = res['message'];
if (data is Map) {
hourlyPriceData = data['hourly_competitor_prices'] ?? [];
pciRegions = data['pci_regions'] ?? [];
siroBasePrices = data['siro_base_prices'] is Map
? data['siro_base_prices'] as Map
: {};
update();
}
}
} catch (e) {
// Silently fail
}
}
Future<void> triggerAICampaign() async {
isLoading = true;
update();
try {
Map<String, dynamic> params = {};
if (selectedCountry != 'All') {
params['country_code'] = selectedCountry;
}
var res = await CRUD().post(
link: AppLink.triggerCampaign,
payload: params,
);
if (res is Map) {
if (res['status'] == 'success') {
Get.snackbar("Success", "AI campaign triggered successfully! Promos sent.");
fetchCampaignsLog();
fetchTelemetry();
} else {
Get.snackbar("Campaign Alert", res['message'] ?? "Campaign rate limited.");
}
} else {
Get.snackbar("Error", "Failed to trigger AI campaign");
}
} catch (e) {
Get.snackbar("Error", "Network error while triggering campaign");
} finally {
isLoading = false;
update();
}
}
}

View File

@@ -6,6 +6,7 @@ import 'views/admin/promo/promo_management_page.dart';
import 'views/admin/pricing/kazan_editor_page.dart';
import 'views/admin/complaints/complaint_list_page.dart';
import 'views/admin/drivers/driver_documents_review_page.dart';
import 'views/admin/marketing/marketing_page.dart';
List<GetPage<dynamic>> routes = [
GetPage(name: "/", page: () => const AdminHomePage()),
@@ -15,5 +16,6 @@ List<GetPage<dynamic>> routes = [
GetPage(name: "/kazan", page: () => KazanEditorPage()),
GetPage(name: "/complaints", page: () => ComplaintListPage()),
GetPage(name: "/driver-docs", page: () => DriverDocsReviewPage()),
GetPage(name: "/marketing", page: () => const MarketingPage()),
];

View File

@@ -814,6 +814,8 @@ class _AdminHomePageState extends State<AdminHomePage>
_danger, () => Get.to(() => const AuditLogsPage())),
ActionItem('واتساب جماعي', Icons.message_rounded,
const Color(0xFF4CAF50), () => _showWhatsAppDialog(context)),
ActionItem('أتمتة التسويق', Icons.campaign_rounded,
const Color(0xFF80CBC4), () => Get.toNamed('/marketing')),
ActionItem(
'إشعار سائقين',
Icons.notifications_active_rounded,

View File

@@ -0,0 +1,810 @@
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:get/get.dart';
import 'package:fl_chart/fl_chart.dart';
import '../../../constant/colors.dart';
import '../../../controller/admin/marketing_controller.dart';
class MarketingPage extends StatelessWidget {
const MarketingPage({super.key});
static const Color _bg = AppColor.bg;
static const Color _surface = AppColor.surface;
static const Color _accent = AppColor.accent;
static const Color _danger = AppColor.danger;
static const Color _success = AppColor.success;
static const Color _info = AppColor.info;
static const Color _textPrimary = AppColor.textPrimary;
static const Color _textSecondary = AppColor.textSecondary;
static const Color _divider = AppColor.divider;
@override
Widget build(BuildContext context) {
final controller = Get.put(MarketingController());
// Initial load
controller.fetchAnomalies();
controller.fetchCampaignsLog();
controller.fetchTelemetry();
controller.fetchPriceComparison();
return GetBuilder<MarketingController>(
builder: (c) {
return DefaultTabController(
length: 3,
child: Scaffold(
backgroundColor: _bg,
appBar: AppBar(
title: const Text(
'أتمتة التسويق الذكي (Siro AI Marketing)',
style: TextStyle(fontWeight: FontWeight.w700, fontSize: 16),
),
backgroundColor: _bg,
elevation: 0,
foregroundColor: _textPrimary,
bottom: PreferredSize(
preferredSize: const Size.fromHeight(98),
child: Column(
children: [
_buildCountrySelector(c),
const TabBar(
indicatorColor: _accent,
labelColor: _accent,
unselectedLabelColor: _textSecondary,
labelStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
tabs: [
Tab(icon: Icon(Icons.analytics_outlined, size: 20), text: 'شواذ الأسعار والمنافسين'),
Tab(icon: Icon(Icons.campaign_outlined, size: 20), text: 'سجل الحملات المنجزة'),
Tab(icon: Icon(Icons.settings_outlined, size: 20), text: 'إعدادات الأتمتة والتحكم'),
],
),
],
),
),
),
body: TabBarView(
children: [
_buildAnomaliesTab(context, c),
_buildLogsTab(context, c),
_buildConfigTab(context, c),
],
),
),
);
},
);
}
Widget _buildCountrySelector(MarketingController c) {
final countries = {
'All': 'الكل',
'SY': 'سوريا 🇸🇾',
'JO': 'الأردن 🇯🇴',
'EG': 'مصر 🇪🇬',
'IQ': 'العراق 🇮🇶',
};
return SizedBox(
height: 44,
child: ListView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
children: countries.entries.map((entry) {
final isSelected = c.selectedCountry == entry.key;
return Padding(
padding: const EdgeInsets.only(left: 8),
child: ChoiceChip(
label: Text(
entry.value,
style: TextStyle(
color: isSelected ? Colors.white : _textSecondary,
fontWeight: FontWeight.bold,
fontSize: 11,
),
),
selected: isSelected,
onSelected: (_) => c.changeCountry(entry.key),
selectedColor: _accent,
backgroundColor: _surface,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
side: BorderSide(color: isSelected ? _accent : _divider),
),
),
);
}).toList(),
),
);
}
Widget _buildAnomaliesTab(BuildContext context, MarketingController c) {
return SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildAIControlCard(context, c),
_buildComparisonChart(),
_buildPCIHeatmapSection(),
Padding(
padding: const EdgeInsets.fromLTRB(16, 20, 16, 8),
child: Row(
children: [
Container(
width: 3,
height: 14,
decoration: BoxDecoration(color: _accent, borderRadius: BorderRadius.circular(2)),
),
const SizedBox(width: 8),
const Text(
'أحدث مقارنات أسعار المنافسين والفرص السوقية',
style: TextStyle(color: _textSecondary, fontSize: 12, fontWeight: FontWeight.bold),
),
],
),
),
if (c.isLoading && c.priceAnomalies.isEmpty)
const SizedBox(
height: 200,
child: Center(child: CircularProgressIndicator(color: _accent)),
)
else if (c.priceAnomalies.isEmpty)
const SizedBox(
height: 120,
child: Center(
child: Text('لا توجد شواذ سعرية مسجلة حالياً.', style: TextStyle(color: _textSecondary)),
),
)
else
ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
itemCount: c.priceAnomalies.length,
itemBuilder: (context, index) {
final anomaly = c.priceAnomalies[index];
return AnimationConfiguration.staggeredList(
position: index,
duration: const Duration(milliseconds: 375),
child: SlideAnimation(
verticalOffset: 20.0,
child: FadeInAnimation(
child: Card(
color: _surface,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: const BorderSide(color: _divider),
),
margin: const EdgeInsets.only(bottom: 12),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: _accent.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
),
child: Text(
anomaly['competitor_name'] ?? "منافس غير معروف",
style: const TextStyle(color: _accent, fontWeight: FontWeight.bold, fontSize: 11),
),
),
Text(
anomaly['country_code'] ?? "",
style: const TextStyle(color: _textSecondary, fontSize: 11),
),
],
),
const SizedBox(height: 12),
Row(
children: [
_buildStatItem('سعرنا', '${anomaly['our_price']}', _success),
const SizedBox(width: 24),
_buildStatItem('سعر المنافس', '${anomaly['competitor_price']}', _danger),
const SizedBox(width: 24),
_buildStatItem(
'الفارق',
'${((double.tryParse(anomaly['competitor_price']?.toString() ?? '0') ?? 0) - (double.tryParse(anomaly['our_price']?.toString() ?? '0') ?? 0)).toStringAsFixed(2)}',
_info,
),
],
),
const SizedBox(height: 12),
Divider(color: _divider, height: 1),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'تاريخ الرصد: ${anomaly['detected_at'] ?? ""}',
style: const TextStyle(color: _textSecondary, fontSize: 10),
),
if (anomaly['anomaly_type'] != null)
Text(
anomaly['anomaly_type'].toString(),
style: TextStyle(
color: anomaly['anomaly_type'].toString().contains('high') ? _danger : _info,
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
],
),
],
),
),
),
),
),
);
},
),
],
),
);
}
Widget _buildComparisonChart() {
return GetBuilder<MarketingController>(
builder: (c) {
final hourlyData = c.hourlyPriceData;
final siroBase = c.siroBasePrices;
final double siroSpeedPrice = (siroBase['speedPrice'] != null)
? double.tryParse(siroBase['speedPrice'].toString()) ?? 0.0
: 0.0;
List<FlSpot> competitorSpots = [];
if (hourlyData is List && hourlyData.isNotEmpty) {
for (int i = 0; i < hourlyData.length && i < 24; i++) {
final val = hourlyData[i];
final double avg = double.tryParse((val['avg_price_per_km'] ?? 0).toString()) ?? 0.0;
competitorSpots.add(FlSpot(i.toDouble(), avg));
}
}
if (competitorSpots.isEmpty) {
competitorSpots = const [FlSpot(0, 0), FlSpot(1, 0)];
}
final double maxY = competitorSpots.fold<double>(0, (p, s) => s.y > p ? s.y : p);
final double chartMaxY = maxY > 0 ? maxY * 1.3 : 10;
List<FlSpot> siroSpots = [];
if (siroSpeedPrice > 0) {
for (int i = 0; i < (hourlyData is List ? hourlyData.length : 1); i++) {
siroSpots.add(FlSpot(i.toDouble(), siroSpeedPrice));
}
}
return Card(
color: _surface,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: const BorderSide(color: _divider),
),
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'مقارنة تقلبات الأسعار اللحظية (ساعة/ريال)',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: _textPrimary),
),
const SizedBox(height: 4),
Text(
hourlyData is List && hourlyData.isNotEmpty
? 'مقارنة أسعار Siro مقابل متوسط المنافسين لآخر ${hourlyData.length} ساعة'
: 'مقارنة أسعار Siro مقابل متوسط المنافسين لآخر 24 ساعة',
style: const TextStyle(fontSize: 10, color: _textSecondary),
),
const SizedBox(height: 24),
SizedBox(
height: 160,
child: LineChart(
LineChartData(
gridData: const FlGridData(show: false),
titlesData: FlTitlesData(
show: true,
rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
leftTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
reservedSize: 30,
getTitlesWidget: (value, meta) {
if (value == 0 || value == chartMaxY / 2 || value == chartMaxY) {
return Text('${value.toInt()}', style: const TextStyle(color: _textSecondary, fontSize: 9));
}
return const SizedBox.shrink();
},
),
),
bottomTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
reservedSize: 22,
getTitlesWidget: (value, meta) {
final idx = value.toInt();
if (idx % 4 == 0 && idx < 24) {
return Text('${idx}h', style: const TextStyle(color: _textSecondary, fontSize: 8));
}
return const SizedBox.shrink();
},
),
),
),
borderData: FlBorderData(show: false),
minX: 0,
maxX: ((hourlyData is List ? hourlyData.length : 1) - 1).toDouble(),
minY: 0,
maxY: chartMaxY,
lineBarsData: [
if (siroSpots.length > 1)
LineChartBarData(
spots: siroSpots,
isCurved: true,
color: _accent,
barWidth: 3,
isStrokeCapRound: true,
dotData: const FlDotData(show: false),
belowBarData: BarAreaData(
show: true,
color: _accent.withOpacity(0.1),
),
),
LineChartBarData(
spots: competitorSpots,
isCurved: true,
color: _danger,
barWidth: 2,
isStrokeCapRound: true,
dotData: const FlDotData(show: false),
belowBarData: BarAreaData(
show: true,
color: _danger.withOpacity(0.05),
),
),
],
),
),
),
],
),
),
);
},
);
}
Widget _buildPCIHeatmapSection() {
return GetBuilder<MarketingController>(
builder: (c) {
final pciData = c.pciRegions;
final siroBase = c.siroBasePrices;
final double siroSpeedPrice = (siroBase['speedPrice'] != null)
? double.tryParse(siroBase['speedPrice'].toString()) ?? 0.0
: 0.0;
List<Map<String, dynamic>> regions = [];
if (pciData is List && pciData.isNotEmpty) {
for (final item in pciData) {
final double compAvg = double.tryParse((item['avg_price_per_km'] ?? 0).toString()) ?? 0.0;
final pci = siroSpeedPrice > 0 && compAvg > 0
? (siroSpeedPrice / compAvg).clamp(0.5, 1.5)
: 1.0;
final pct = ((1 - pci) * 100).abs().toStringAsFixed(1);
final isCheaper = pci < 1;
regions.add({
'name': '${item['competitor_name'] ?? 'منافس'} (${item['lat_group'] ?? ''}, ${item['lng_group'] ?? ''})',
'pci': pci,
'desc': isCheaper ? 'أرخص بنسبة $pct% من المنافسين' : 'أغلى بنسبة $pct% من المنافسين',
'samples': item['samples'] ?? 0,
});
}
}
if (regions.isEmpty) {
regions = [
{'name': 'لا توجد بيانات', 'pci': 1.0, 'desc': 'يتم جمع البيانات خلال 24 ساعة', 'samples': 0},
];
}
return Card(
color: _surface,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: const BorderSide(color: _divider),
),
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'خارطة الفجوات ومؤشر التنافسية السعري (PCI)',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: _textPrimary),
),
const SizedBox(height: 12),
...regions.map((region) {
final pciVal = (region['pci'] as num).toDouble();
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Text(region['name'] as String, style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: _textPrimary)),
),
const SizedBox(width: 8),
Text(region['desc'] as String, style: const TextStyle(fontSize: 10, color: _success)),
],
),
const SizedBox(height: 6),
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value: (1 - pciVal).clamp(0.0, 1.0),
backgroundColor: AppColor.surfaceElevated,
color: _success,
minHeight: 6,
),
),
],
),
);
}).toList(),
],
),
),
);
},
);
}
Widget _buildLogsTab(BuildContext context, MarketingController c) {
if (c.isLoading && c.campaignsLog.isEmpty) {
return const Center(child: CircularProgressIndicator(color: _accent));
}
if (c.campaignsLog.isEmpty) {
return const Center(
child: Text('سجل الحملات فارغ حالياً.', style: TextStyle(color: _textSecondary)),
);
}
return ListView.builder(
physics: const BouncingScrollPhysics(),
padding: const EdgeInsets.all(16),
itemCount: c.campaignsLog.length,
itemBuilder: (context, index) {
final log = c.campaignsLog[index];
final channel = log['channel']?.toString().toUpperCase() ?? "FCM";
Color channelColor = _info;
if (channel == 'SMS') channelColor = _success;
if (channel == 'WHATSAPP') channelColor = const Color(0xFF25D366);
return Card(
color: _surface,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: const BorderSide(color: _divider),
),
margin: const EdgeInsets.only(bottom: 12),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: channelColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
),
child: Text(
channel,
style: TextStyle(color: channelColor, fontWeight: FontWeight.bold, fontSize: 11),
),
),
Text(
log['created_at'] ?? "",
style: const TextStyle(color: _textSecondary, fontSize: 11),
),
],
),
const SizedBox(height: 12),
Text(
log['campaign_name'] ?? "حملة استعادة تلقائية",
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: _textPrimary),
),
const SizedBox(height: 8),
Text(
log['message_body'] ?? "",
style: const TextStyle(fontSize: 12, color: _textSecondary, height: 1.4),
),
const SizedBox(height: 12),
Divider(color: _divider, height: 1),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
const Icon(Icons.people_outline_rounded, size: 16, color: _textSecondary),
const SizedBox(width: 6),
Text(
'المستهدفون: ${log['users_targeted'] ?? 0}',
style: const TextStyle(color: _textSecondary, fontSize: 12),
),
],
),
if (log['promo_code'] != null)
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: _accent.withOpacity(0.08),
borderRadius: BorderRadius.circular(6),
border: Border.all(color: _accent.withOpacity(0.2)),
),
child: Text(
'كود: ${log['promo_code']}',
style: const TextStyle(color: _accent, fontWeight: FontWeight.bold, fontSize: 11),
),
),
],
),
],
),
),
);
},
);
}
Widget _buildConfigTab(BuildContext context, MarketingController c) {
final promptCtrl = TextEditingController(text: c.systemPrompt);
return SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// 1. Telemetry Monitor Card
Card(
color: _surface,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: const BorderSide(color: _divider),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Row(
children: [
Icon(Icons.bar_chart_rounded, color: _info, size: 20),
SizedBox(width: 8),
Text(
'مراقب استهلاك الرموز والطلبات (API Telemetry)',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: _textPrimary),
),
],
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
_buildTelemetryItem('طلبات الـ API', '${c.apiRequestsCount}', _textPrimary),
_buildTelemetryItem('الرموز (Tokens)', '${c.totalTokensUsed}', _textPrimary),
_buildTelemetryItem('التكلفة التقديرية', '\$${c.estimatedCostUSD.toStringAsFixed(5)}', _success),
],
),
],
),
),
),
const SizedBox(height: 16),
// 2. Autopilot Mode Card
Card(
color: _surface,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: const BorderSide(color: _divider),
),
child: SwitchListTile(
title: const Text(
'التشغيل الآلي بالكامل (Full Autopilot)',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: _textPrimary),
),
subtitle: Text(
c.isAutopilotEnabled
? 'يقوم النظام بإرسال الرسائل الترويجية فور رصد فرصة سعرية دون تدخل.'
: 'النظام في وضع شبه الآلي (يتطلب مراجعة المدير قبل الإرسال).',
style: const TextStyle(fontSize: 10, color: _textSecondary),
),
value: c.isAutopilotEnabled,
activeColor: _accent,
onChanged: c.toggleAutopilot,
),
),
const SizedBox(height: 16),
// 3. Prompt Configuration Editor Card
Card(
color: _surface,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: const BorderSide(color: _divider),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Row(
children: [
Icon(Icons.edit_note_rounded, color: _accent, size: 20),
SizedBox(width: 8),
Text(
'تعديل التوجيه الأساسي للذكاء الاصطناعي (System Prompt)',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: _textPrimary),
),
],
),
const SizedBox(height: 12),
TextField(
controller: promptCtrl,
maxLines: 4,
style: const TextStyle(fontSize: 12, color: _textPrimary),
decoration: InputDecoration(
filled: true,
fillColor: AppColor.surfaceElevated,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: _divider),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: _divider),
),
),
),
const SizedBox(height: 12),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: _accent,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
padding: const EdgeInsets.symmetric(vertical: 12),
),
onPressed: () => c.savePrompt(promptCtrl.text),
child: const Text('حفظ التوجيهات الجديدة', style: TextStyle(fontWeight: FontWeight.bold)),
),
],
),
),
),
],
),
);
}
Widget _buildTelemetryItem(String label, String value, Color valueColor) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: const TextStyle(color: _textSecondary, fontSize: 10)),
const SizedBox(height: 4),
Text(
value,
style: TextStyle(color: valueColor, fontSize: 14, fontWeight: FontWeight.bold),
),
],
);
}
Widget _buildStatItem(String label, String value, Color color) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: const TextStyle(color: _textSecondary, fontSize: 11)),
const SizedBox(height: 4),
Text(
value,
style: TextStyle(color: color, fontSize: 15, fontWeight: FontWeight.bold),
),
],
);
}
Widget _buildAIControlCard(BuildContext context, MarketingController c) {
return Container(
margin: const EdgeInsets.all(16),
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
gradient: const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
AppColor.surfaceElevated,
AppColor.surface,
],
),
border: Border.all(color: AppColor.accentBorder),
boxShadow: [
BoxShadow(
color: _accent.withOpacity(0.08),
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: _accent.withOpacity(0.12),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(Icons.psychology_outlined, color: _accent, size: 24),
),
const SizedBox(width: 12),
const Text(
'مركز حملات الذكاء الاصطناعي (Gemini)',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 15),
),
],
),
const SizedBox(height: 12),
const Text(
'يقوم نظام Autopilot بتحليل الشواذ السعرية لمنافسينا في مختلف المناطق الجغرافية، وصياغة عروض وحملات تسويقية ملائمة ومخصصة لإرسالها فورياً للعملاء المستهدفين.',
style: TextStyle(color: Colors.white70, fontSize: 11, height: 1.5),
),
const SizedBox(height: 20),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: _accent,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
padding: const EdgeInsets.symmetric(vertical: 14),
elevation: 4,
),
onPressed: c.isLoading ? null : () => c.triggerAICampaign(),
icon: c.isLoading
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2),
)
: const Icon(Icons.offline_bolt_rounded),
label: const Text(
'إطلاق حملة استعادة ذكية فوراً',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
],
),
);
}
}