Files
tripz-llc/backend/bot/cron_generate_heatmap_cache.php
2026-08-09 16:56:13 +03:00

111 lines
3.5 KiB
PHP

<?php
/**
* cron_generate_heatmap_cache.php
* يجمع بيانات الخريطة الحرارية ويخزنها في Redis
*/
require_once __DIR__ . '/../core/bootstrap.php';
require_once __DIR__ . '/../functions.php';
try {
$con = Database::get('main');
$redis = getRedisConnection();
} catch (Exception $e) {
die("Connection failed: " . $e->getMessage() . "\n");
}
// getRedisConnection() لا ترمي استثناءً — تُعيد null عند تعذّر الاتصال.
// الهدف الوحيد لهذا السكربت هو الكتابة إلى مفتاح Redis للكاش.
if (!$redis) {
error_log('[HeatmapCache] ABORT: Redis unavailable — nothing to cache into.');
die("Redis unavailable — aborting heatmap cache generation.\n");
}
echo "Starting Heatmap Cache Generation (Redis)...\n";
// مربعات المدن الكبرى لتمثيل الدول (لتجنب حساب المضلعات المعقدة)
// الأردن (عمان والزرقاء)
// سوريا (دمشق)
// مصر (القاهرة والإسكندرية)
// العراق (بغداد)
$cityBounds = [
'JO' => [ // Amman & Zarqa rough bounding box
'lat' => [31.80, 32.20],
'lng' => [35.80, 36.20]
],
'SY' => [ // Damascus
'lat' => [33.40, 33.60],
'lng' => [36.20, 36.40]
],
'EG' => [ // Cairo & Alexandria
'lat' => [29.80, 31.30],
'lng' => [29.80, 31.50]
],
'IQ' => [ // Baghdad
'lat' => [33.10, 33.50],
'lng' => [44.20, 44.60]
]
];
try {
$sql = "SELECT latitude, longitude, source, created_at
FROM passenger_opening_locations
WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
ORDER BY created_at DESC
LIMIT 20000";
$stmt = $con->query($sql);
$locations = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stats = ['geofence' => 0, 'app_usage' => 0, 'silent_push' => 0];
// تقسيم البيانات حسب الدولة (لتسهيل قراءتها من الـ API)
$countryData = [
'JO' => [], 'SY' => [], 'EG' => [], 'IQ' => [], 'OTHER' => []
];
foreach ($locations as $loc) {
$lat = (float)$loc['latitude'];
$lng = (float)$loc['longitude'];
if ($lat == 0 || $lng == 0) continue;
$src = $loc['source'] ?? 'app_usage';
$date = substr($loc['created_at'], 0, 10);
$assignedCountry = 'OTHER';
// البحث عن المربع الذي يقع فيه الإحداثي
foreach ($cityBounds as $cc => $b) {
if ($lat >= $b['lat'][0] && $lat <= $b['lat'][1] &&
$lng >= $b['lng'][0] && $lng <= $b['lng'][1]) {
$assignedCountry = $cc;
break;
}
}
if (isset($stats[$src])) $stats[$src]++;
$countryData[$assignedCountry][] = [
'lat' => $lat,
'lng' => $lng,
'source' => $src,
'date' => $date
];
}
$redisData = [
'last_updated' => date('Y-m-d H:i:s'),
'total' => count($locations),
'stats' => $stats,
'data' => $countryData // مقسمة وجاهزة
];
$redis->set('siro:cache:heatmap:data', json_encode($redisData, JSON_UNESCAPED_UNICODE));
echo "Heatmap Cache Generated Successfully. Points: " . count($locations) . "\n";
} catch (Exception $e) {
error_log("Error generating heatmap cache: " . $e->getMessage());
echo "Error: " . $e->getMessage();
}
?>