import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:drift/drift.dart'; import 'package:trainhub_flutter/database/database.dart'; import 'package:trainhub_flutter/models/training_models.dart'; class TrainingsProvider extends ChangeNotifier { final AppDatabase database; List _plans = []; List _exercises = []; List get plans => _plans; List get exercises => _exercises; TrainingsProvider(this.database) { _loadData(); } Future _loadData() async { final dbPlans = await database.select(database.trainingPlans).get(); _plans = dbPlans.map((p) { final sectionsJson = p.sections != null && p.sections!.isNotEmpty ? jsonDecode(p.sections!) : []; // Manual mapping or just pass to model return TrainingPlanModel.fromJson({ 'id': p.id, 'name': p.name, 'sections': sectionsJson, }); }).toList(); _exercises = await database.select(database.exercises).get(); notifyListeners(); } Future createPlan(String name) async { final id = DateTime.now().toIso8601String(); await database .into(database.trainingPlans) .insert( TrainingPlansCompanion.insert( id: id, name: name, sections: const Value('[]'), ), ); await _loadData(); return _plans.firstWhere((p) => p.id == id); } Future updatePlan(TrainingPlanModel plan) async { await (database.update( database.trainingPlans, )..where((t) => t.id.equals(plan.id))).write( TrainingPlansCompanion( name: Value(plan.name), sections: Value( jsonEncode(plan.sections.map((s) => s.toJson()).toList()), ), ), ); await _loadData(); } Future deletePlan(String id) async { await (database.delete( database.trainingPlans, )..where((t) => t.id.equals(id))).go(); await _loadData(); } Future addExercise( String name, String instructions, String tags, String videoUrl, ) async { final id = DateTime.now().toIso8601String(); await database .into(database.exercises) .insert( ExercisesCompanion.insert( id: id, name: name, instructions: Value(instructions), tags: Value(tags), // Storing as JSON string videoUrl: Value(videoUrl), ), ); await _loadData(); return _exercises.firstWhere((e) => e.id == id); } Future updateExercise(Exercise exercise) async { await (database.update( database.exercises, )..where((t) => t.id.equals(exercise.id))).write( ExercisesCompanion( name: Value(exercise.name), instructions: Value(exercise.instructions), tags: Value(exercise.tags), videoUrl: Value(exercise.videoUrl), ), ); await _loadData(); } Future deleteExercise(String id) async { await (database.delete( database.exercises, )..where((t) => t.id.equals(id))).go(); await _loadData(); } }