'failure', 'message' => 'Unauthorized. Driver role required.']); exit; } // 2. Filter Inputs $action = filterRequest('action') ?? 'set'; $destLat = filterRequest('destination_lat') ?? filterRequest('target_latitude'); $destLng = filterRequest('destination_lng') ?? filterRequest('target_longitude'); $destName = filterRequest('destination_name') ?? 'Destination'; try { if ($action === 'get') { $stmtGet = $con->prepare(" SELECT target_latitude, target_longitude, destination_name, created_at FROM driver_destinations WHERE driver_id = :did AND is_active = 1 LIMIT 1 "); $stmtGet->execute([':did' => $user_id]); $activeDest = $stmtGet->fetch(PDO::FETCH_ASSOC); if ($activeDest) { jsonSuccess($activeDest, "Active destination retrieved."); } else { jsonSuccess(null, "No active destination set."); } exit; } if ($action === 'clear') { $stmtDeactivate = $con->prepare(" UPDATE driver_destinations SET is_active = 0 WHERE driver_id = :did AND is_active = 1 "); $stmtDeactivate->execute([':did' => $user_id]); jsonSuccess(null, "تم إلغاء تفعيل الوجهة الشخصية بنجاح."); exit; } // Default action: set if (empty($destLat) || empty($destLng)) { jsonError("Missing required parameters: destination_lat and destination_lng are required."); } // 3. Enforce Limit: Max 2 times daily $stmtCount = $con->prepare(" SELECT COUNT(*) FROM driver_destinations WHERE driver_id = :did AND usage_date = CURDATE() AND is_active = 1 "); $stmtCount->execute([':did' => $user_id]); $dailyCount = intval($stmtCount->fetchColumn()); if ($dailyCount >= 2) { jsonError("حسناً كابتن، لقد وصلت للحد الأقصى المسموح به لتحديد الوجهة اليوم (مرتان في اليوم)."); } // 4. Deactivate previous active destinations for this driver $stmtDeactivate = $con->prepare(" UPDATE driver_destinations SET is_active = 0 WHERE driver_id = :did AND is_active = 1 "); $stmtDeactivate->execute([':did' => $user_id]); // 5. Insert new destination $stmtInsert = $con->prepare(" INSERT INTO driver_destinations (driver_id, target_latitude, target_longitude, destination_name, is_active, usage_date) VALUES (:did, :lat, :lng, :name, 1, CURDATE()) "); $stmtInsert->execute([ ':did' => $user_id, ':lat' => (float)$destLat, ':lng' => (float)$destLng, ':name' => $destName ]); jsonSuccess(null, "تم حفظ وجهتك كابتن بنجاح! سيتم توجيه الطلبات المطابقة لوجهتك."); } catch (Exception $e) { error_log("[save_driver_destination.php] Error: " . $e->getMessage()); jsonError("Failed to save driver destination: " . $e->getMessage()); }