feat: استيراد كود سيرو إلى تريبز (سيرو @ecfe7568) — بلا تعديل
قرار المالك 2026-07-27: باك إند سيرو PHP هو المعتمد، وتطبيقاته المجرّبة ميدانياً تحل محل إعادة البناء المؤرشفة. سيرو نفسه لم يُمسّ. الخريطة: backend · payment_server · loction_server · ride_server · passenger_server · docker · dashboard · stress_test → الجذر siro_rider → apps/rider siro_driver → apps/driver siro_admin → dashboards/admin siro_service → dashboards/service android_bot → apps/android_bot socialBot → apps/socialBot نُسخ المتعقَّب في git سيرو فقط عبر `git archive` (3,198 ملفاً / ~169 م.ب) لا `cp -r` — فاستُثنيت مخلفات البناء تلقائياً. بلا أي تعديل محتوى عمداً: كل ما يلي يصير فرقاً مقروءاً مقابل المصدر. لم يُستورد وسببه: siromove.com (الموقع التسويقي يبقى marketing/ في تريبز، سيرو فيه 8 ملفات) · docs و planning (تريبز له docs/ الخاص) · deploy.sh (ليس نشراً على سيرفر بل `git add . && git push origin --all` — فخّ في مستودع آخر) · transit_dashboard (بانتظار قرار مصير backend-transit و dashboards/transit-web). ⚠️ لا يبني بعد — ثلاثة نواقص متوقعة ومقصودة: 1. `.env` و `lib/env/env.g.dart` غير متعقَّبين في سيرو (أسرار لكل مستأجر): كل تطبيق فلاتر يحتاج .env خاصاً ثم توليد env.g.dart بـ build_runner. 2. إعدادات Firebase (9 ملفات google-services.json و GoogleService-Info.plist) يستبعدها .gitignore تريبز — ولكل مستأجر مشروع Firebase خاص أصلاً. 3. apps/driver في سيرو يشير إلى `../../Intaleq/packages/get` خارج المستودع → يجب ضمّ الحزم داخله أسوة بـ apps/rider. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
9909d9b4c1
commit
4d8414c96b
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
/**
|
||||
* getPredictiveDemandZones.php
|
||||
* ─────────────────────────────────────────────────────────────
|
||||
* API endpoint: يُعيد للسائق قائمة بأفضل المناطق المتوقع
|
||||
* ارتفاع الطلب فيها خلال الساعة القادمة.
|
||||
*
|
||||
* يقرأ من Redis أولاً (cache يُجدَّد كل ساعة بالـ cron)،
|
||||
* ثم يُصفّي أقرب المناطق لموقع السائق الحالي.
|
||||
*
|
||||
* Request (GET/POST):
|
||||
* lat — خط العرض الحالي للسائق
|
||||
* lng — خط الطول الحالي للسائق
|
||||
* radius — نطاق البحث بالكيلومترات (اختياري، افتراضي: 10)
|
||||
*
|
||||
* Response:
|
||||
* { success: true, zones: [...], predicted_hour: X, last_updated: "..." }
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../../core/bootstrap.php';
|
||||
require_once __DIR__ . '/../../functions.php';
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
// ── Auth ──────────────────────────────────────────────────────
|
||||
// يستخدم نفس آلية JWT الموجودة في النظام
|
||||
$driverId = getAuthDriverId(); // دالة موجودة في bootstrap/functions
|
||||
if (!$driverId) {
|
||||
http_response_code(401);
|
||||
echo json_encode(['success' => false, 'message' => 'Unauthorized']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// ── Parameters ────────────────────────────────────────────────
|
||||
$driverLat = (float)filterRequest('lat');
|
||||
$driverLng = (float)filterRequest('lng');
|
||||
$radiusKm = (float)(filterRequest('radius') ?? 10);
|
||||
|
||||
// تحويل km إلى درجات تقريباً (1° ≈ 111km)
|
||||
$radiusDeg = $radiusKm / 111.0;
|
||||
|
||||
// ── Redis Cache ───────────────────────────────────────────────
|
||||
try {
|
||||
$redis = getRedisConnection();
|
||||
} catch (Exception $e) {
|
||||
$redis = null;
|
||||
}
|
||||
|
||||
$cacheRaw = $redis ? $redis->get('siro:cache:predictive_demand') : null;
|
||||
|
||||
if ($cacheRaw) {
|
||||
$cacheData = json_decode($cacheRaw, true);
|
||||
$allZones = $cacheData['zones'] ?? [];
|
||||
|
||||
// فلتر: فقط المناطق ضمن نطاق السائق
|
||||
$nearbyZones = array_filter($allZones, function ($z) use ($driverLat, $driverLng, $radiusDeg) {
|
||||
if ($driverLat == 0 || $driverLng == 0) return true; // لو ما أرسل موقعه، أرجع الكل
|
||||
return abs($z['lat'] - $driverLat) <= $radiusDeg
|
||||
&& abs($z['lng'] - $driverLng) <= $radiusDeg;
|
||||
});
|
||||
|
||||
// ترتيب: الأقرب للسائق أولاً
|
||||
if ($driverLat != 0) {
|
||||
usort($nearbyZones, function ($a, $b) use ($driverLat, $driverLng) {
|
||||
$da = abs($a['lat'] - $driverLat) + abs($a['lng'] - $driverLng);
|
||||
$db = abs($b['lat'] - $driverLat) + abs($b['lng'] - $driverLng);
|
||||
return $da <=> $db;
|
||||
});
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'source' => 'cache',
|
||||
'predicted_hour' => $cacheData['predicted_hour'] ?? null,
|
||||
'last_updated' => $cacheData['last_updated'] ?? null,
|
||||
'zones' => array_values($nearbyZones),
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
exit;
|
||||
}
|
||||
|
||||
// ── Fallback: حساب مباشر من DB إذا لم يتوفر cache ────────────
|
||||
try {
|
||||
$con = Database::get('main');
|
||||
} catch (Exception $e) {
|
||||
echo json_encode(['success' => false, 'message' => 'DB error']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$nextHour = ((int)date('H') + 1) % 24;
|
||||
$dow = (int)date('N');
|
||||
$gridSize = 0.01;
|
||||
|
||||
$sql = "
|
||||
SELECT
|
||||
ROUND(pickup_lat / :g) * :g AS lat,
|
||||
ROUND(pickup_lng / :g) * :g AS lng,
|
||||
COUNT(*) AS demand_score,
|
||||
country_code
|
||||
FROM rides
|
||||
WHERE
|
||||
status IN ('completed', 'cancelled_by_driver', 'timeout')
|
||||
AND HOUR(created_at) = :hour
|
||||
AND DAYOFWEEK(created_at) = :dow
|
||||
AND created_at >= DATE_SUB(NOW(), INTERVAL 4 WEEK)
|
||||
AND pickup_lat BETWEEN (:dlat - :r) AND (:dlat + :r)
|
||||
AND pickup_lng BETWEEN (:dlng - :r) AND (:dlng + :r)
|
||||
GROUP BY lat, lng, country_code
|
||||
HAVING demand_score >= 2
|
||||
ORDER BY demand_score DESC
|
||||
LIMIT 10
|
||||
";
|
||||
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->execute([
|
||||
':g' => $gridSize,
|
||||
':hour' => $nextHour,
|
||||
':dow' => $dow,
|
||||
':dlat' => $driverLat ?: 31.95, // fallback عمّان
|
||||
':dlng' => $driverLng ?: 35.93,
|
||||
':r' => $radiusDeg,
|
||||
]);
|
||||
$zones = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
// تسمية المناطق
|
||||
foreach ($zones as &$z) {
|
||||
$stmtN = $con->prepare("
|
||||
SELECT zone_name FROM geofence_zones
|
||||
WHERE is_active = 1
|
||||
AND ABS(latitude - :lat) < 0.05
|
||||
AND ABS(longitude - :lng) < 0.05
|
||||
ORDER BY ABS(latitude - :lat) + ABS(longitude - :lng) ASC
|
||||
LIMIT 1
|
||||
");
|
||||
$stmtN->execute([':lat' => $z['lat'], ':lng' => $z['lng']]);
|
||||
$nameRow = $stmtN->fetch(PDO::FETCH_ASSOC);
|
||||
$z['zone_name'] = $nameRow['zone_name'] ?? 'منطقة قريبة';
|
||||
$z['lat'] = (float)$z['lat'];
|
||||
$z['lng'] = (float)$z['lng'];
|
||||
$z['demand_score'] = (int)$z['demand_score'];
|
||||
}
|
||||
unset($z);
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'source' => 'realtime',
|
||||
'predicted_hour' => $nextHour,
|
||||
'last_updated' => date('Y-m-d H:i:s'),
|
||||
'zones' => $zones,
|
||||
], JSON_UNESCAPED_UNICODE);
|
||||
?>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
/**
|
||||
* sync_location.php
|
||||
* Unified endpoint for receiving passenger location updates from:
|
||||
* - App Usage (Primary)
|
||||
* - Geofencing Events (Secondary)
|
||||
* - Silent Push Wakeups (Tertiary)
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
// require_once __DIR__ . '/../../functions.php';
|
||||
require_once __DIR__ . '/../../core/Services/LocationIntelligenceEngine.php';
|
||||
|
||||
// Validate JWT or traditional auth if needed. For now, rely on standard filterRequest if used.
|
||||
$passengerId = filterRequest('passenger_id');
|
||||
$lat = filterRequest('lat', 'float');
|
||||
$lng = filterRequest('lng', 'float');
|
||||
$source = filterRequest('source') ?? 'app_usage'; // 'app_usage', 'geofence', 'silent_push'
|
||||
$batteryLevel = filterRequest('battery_level', 'int');
|
||||
|
||||
if (!$passengerId || !$lat || !$lng) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['status' => 'failure', 'message' => 'Missing required parameters (passenger_id, lat, lng).']);
|
||||
exit;
|
||||
}
|
||||
|
||||
try {
|
||||
$engine = new LocationIntelligenceEngine($con);
|
||||
$newGeofences = $engine->processLocationUpdate($passengerId, $lat, $lng, $source, $batteryLevel);
|
||||
|
||||
// Respond with success and optionally new geofences
|
||||
echo json_encode([
|
||||
'status' => 'success',
|
||||
'message' => 'Location synced successfully',
|
||||
'update_geofences' => $newGeofences // App can use this array to update device geofencing regions
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
error_log("[sync_location.php] Error: " . $e->getMessage());
|
||||
http_response_code(500);
|
||||
echo json_encode(['status' => 'failure', 'message' => 'Internal server error.']);
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
// ============================================================
|
||||
// api/payments/get_prime_status.php
|
||||
// PURPOSE : جلب حالة اشتراك Siro Prime للراكب
|
||||
// AUTH : JWT (passenger)
|
||||
// ============================================================
|
||||
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
$passengerId = $user_id ?? null;
|
||||
if (!$passengerId || $role !== 'passenger') {
|
||||
jsonError("Unauthorized");
|
||||
exit;
|
||||
}
|
||||
|
||||
$isPrime = false;
|
||||
$expireAt = null;
|
||||
|
||||
// 1. تحقق من Redis أولاً (الأسرع)
|
||||
if (isset($redis) && $redis !== null) {
|
||||
try {
|
||||
$cached = $redis->get("prime:passenger:{$passengerId}");
|
||||
if ($cached) {
|
||||
$data = json_decode($cached, true);
|
||||
if (isset($data['is_prime']) && $data['is_prime'] == 1) {
|
||||
$expTime = strtotime($data['expire_at'] ?? '0');
|
||||
if ($expTime > time()) {
|
||||
$isPrime = true;
|
||||
$expireAt = $data['expire_at'];
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception $e) {}
|
||||
}
|
||||
|
||||
// 2. إذا ما وُجد في Redis، ارجع للـ DB
|
||||
if (!$isPrime) {
|
||||
try {
|
||||
$stmt = $con->prepare("SELECT is_prime, expire_at FROM passenger_prime_subscriptions WHERE passenger_id = :pid LIMIT 1");
|
||||
$stmt->execute([':pid' => $passengerId]);
|
||||
$row = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if ($row && $row['is_prime'] == 1 && strtotime($row['expire_at']) > time()) {
|
||||
$isPrime = true;
|
||||
$expireAt = $row['expire_at'];
|
||||
|
||||
// تحديث Redis للمرات القادمة
|
||||
if (isset($redis) && $redis !== null) {
|
||||
try {
|
||||
$redis->setex("prime:passenger:{$passengerId}", 3600, json_encode([
|
||||
'is_prime' => 1,
|
||||
'expire_at' => $expireAt
|
||||
]));
|
||||
} catch (Exception $e) {}
|
||||
}
|
||||
}
|
||||
} catch (PDOException $e) {
|
||||
error_log("[Prime Status] DB Error: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
jsonSuccess([
|
||||
'is_prime' => $isPrime,
|
||||
'expire_at' => $expireAt,
|
||||
], "Prime status fetched");
|
||||
?>
|
||||
@@ -0,0 +1,201 @@
|
||||
<?php
|
||||
// ============================================================
|
||||
// api/payments/initiate_prime.php
|
||||
// PURPOSE : شراء اشتراك Siro Prime عبر خصم رصيد المحفظة الداخلية
|
||||
// AUTH : JWT (passenger)
|
||||
// FLOW :
|
||||
// 1. جلب هوية الراكب من JWT
|
||||
// 2. تحديد السعر حسب الدولة
|
||||
// 3. التحقق من رصيد الراكب في سيرفر المحفظة (S2S)
|
||||
// 4. إذا الرصيد كافٍ → الخصم + تفعيل Prime
|
||||
// 5. إذا الرصيد غير كافٍ → رسالة لإرشاد المستخدم للشحن
|
||||
// ============================================================
|
||||
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
// ── 1. هوية الراكب من JWT ─────────────────────────────────────
|
||||
$passengerId = $user_id ?? null;
|
||||
if (!$passengerId || $role !== 'passenger') {
|
||||
jsonError("Unauthorized");
|
||||
exit;
|
||||
}
|
||||
|
||||
// ── 2. الدولة والسعر ──────────────────────────────────────────
|
||||
$country = filterRequest("country") ?: 'Jordan';
|
||||
|
||||
$pricingMap = [
|
||||
'Jordan' => ['amount' => 3.00, 'currency' => 'JOD'], // ~4 USD/month
|
||||
'Egypt' => ['amount' => 200.00,'currency' => 'EGP'], // ~4 USD/month
|
||||
'Syria' => ['amount' => 500.00,'currency' => 'SYP'], // ~4 USD/month (New Syrian Pound)
|
||||
];
|
||||
|
||||
$amount = $pricingMap[$country]['amount'] ?? 3.00;
|
||||
$currency = $pricingMap[$country]['currency'] ?? 'JOD';
|
||||
|
||||
// ── 3. سيرفر المحفظة حسب الدولة ──────────────────────────────
|
||||
$walletServer = "https://walletintaleq.intaleq.xyz"; // Default
|
||||
if (strtolower($country) === 'jordan') {
|
||||
$walletServer = getenv('WALLET_SERVER_JORDAN') ?: "https://walletintaleq.intaleq.xyz";
|
||||
} elseif (strtolower($country) === 'egypt') {
|
||||
$walletServer = getenv('WALLET_SERVER_EGYPT') ?: "https://wallet-egypt.siromove.com";
|
||||
} elseif (strtolower($country) === 'syria') {
|
||||
$walletServer = getenv('WALLET_SERVER_SYRIA') ?: "https://wallet-syria.siromove.com";
|
||||
}
|
||||
|
||||
$s2sKey = getenv('S2S_SHARED_KEY');
|
||||
if (empty($s2sKey)) {
|
||||
error_log("[Prime] CRITICAL: S2S_SHARED_KEY not set");
|
||||
jsonError("Server configuration error");
|
||||
exit;
|
||||
}
|
||||
|
||||
// ── 4. التحقق من رصيد الراكب في سيرفر المحفظة ────────────────
|
||||
$balanceUrl = "$walletServer/v2/main/ride/passengerWallet/getWalletByPassenger.php";
|
||||
|
||||
$chBalance = curl_init($balanceUrl);
|
||||
curl_setopt_array($chBalance, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => http_build_query(['passenger_id' => $passengerId]),
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-Type: application/x-www-form-urlencoded',
|
||||
'X-S2S-Api-Key: ' . $s2sKey
|
||||
]
|
||||
]);
|
||||
|
||||
$balanceRaw = curl_exec($chBalance);
|
||||
$balanceCode = curl_getinfo($chBalance, CURLINFO_HTTP_CODE);
|
||||
$balanceErr = curl_error($chBalance);
|
||||
curl_close($chBalance);
|
||||
|
||||
if ($balanceErr || $balanceCode !== 200) {
|
||||
error_log("[Prime] Wallet balance fetch failed: HTTP $balanceCode | err: $balanceErr");
|
||||
jsonError("Unable to verify wallet balance. Please try again.");
|
||||
exit;
|
||||
}
|
||||
|
||||
$balanceData = json_decode($balanceRaw, true);
|
||||
$walletBalance = (float)($balanceData['message'][0]['total'] ?? $balanceData['total'] ?? -1);
|
||||
|
||||
if ($walletBalance < 0) {
|
||||
error_log("[Prime] Unexpected wallet response: $balanceRaw");
|
||||
jsonError("Unable to read wallet balance.");
|
||||
exit;
|
||||
}
|
||||
|
||||
// ── 5. هل الرصيد كافٍ؟ ────────────────────────────────────────
|
||||
if ($walletBalance < $amount) {
|
||||
// رصيد غير كافٍ — أخبر التطبيق ليوجّه المستخدم للشحن
|
||||
echo json_encode([
|
||||
'status' => 'insufficient_balance',
|
||||
'current_balance' => $walletBalance,
|
||||
'required_amount' => $amount,
|
||||
'currency' => $currency,
|
||||
'message' => 'Your wallet balance is insufficient. Please top up your wallet to subscribe to Siro Prime.'
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
// ── 6. الرصيد كافٍ → بدء عملية الاشتراك ─────────────────────
|
||||
try {
|
||||
$con->beginTransaction();
|
||||
|
||||
// 6a. تسجيل الحركة في قاعدة بيانات سيرو (بادئها paid مباشرةً)
|
||||
$transactionRef = "PRIME-" . time() . "-" . rand(1000, 9999);
|
||||
$stmtTx = $con->prepare("
|
||||
INSERT INTO prime_payment_transactions (transaction_ref, passenger_id, amount, currency, status)
|
||||
VALUES (:ref, :pid, :amt, :curr, 'paid')
|
||||
");
|
||||
$stmtTx->execute([
|
||||
':ref' => $transactionRef,
|
||||
':pid' => $passengerId,
|
||||
':amt' => $amount,
|
||||
':curr' => $currency
|
||||
]);
|
||||
|
||||
// 6b. تفعيل أو تجديد اشتراك Prime (30 يوماً)
|
||||
$expireAt = date('Y-m-d H:i:s', strtotime('+30 days'));
|
||||
$stmtPrime = $con->prepare("
|
||||
INSERT INTO passenger_prime_subscriptions (passenger_id, is_prime, expire_at)
|
||||
VALUES (:pid, 1, :exp)
|
||||
ON DUPLICATE KEY UPDATE is_prime = 1, expire_at = :exp2, updated_at = NOW()
|
||||
");
|
||||
$stmtPrime->execute([
|
||||
':pid' => $passengerId,
|
||||
':exp' => $expireAt,
|
||||
':exp2' => $expireAt
|
||||
]);
|
||||
|
||||
// 6c. خصم المبلغ من المحفظة عبر S2S (نفس نمط tips/add.php)
|
||||
$deductUrl = "$walletServer/v2/main/ride/payment/add.php";
|
||||
$deductData = [
|
||||
"user_id" => $passengerId,
|
||||
"user_type" => "passenger",
|
||||
"amount" => -1 * $amount, // سالب = خصم
|
||||
"action" => "subtract",
|
||||
"paymentID" => $transactionRef,
|
||||
"paymentMethod" => "prime-subscription",
|
||||
"reason" => "Siro Prime Subscription - 1 Month"
|
||||
];
|
||||
|
||||
$chDeduct = curl_init($deductUrl);
|
||||
curl_setopt_array($chDeduct, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => http_build_query($deductData),
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 15,
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-Type: application/x-www-form-urlencoded',
|
||||
'X-S2S-Api-Key: ' . $s2sKey
|
||||
]
|
||||
]);
|
||||
|
||||
$deductRaw = curl_exec($chDeduct);
|
||||
$deductCode = curl_getinfo($chDeduct, CURLINFO_HTTP_CODE);
|
||||
$deductErr = curl_error($chDeduct);
|
||||
curl_close($chDeduct);
|
||||
|
||||
$deductRes = json_decode($deductRaw, true);
|
||||
|
||||
if ($deductErr || $deductCode !== 200 || ($deductRes['status'] ?? '') !== 'success') {
|
||||
// فشل الخصم → نرجع الكل
|
||||
$con->rollBack();
|
||||
error_log("[Prime] Wallet deduct FAILED: HTTP $deductCode | err: $deductErr | response: $deductRaw");
|
||||
jsonError("Failed to deduct wallet balance. Please try again.");
|
||||
exit;
|
||||
}
|
||||
|
||||
$con->commit();
|
||||
|
||||
// 6d. تحديث Redis فوراً (التفعيل اللحظي بدون إعادة طلب من DB)
|
||||
if (isset($redis) && $redis !== null) {
|
||||
try {
|
||||
$primeKey = "prime:passenger:{$passengerId}";
|
||||
$redis->setex($primeKey, 3600, json_encode([
|
||||
'is_prime' => 1,
|
||||
'expire_at' => $expireAt
|
||||
]));
|
||||
} catch (Exception $e) {
|
||||
// Redis failure is non-critical — DB is source of truth
|
||||
error_log("[Prime] Redis update failed (non-critical): " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// ── 7. ردّ النجاح للفلاتر ───────────────────────────────────
|
||||
jsonSuccess([
|
||||
'is_prime' => true,
|
||||
'expire_at' => $expireAt,
|
||||
'transaction_ref' => $transactionRef,
|
||||
'amount_deducted' => $amount,
|
||||
'currency' => $currency,
|
||||
], "Welcome to Siro Prime! 👑");
|
||||
|
||||
} catch (PDOException $e) {
|
||||
if ($con->inTransaction()) {
|
||||
$con->rollBack();
|
||||
}
|
||||
error_log("[Prime] DB Error: " . $e->getMessage());
|
||||
jsonError("Database error. Please try again.");
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
$lat = filterRequest('passenger_lat') ?: filterRequest('lat');
|
||||
$lng = filterRequest('passenger_lng') ?: filterRequest('lng');
|
||||
$country = filterRequest('country') ?: filterRequest('country_code');
|
||||
$distance = (float)(filterRequest('distance') ?: 0);
|
||||
$siroPrice = (float)(filterRequest('siro_price') ?: 0);
|
||||
|
||||
if (!$lat || !$lng || !$country) {
|
||||
echo json_encode(["status" => "error", "message" => "Missing parameters"]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$lat = (float)$lat;
|
||||
$lng = (float)$lng;
|
||||
$countryCode = strtoupper($country);
|
||||
if ($countryCode == 'JORDAN') $countryCode = 'JO';
|
||||
if ($countryCode == 'SYRIA') $countryCode = 'SY';
|
||||
if ($countryCode == 'EGYPT') $countryCode = 'EG';
|
||||
|
||||
$avgPricePerKm = 0;
|
||||
$topComp = 'TaxiF'; // Default
|
||||
|
||||
try {
|
||||
$redis = getRedisConnection();
|
||||
$cacheJson = $redis->get('siro:cache:pricing:grids');
|
||||
if ($cacheJson) {
|
||||
$cacheData = json_decode($cacheJson, true);
|
||||
if ($cacheData && isset($cacheData['grids'])) {
|
||||
$gridSize = 0.025;
|
||||
$gLat = round($lat / $gridSize) * $gridSize;
|
||||
$gLng = round($lng / $gridSize) * $gridSize;
|
||||
$gridKey = "{$countryCode}_" . number_format($gLat, 3) . "_" . number_format($gLng, 3);
|
||||
|
||||
$grids = $cacheData['grids'];
|
||||
if (isset($grids[$gridKey])) {
|
||||
$avgPricePerKm = (float)$grids[$gridKey]['avg_price'];
|
||||
$topComp = $grids[$gridKey]['top_competitor'] ?? 'TaxiF';
|
||||
} else {
|
||||
$fallbackKey = "{$countryCode}_FALLBACK";
|
||||
if (isset($grids[$fallbackKey])) {
|
||||
$avgPricePerKm = (float)$grids[$fallbackKey]['avg_price'];
|
||||
$topComp = $grids[$fallbackKey]['top_competitor'] ?? 'TaxiF';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
// Continue with defaults if Redis fails
|
||||
}
|
||||
|
||||
// If we couldn't get a price from Redis, use a smart default based on country
|
||||
if ($avgPricePerKm <= 0) {
|
||||
if ($countryCode === 'JO') {
|
||||
$avgPricePerKm = 0.35;
|
||||
$topComp = 'TaxiF';
|
||||
} else if ($countryCode === 'SY') {
|
||||
$avgPricePerKm = 4000;
|
||||
$topComp = 'Yango';
|
||||
} else if ($countryCode === 'EG') {
|
||||
$avgPricePerKm = 15;
|
||||
$topComp = 'inDrive';
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate the competitor's total price based on distance and average market per-km rate
|
||||
// 🔥 لا يوجد أي تعديل صناعي على سعر المنافس هنا — الرقم المعروض للراكب
|
||||
// يجب أن يعكس بيانات السوق الحقيقية فقط، حتى لو لم نكن أرخص فعلياً في هذه الرحلة.
|
||||
$competitorTotalPrice = round($distance * $avgPricePerKm, 2);
|
||||
|
||||
// Format the labels
|
||||
$compNameAr = 'التطبيقات الأخرى';
|
||||
|
||||
// نعرض شارة "أوفر" فقط إذا كنا أرخص فعلياً حسب البيانات الحقيقية — لا تلاعب بالأرقام
|
||||
$savingsPct = 0;
|
||||
$savingsLabel = null;
|
||||
if ($competitorTotalPrice > 0 && $siroPrice > 0 && $siroPrice < $competitorTotalPrice) {
|
||||
$savingsPct = (($competitorTotalPrice - $siroPrice) / $competitorTotalPrice) * 100;
|
||||
$savingsLabel = "أوفر بـ " . number_format($savingsPct, 1) . "% من $compNameAr ⚡";
|
||||
}
|
||||
|
||||
$siroCommissionRate = 0.14; // Default 14% commission
|
||||
if ($countryCode === 'JO') $siroCommissionRate = 0.14;
|
||||
$extraEarnings = $siroPrice * $siroCommissionRate;
|
||||
$driverExtraLabel = "رحلة مربحة! تكسب أكثر مقارنة بـ $compNameAr 💰";
|
||||
|
||||
// Return exactly what Dart expects in the root JSON
|
||||
echo json_encode([
|
||||
"status" => "success",
|
||||
"has_competitor_data" => true,
|
||||
"competitor_avg_price" => $competitorTotalPrice,
|
||||
"top_competitor" => $topComp,
|
||||
"savings_percent" => $savingsPct,
|
||||
"savings_label" => $savingsLabel,
|
||||
"driver_extra_amount" => round($extraEarnings, 2),
|
||||
"driver_extra_label" => $driverExtraLabel
|
||||
]);
|
||||
?>
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
/**
|
||||
* get_hotzones.php
|
||||
* ───────────────
|
||||
* واجهة فائقة السرعة (Ultra-Fast API) مخصصة لتطبيق السائق (Flutter).
|
||||
* تقرأ المناطق الساخنة (Hot Zones) التي حددها الذكاء الاصطناعي من الـ Redis مباشرة.
|
||||
* زمن الاستجابة: O(1).
|
||||
*/
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
require_once __DIR__ . '/../../connect.php';
|
||||
|
||||
$countryCode = strtoupper(filterRequest('country_code') ?? 'JO');
|
||||
|
||||
try {
|
||||
$redis = getRedisConnection();
|
||||
$hotZonesJson = $redis->get('siro:cache:ai:hotzones');
|
||||
} catch (Exception $e) {
|
||||
echo json_encode(["status" => "error", "message" => "Redis connection failed"]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (!$hotZonesJson) {
|
||||
echo json_encode(["status" => "success", "data" => [], "message" => "No hot zones available"]);
|
||||
exit;
|
||||
}
|
||||
|
||||
// الـ JSON القادم من Redis تم تصميمه بالفعل بالشكل النهائي المطلوب للتطبيق
|
||||
echo $hotZonesJson;
|
||||
?>
|
||||
Reference in New Issue
Block a user