sync static method

Future<bool> sync(
  1. String apiUrl, {
  2. String? userId,
  3. Map<String, String>? headers,
})

Sync locations to API

Implementation

static Future<bool> sync(String apiUrl, {String? userId, Map<String, String>? headers}) async {
  try {
    if (_database == null) await _initDatabase();

    final List<Map<String, dynamic>> maps = await _database!.query(
      'locations',
      where: 'synced = ?',
      whereArgs: [0],
    );

    if (maps.isEmpty) return true;

    final List<Map<String, dynamic>> locations = maps.map((map) {
      final location = LocationData.fromMap(map);
      return location.toMap();
    }).toList();

    final Map<String, dynamic> payload = {
      'locations': locations,
      if (userId != null) 'userId': userId,
    };

    final response = await http.post(
      Uri.parse(apiUrl),
      headers: {
        'Content-Type': 'application/json',
        ...?headers,
      },
      body: json.encode(payload),
    );

    if (response.statusCode == 200) {
      // Mark locations as synced
      await _database!.update(
        'locations',
        {'synced': 1},
        where: 'synced = ?',
        whereArgs: [0],
      );
      return true;
    } else {
      print('API sync failed: ${response.statusCode}');
      return false;
    }
  } catch (e) {
    print('Error syncing locations: $e');
    return false;
  }
}