import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import 'package:pocketbase/pocketbase.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:uae_stat/config/api_config.dart'; import 'package:uae_stat/infrastructure/data/p_auth_repo.dart'; import 'package:uae_stat/domain/entities/session_entity.dart'; import 'package:uae_stat/presentation/components/indicators/locale_provider.dart'; import 'package:url_launcher/url_launcher.dart'; class SessionCheckScreen extends ConsumerStatefulWidget { @override _SessionCheckScreenState createState() => _SessionCheckScreenState(); } class _SessionCheckScreenState extends ConsumerState { final pb = PocketBase(apiUrl); final PAuthRepo _authRepo = PAuthRepo(); dynamic preferredLanguage; bool _isLoading = true; String get playStoreUrl => "https://play.google.com/store/apps/details?id=ae.gov.fcsc.frontend"; @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((_) async { await userDetails(); _checkSession(); }); } Future userDetails() async { try { final prefs = await SharedPreferences.getInstance(); final userId = prefs.getString('userId'); // Authenticate admin d final adminAuth = await pb.admins.authWithPassword( 'pb@venbainfotech.com', 'pb@venbainfotech.com', ); final String adminToken = adminAuth.token; print('adminToken: $adminToken'); // Fetch user details final userDetailsResponse = await pb.collection('users').getOne( userId!, headers: { 'Authorization': 'Bearer $adminToken', }, ); print('userDetailsLogin: $userDetailsResponse'); preferredLanguage = userDetailsResponse.data['language'] ?? ''; print('preferredLanguage login $preferredLanguage'); // **Set Default Locale in Provider** if (preferredLanguage == 'ar') { ref.read(localeProvider.notifier).setLocale(const Locale('ar')); } else { ref.read(localeProvider.notifier).setLocale(const Locale('en')); } } catch (e) { print('Error fetching user details: $e'); rethrow; } } Future _checkSession() async { await Future.delayed(Duration(seconds: 2)); // Optional splash delay final SessionEntity? session = await _authRepo.fetchLocallyStored(); final GoRouterState state = GoRouterState.of(context); final String? intendedPath = state.uri.toString().isNotEmpty && state.uri.path != '/' ? state.uri.path : null; print('fetchLocallyStored $session'); print('navigating to intended path: $intendedPath'); // First if: Check if app data exists (indicating app setup) if (session != null) { // Second if: Check if user is logged in (session is valid) if (session.freshness != SessionFreshness.expired) { // User is logged in, check for shared intent path if (intendedPath != null) { print('navigating to intended path: $intendedPath'); if (mounted) { context.go(intendedPath); } } else { print('myhomepage'); if (mounted) { context.go('/myhomepage'); // Redirect to home } } } else { // User is not logged in, redirect to login with intended path if present print('session expired, redirecting to login'); if (mounted) { context.go('/login', extra: intendedPath != null ? {'intendedPath': intendedPath} : null); } } } else { // No session data, redirect to Play Store print('no session data, redirecting to play store'); if (mounted) { _redirectToPlayStore(); } } setState(() { _isLoading = false; // Stop showing splash }); } Future _redirectToPlayStore() async { final Uri url = Uri.parse(playStoreUrl); if (await canLaunchUrl(url)) { await launchUrl(url, mode: LaunchMode.externalApplication); } } @override Widget build(BuildContext context) { return _isLoading ? SplashScreen() // Show splash while loading : SizedBox.shrink(); } } class SplashScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset('assets/images/logo.png', width: 150), // App Logo // SizedBox(height: 20), // CircularProgressIndicator(), // Loading indicator ], ), ), ); } } // import 'dart:math'; // // import 'package:flutter/material.dart'; // import 'package:go_router/go_router.dart'; // import 'package:flutter_secure_storage/flutter_secure_storage.dart'; // import 'package:uae_stat/infrastructure/data/p_auth_repo.dart'; // import 'package:url_launcher/url_launcher.dart'; // // class AuthRepository { // final FlutterSecureStorage _secureStorage = const FlutterSecureStorage(); // // Future fetchLocallyStored() async { // return await _secureStorage.read(key: "FlutterSecureStorage.session"); // } // } // // class SessionCheckScreen extends StatefulWidget { // const SessionCheckScreen({Key? key}) : super(key: key); // // @override // _SessionCheckScreenState createState() => _SessionCheckScreenState(); // } // // class _SessionCheckScreenState extends State { // final PAuthRepo _pAuthRepo = PAuthRepo(); // final AuthRepository _authRepo = AuthRepository(); // final String playStoreUrl = "https://play.google.com/store/apps/details?id=ae.gov.fcsc.frontend"; // // @override // void initState() { // super.initState(); // WidgetsBinding.instance.addPostFrameCallback((_) { // _checkSessionAndHandleLink(); // }); // } // // Future _checkSessionAndHandleLink() async { // try { // final session = await _authRepo.fetchLocallyStored(); // // // Check if user is not logged in // if (session == null || session.isEmpty) { // _handleUnauthenticatedUser(); // return; // } // // // User is authenticated, process the shared link // final GoRouterState state = GoRouterState.of(context); // final String? sharedLink = state.uri.toString().isNotEmpty && state.uri.path != '/' // ? state.uri.toString() // : null; // // print(sharedLink); // // if (sharedLink != null) { // // Validate if the link is a valid app route // final Uri parsedUri = Uri.parse(sharedLink); // final String path = parsedUri.path; // // if (mounted) { // GoRouter.of(context).go(path); // } // } else { // // Default route for authenticated users with no specific link // if (mounted) { // GoRouter.of(context).go('/myhomepage'); // } // } // } catch (e) { // print("Error processing link: $e"); // _handleUnauthenticatedUser(); // } // } // // void _handleUnauthenticatedUser() { // final GoRouterState state = GoRouterState.of(context); // final String? sharedLink = state.uri.toString().isNotEmpty && state.uri.path != '/' // ? state.uri.toString() // : null; // // if (sharedLink != null) { // // Store the intended destination and redirect to login // if (mounted) { // GoRouter.of(context).go('/login', extra: {'redirectTo': sharedLink}); // } // } else { // // No specific link, just go to login // if (mounted) { // GoRouter.of(context).go('/login'); // } // } // } // // Future _redirectToPlayStore() async { // final Uri url = Uri.parse(playStoreUrl); // // if (await canLaunchUrl(url)) { // await launchUrl(url, mode: LaunchMode.externalApplication); // } // } // // @override // Widget build(BuildContext context) { // return const Scaffold( // body: Center( // child: CircularProgressIndicator(), // ), // ); // } // } // // // import 'package:flutter/material.dart'; // // import 'package:go_router/go_router.dart'; // // import 'package:flutter_secure_storage/flutter_secure_storage.dart'; // // import 'package:uae_stat/infrastructure/data/p_auth_repo.dart'; // // import 'package:url_launcher/url_launcher.dart'; // // // // class AuthRepository { // // final FlutterSecureStorage _secureStorage = const FlutterSecureStorage(); // // // // Future fetchLocallyStored() async { // // return await _secureStorage.read(key: "FlutterSecureStorage.session"); // // } // // } // // // // class SessionCheckScreen extends StatefulWidget { // // const SessionCheckScreen({Key? key}) : super(key: key); // // // // @override // // _SessionCheckScreenState createState() => _SessionCheckScreenState(); // // } // // // // class _SessionCheckScreenState extends State { // // final PAuthRepo _pAuthRepo = PAuthRepo(); // // final AuthRepository _authRepo = AuthRepository(); // // final String playStoreUrl = "https://play.google.com/store/apps/details?id=ae.gov.fcsc.frontend"; // // // // @override // // void initState() { // // super.initState(); // // WidgetsBinding.instance.addPostFrameCallback((_) { // // _checkSessionAndHandleLink(); // // }); // // } // // // // Future _checkSessionAndHandleLink() async { // // try { // // final session = await _authRepo.fetchLocallyStored(); // // // // // Check if user is not logged in // // if (session == null || session.isEmpty) { // // _handleUnauthenticatedUser(); // // return; // // } // // // // // User is authenticated, process the shared link // // final GoRouterState state = GoRouterState.of(context); // // final String? sharedLink = state.uri.toString().isNotEmpty && state.uri.path != '/' // // ? state.uri.toString() // // : null; // // // // if (sharedLink != null) { // // // Validate if the link is a valid app route // // final Uri parsedUri = Uri.parse(sharedLink); // // final String path = parsedUri.path; // // // // if (mounted) { // // GoRouter.of(context).go(path); // // } // // } else { // // // Default route for authenticated users with no specific link // // if (mounted) { // // GoRouter.of(context).go('/myhomepage'); // // } // // } // // } catch (e) { // // print("Error processing link: $e"); // // _handleUnauthenticatedUser(); // // } // // } // // // // void _handleUnauthenticatedUser() { // // final GoRouterState state = GoRouterState.of(context); // // final String? sharedLink = state.uri.toString().isNotEmpty && state.uri.path != '/' // // ? state.uri.toString() // // : null; // // // // if (sharedLink != null) { // // // Store the intended destination and redirect to login // // if (mounted) { // // GoRouter.of(context).go('/login', extra: {'redirectTo': sharedLink}); // // } // // } else { // // // No specific link, just go to login // // if (mounted) { // // GoRouter.of(context).go('/login'); // // } // // } // // } // // // // Future _redirectToPlayStore() async { // // final Uri url = Uri.parse(playStoreUrl); // // // // if (await canLaunchUrl(url)) { // // await launchUrl(url, mode: LaunchMode.externalApplication); // // } // // } // // // // @override // // Widget build(BuildContext context) { // // return const Scaffold( // // body: Center( // // child: CircularProgressIndicator(), // // ), // // ); // // } // // }