import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:timezone/timezone.dart' as tz; import 'package:timezone/data/latest.dart' as tz; import 'package:flutter_timezone/flutter_timezone.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../services/app_settings.dart'; import '../services/google_calendar_service.dart'; class NotificationService { static final NotificationService _instance = NotificationService._internal(); factory NotificationService() => _instance; NotificationService._internal(); final FlutterLocalNotificationsPlugin _plugin = FlutterLocalNotificationsPlugin(); bool _initialized = false; static const _channel = AndroidNotificationChannel( 'shooting_app_events', 'Event Reminders', description: 'Notifications for upcoming shooting events', importance: Importance.max, playSound: true, enableVibration: true, ); NotificationDetails get _notifDetails => const NotificationDetails( android: AndroidNotificationDetails( 'shooting_app_events', 'Event Reminders', channelDescription: 'Notifications for upcoming shooting events', importance: Importance.max, priority: Priority.high, icon: '@drawable/ic_stat_icon_white', ), iOS: DarwinNotificationDetails( presentAlert: true, presentBadge: true, presentSound: true, ), ); Future initialize() async { if (_initialized) return; _initialized = true; // set early to prevent re-entry try { tz.initializeTimeZones(); final String timezoneName = await FlutterTimezone.getLocalTimezone(); tz.setLocalLocation(tz.getLocation(timezoneName)); } catch (_) {} try { const androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher'); const iosSettings = DarwinInitializationSettings( requestAlertPermission: false, requestBadgePermission: false, requestSoundPermission: false, ); const initSettings = InitializationSettings(android: androidSettings, iOS: iosSettings); await _plugin.initialize(initSettings); final androidPlugin = _plugin.resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>(); await androidPlugin?.createNotificationChannel(_channel); // Permissions are asked only once the club is unlocked: reminders are // a member feature, so other users never see the prompts. } catch (_) {} } // Android 12+ needs "Alarms & reminders" access for on-time delivery // (denied by default on Android 14+). Ask once; without it we fall back // to inexact alarms, which Android may delay by an hour or more. Future _requestExactAlarmsOnce() async { final android = _plugin.resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>(); if (android == null) return; if (await android.canScheduleExactNotifications() ?? true) return; final prefs = await SharedPreferences.getInstance(); if (prefs.getBool('exactAlarmAsked') ?? false) return; await prefs.setBool('exactAlarmAsked', true); await android.requestExactAlarmsPermission(); } Future _scheduleMode() async { final android = _plugin.resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>(); final canExact = await android?.canScheduleExactNotifications() ?? true; return canExact ? AndroidScheduleMode.exactAllowWhileIdle : AndroidScheduleMode.inexactAllowWhileIdle; } /// Fetches the calendar and reschedules all reminders. Call on app start /// and whenever notification settings change. Future rescheduleFromCalendar() async { if (!AppSettings.instance.clubUnlocked) { await cancelAll(); // reminders are a club-member feature return; } try { await requestPermissions(); await _requestExactAlarmsOnce(); } catch (_) {} final service = GoogleCalendarService(); try { final now = DateTime.now(); final events = await service.getEvents( startDate: now, endDate: now.add(const Duration(days: 365)), ); await scheduleEventNotifications(events); } catch (_) { } finally { service.dispose(); } } Future requestPermissions() async { final android = _plugin.resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>(); final ios = _plugin.resolvePlatformSpecificImplementation< IOSFlutterLocalNotificationsPlugin>(); bool granted = false; if (android != null) { granted = await android.requestNotificationsPermission() ?? false; } if (ios != null) { granted = await ios.requestPermissions(alert: true, badge: true, sound: true) ?? false; } return granted; } Future cancelAll() async { await _plugin.cancelAll(); } Future scheduleEventNotifications(List events) async { try { await initialize(); final prefs = await SharedPreferences.getInstance(); final hours = prefs.getInt('notificationHours_single') ?? 1; final notifyDezuranje = prefs.getBool('notifyDezuranje') ?? true; final notifySestanek = prefs.getBool('notifySestanek') ?? true; final notifyTekma = prefs.getBool('notifyTekma') ?? true; final language = prefs.getString('language') ?? 'Slovenian'; final now = DateTime.now(); final mode = await _scheduleMode(); await _plugin.cancelAll(); int notifId = 0; for (final event in events) { if (event.startTime == null) continue; final summary = (event.summary ?? '').toLowerCase(); // Same classification as the calendar screen; skip anything else final isCompetition = summary.contains('liga') || summary.contains('tekmovanje') || summary.contains('tekma'); final isSestanek = !isCompetition && summary.contains('sestanek'); final isDezuranje = !isCompetition && !isSestanek && summary.contains('dežurstvo'); if (!isCompetition && !isSestanek && !isDezuranje) continue; if (isCompetition && !notifyTekma) continue; if (isSestanek && !notifySestanek) continue; if (isDezuranje && !notifyDezuranje) continue; final notifyAt = event.startTime!.subtract(Duration(hours: hours)); if (notifyAt.isAfter(now)) { await _scheduleNotification( id: notifId++, title: event.summary ?? 'Event', body: _startsIn(hours, language), scheduledDate: notifyAt, mode: mode, ); } } } catch (_) {} } static String _startsIn(int hours, String language) { switch (language) { case 'Slovenian': final mod = hours % 100; final unit = mod == 1 ? 'uro' : mod == 2 ? 'uri' : (mod == 3 || mod == 4) ? 'ure' : 'ur'; return 'Začne se čez $hours $unit'; case 'German': return hours == 1 ? 'Beginnt in 1 Stunde' : 'Beginnt in $hours Stunden'; default: return hours == 1 ? 'Starts in 1 hour' : 'Starts in $hours hours'; } } Future _scheduleNotification({ required int id, required String title, required String body, required DateTime scheduledDate, required AndroidScheduleMode mode, }) async { final tzDate = tz.TZDateTime.from(scheduledDate, tz.local); await _plugin.zonedSchedule( id, title, body, tzDate, _notifDetails, androidScheduleMode: mode, uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime, ); } }