stopAndSave method

void stopAndSave({
  1. required bool shouldSave,
})

Implementation

void stopAndSave({required bool shouldSave}) async {
  final user = FirebaseAuth.instance.currentUser;
  bool isFirstExerciseInTimeWindow = false;

  if (user != null && shouldSave) {
    final now = DateTime.now();
    final startTime = now.subtract(elapsed.value);
    final durationInSeconds = elapsed.value.inSeconds;

    await FirebaseFirestore.instance
        .collection('users')
        .doc(user.uid)
        .collection('exerciseLogs')
        .add({
      'exerciseName': exerciseName.value,
      'category': exerciseCategory.value,
      'startTime': Timestamp.fromDate(startTime),
      'endTime': Timestamp.fromDate(now),
      'duration': durationInSeconds,
      //in Sekunden --> am Tag dann 300 Sekunden ingesamt nötig, dass die Streak verlängert wird, bzw. die tägliche Mindestdauer erreicht/erfüllt wird
    });

    // Check if this is the first exercise in the last 4 hours
    isFirstExerciseInTimeWindow = await checkIfFirstExerciseInTimeWindow(user.uid);

    // Check and update streak - Fixed null safety
    if ((await statisticsController.isStreakActive(user.email!) == false) &&
        (await statisticsController.getDoneExercisesInSeconds(user.email!) >= 300)) {
      await FirebaseFirestore.instance
          .collection('users')
          .doc(user.uid)
          .collection('streaks')
          .add({'isActive': true, 'startedAt': Timestamp.now()});
    }

    // Update streak controller
    final streakCtrl = Get.find<StreakController>();
    await streakCtrl.loadStreakData();
  }

  // Reset timer state
  _stopwatch.stop();
  _stopwatch.reset();
  isRunning.value = false;
  isPaused.value = false;
  exerciseName.value = '';
  exerciseCategory.value = '';
  elapsed.value = Duration.zero;

  // Navigate to dashboard with Progress tab selected
  Get.offAll(
          () => Dashboard(initialIndex: 0),
      arguments: {
        'exerciseCompleted': true,
        'isFirstInTimeWindow': isFirstExerciseInTimeWindow
      }
  );
}