Files
Siro/backend/ride/gamification/get_streak.php
T

70 lines
1.9 KiB
PHP

<?php
require_once __DIR__ . '/../../connect.php';
$driver_id = filterRequest("driver_id");
if (empty($driver_id)) {
jsonError("Missing driver_id");
exit;
}
global $redis;
$redisKey = "driver_streak:{$driver_id}";
// 1. Try to read from Redis first (Cache-Aside pattern)
if (isset($redis)) {
try {
$cached = $redis->get($redisKey);
if ($cached) {
$data = json_decode($cached, true);
if ($data) {
// Return immediately if found in cache!
jsonSuccess($data);
exit;
}
}
} catch (Exception $e) {
error_log("Redis read error in get_streak: " . $e->getMessage());
}
}
// 2. Fallback to Database if not found in Redis
$stmt = $con->prepare("SELECT current_streak, zero_commission_until FROM driver_streaks WHERE driver_id = ?");
$stmt->execute([$driver_id]);
$streak = $stmt->fetch(PDO::FETCH_ASSOC);
if ($streak) {
$now = new DateTime();
$until = new DateTime($streak['zero_commission_until']);
$isActive = false;
if ($streak['zero_commission_until'] !== '2000-01-01 00:00:00' && $now < $until) {
$isActive = true;
}
$responseData = [
'streak_count' => intval($streak['current_streak']),
'is_zero_commission_active' => $isActive,
'zero_commission_until' => $streak['zero_commission_until']
];
} else {
// Default if no record yet
$responseData = [
'streak_count' => 0,
'is_zero_commission_active' => false,
'zero_commission_until' => '2000-01-01 00:00:00'
];
}
// 3. Save the DB result into Redis for future reads
if (isset($redis)) {
try {
// Cache it for 2 hours (7200 seconds)
$redis->setex($redisKey, 7200, json_encode($responseData));
} catch (Exception $e) {
error_log("Redis write error in get_streak: " . $e->getMessage());
}
}
jsonSuccess($responseData);
?>