import 'dart:convert'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:http/http.dart' as http; import 'package:responsive_builder/responsive_builder.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../config/apiUrl.dart'; import '../../routes/custom_appBar.dart'; import '../../routes/custom_drawer.dart'; import '../../services/apiService.dart'; import '../../utils/auth_utils.dart'; import '../../utils/pagination.dart'; import '../../widgets/custom_breadcrumb_navigation.dart'; import 'travellerDetails.dart'; class TravellerList extends StatefulWidget { const TravellerList({super.key}); @override TravellerListState createState() => TravellerListState(); } class TravellerListState extends State { final GlobalKey travellerListKey = GlobalKey(); final ApiService apiService = ApiService(); Future>? futureTraveller; // late Future> futureTraveller; late Map depSingleData; String? selectedTravellerId; String? orgId; Color? layoutColor; Color? bodyColor; List allTraveller = []; List filteredTraveller = []; TextEditingController searchController = TextEditingController(); int currentPage = 0; int itemsPerPage = 10; @override void initState() { super.initState(); _checkAuthAndLoadData(); // futureTraveller = fetchGetTraveller(); // // futureTraveller.then((object) { // setState(() { // allTraveller = object; // }); // }); // // WidgetsBinding.instance.addPostFrameCallback((_) { // loadInitialData(); // }); // futurePlans = fetchPlans(); } void _checkAuthAndLoadData() async { final String? token = await getToken(); // Your async function to get token if (token == null || token.isEmpty) { // Token doesn't exist → redirect to login context.go( "/", ); // or use: router.go("/") if you're using `GoRouter` directly return; } if (!mounted) return; try { futureTraveller = fetchGetTraveller(); futureTraveller?.then((object) { setState(() { allTraveller = object; }); }); WidgetsBinding.instance.addPostFrameCallback((_) { loadInitialData(); }); } catch (e) { print("group : $e"); } } void loadInitialData() async { String? layoutString = await getLayoutColor(); String? bodyStringColor = await getBodyColor(); setState(() { layoutColor = layoutString != null ? Color(int.parse(layoutString)) : Colors.redAccent; bodyColor = bodyStringColor != null ? Color(int.parse(bodyStringColor)) : Colors.white; }); } Future getToken() async { final prefs = await SharedPreferences.getInstance(); return prefs.getString('auth_token'); } Future> refreshData() { print("Calling Refresh Data"); futureTraveller = fetchGetTraveller(); return futureTraveller!.then((object) { print("Calling Refresh Data $object"); setState(() { allTraveller = object; filteredTraveller = object; searchController.text = ""; }); return object; }); } Future> fetchGetTraveller() async { // return []; String? ordId = await getOrgId(); final String apiUrlData = '$apiUrl/api/travellers?for=table_view&org_id=$ordId'; final String? token = await getToken(); print("Fetch Traveller"); print("2KN Here : $token"); if (token == null) { throw Exception('Token not found. Please log in.'); } final response = await http.get( Uri.parse(apiUrlData), headers: { 'Authorization': 'Bearer $token', 'Content-Type': 'application/json', 'app-signature': 'ts-traveltool-2025-signature-123456', }, ); print("called api : $apiUrlData"); if (response.statusCode == 200) { final data = json.decode(response.body); return data['data']; // Returning raw JSON list } else if (response.statusCode == 403) { print("403-FORB"); await apiService.logout(context); return []; // throw Exception('Failed to load users'); } else { throw Exception('Failed to load users'); } } void filterTraveller(String query) { // print("all before filtering: $query"); // final lowerQuery = query.toLowerCase(); // setState(() { // filteredTraveller = allTraveller.where((object) { // return (object['traveller_id']?.toLowerCase().contains(lowerQuery) ?? // false) || // (object['description']?.toLowerCase().contains(lowerQuery) ?? false) || // (object['user']?.toLowerCase().contains(lowerQuery) ?? false) || // (object['is_active']?.toLowerCase().contains(lowerQuery) ?? false); // }).toList(); // }); // print("filteredPlans: $filteredTraveller"); final lowerQuery = query.toLowerCase().trim(); setState(() { filteredTraveller = allTraveller.where((object) { final travellerId = object['traveller_id']?.toLowerCase() ?? ''; final firstName = object['first_name']?.toLowerCase() ?? ''; final lastName = object['last_name']?.toLowerCase() ?? ''; final fullName = '$firstName $lastName'; final mobile = object['mobile']?.toLowerCase() ?? ''; final email = object['email']?.toLowerCase() ?? ''; final isActiveStatus = object['is_active'] == "1" ? "active" : "inactive"; return travellerId.contains(lowerQuery) || firstName.contains(lowerQuery) || lastName.contains(lowerQuery) || fullName.contains(lowerQuery) || mobile.contains(lowerQuery) || email.contains(lowerQuery) || isActiveStatus.contains(lowerQuery); }).toList(); currentPage = 0; }); print("filteredTraveller: $filteredTraveller"); } @override Widget build(BuildContext context) { return ResponsiveBuilder( builder: (context, sizingInfo) { bool isDesktop = sizingInfo.deviceScreenType == DeviceScreenType.desktop; return Scaffold( backgroundColor: Color(0xFFf5f5f5), // appBar: isDesktop ? null : const CustomAppBar(title: 'User Management'), // drawer: isDesktop ? null : CustomDrawer(isDesktop: false), appBar: CustomAppBar(isDesktop: isDesktop), drawer: CustomDrawer(isDesktop: false), body: Padding( padding: isDesktop ? EdgeInsets.symmetric( horizontal: MediaQuery.of(context).size.width * 0.1, // 30% of screen width as horizontal padding vertical: MediaQuery.of(context).size.height * 0, // 5% of screen height as vertical padding ) : EdgeInsets.all(0), child: Row( children: [ // if (isDesktop) CustomDrawer(isDesktop: true), // const Expanded(child: Center(child: Text("User Page Content"))), Expanded(child: buildGroupList(isDesktop)), ], ), ), ); }, ); } Widget buildGroupList(bool isDesktop) { return Container( margin: isDesktop ? const EdgeInsets.only(top: 10.0, bottom: 10.0) : null, padding: const EdgeInsets.all(1), decoration: BoxDecoration( color: isDesktop ? Colors.white : Color(0xFFFCFCFC), ), // decoration: BoxDecoration( // // color: Colors.amber, // // color: bodyColor, // color: Color(0xFFE1F5FE), // border: Border.all( // color: Colors.white, // // color: Color(0xFFF7F7FB), // width: 3.5)), child: buildUserTable(isDesktop), ); } Widget buildUserTable(bool isDesktop) { return Container( // margin: isDesktop // ? EdgeInsets.all(10.0) // : EdgeInsets.only(left: 20.0, bottom: 20.0, top: 10.0, right: 20.0), // padding: const EdgeInsets.all(10), height: isDesktop ? MediaQuery.of(context).size.height * 0.98 : MediaQuery.of(context).size.height, child: Padding( padding: const EdgeInsets.all(10.0), child: Container( color: Colors.white, padding: const EdgeInsets.all(10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // Divider( // thickness: 0.2, // how "thick" the line is // color: Colors.grey, // optional // ), Row( // mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ // Left side: Breadcrumb inside a Container (optional) Container( child: BreadcrumbNavigation( isDesktop: isDesktop, breadcrumbItems: [ BreadcrumbItem( title: 'Org Settings', tooltip: 'Go To Organization Settings', onTap: (context) { context.go("/OrganizationSettings"); }, ), BreadcrumbItem(title: 'Traveller Details'), ], ), ), // Text( // 'Traveller Details', // style: GoogleFonts.poppins( // fontSize: isDesktop ? 16 : 14, // fontWeight: FontWeight.w600, // color: Colors.black, // ), // ), ], ), if (isDesktop) SizedBox(width: MediaQuery.of(context).size.width * 0.10), // SizedBox(width: MediaQuery.of(context).size.width * 0.16), if (isDesktop) Container( width: MediaQuery.of(context).size.width * 0.2, height: 40, child: TextField( controller: searchController, onChanged: filterTraveller, decoration: InputDecoration( hintText: "Search ...", hintStyle: TextStyle( fontSize: 12, color: Color(0xFF9E9DBD), ), prefixIcon: Icon( Icons.search, color: Color(0xFF9E9DBD), size: 18, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(12), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(12), borderSide: BorderSide( color: Colors.grey.shade200, width: 0.5, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(12), borderSide: BorderSide( color: Colors.grey.shade300, width: 1, ), ), ), style: GoogleFonts.poppins(fontSize: 12), ), ), // SizedBox(width: 16), Spacer(), ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Color(0xFF114D8B), foregroundColor: Colors.white, disabledBackgroundColor: Color(0xFF114D8B), disabledForegroundColor: Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), side: BorderSide(color: Color(0xFF114D8B), width: 2), ), padding: EdgeInsets.symmetric( horizontal: 20, vertical: 12, ), ), onPressed: () async { showDialog( context: context, builder: (context) => TravellerData( isDesktop: isDesktop, layoutColor: layoutColor!, fetchGetTraveller: refreshData, // role: // "Travel Agent" ), ); }, child: Row( mainAxisSize: MainAxisSize.min, // Ensures content fits nicely children: [ Text( "Add Traveller", style: GoogleFonts.poppins( fontSize: isDesktop ? 13 : 11, ), ), SizedBox(width: 8), // spacing between icon and text Icon( Icons.add_circle_outline_rounded, size: 15, color: Colors.white, ), ], ), ), ], ), if (!isDesktop) SizedBox(height: 5), isDesktop ? SizedBox.shrink() : Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Container( width: MediaQuery.of(context).size.width * 0.8, height: 35, child: TextField( controller: searchController, onChanged: filterTraveller, decoration: InputDecoration( hintText: "Search ...", hintStyle: TextStyle( fontSize: 12, color: Color(0xFF9E9DBD), ), prefixIcon: Icon( Icons.search, color: Color(0xFF9E9DBD), size: 18, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(12), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(12), borderSide: BorderSide( color: Colors.grey.shade200, width: 0.5, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(12), borderSide: BorderSide( color: Colors.grey.shade300, width: 1, ), ), ), style: GoogleFonts.poppins(fontSize: 12), ), ), // SizedBox(width: 16), ], ), const SizedBox(height: 10), FutureBuilder>( future: futureTraveller, builder: (context, snapshot) { final adjHgt = MediaQuery.of(context).size.height; if (futureTraveller == null) { return const Center(child: CircularProgressIndicator()); } if (snapshot.connectionState == ConnectionState.waiting) { return const Center(child: CircularProgressIndicator()); } else if (snapshot.hasError || !snapshot.hasData || snapshot.data!.isEmpty) { return Center( child: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisSize: MainAxisSize.min, children: [ SizedBox(height: adjHgt / 4), Text( "No Data Found ", textAlign: TextAlign.center, style: GoogleFonts.poppins( fontSize: 20, fontWeight: FontWeight.bold, color: Colors.grey, ), ), const SizedBox(height: 20), // Text( // "Please Create Traveller Details", // textAlign: TextAlign.center, // style: GoogleFonts.poppins( // fontSize: 16, // color: Colors.grey, // ), // ), // const SizedBox(height: 20), ], ), ), ); } /* Here collect the list to displayed the data in table or card Used */ List object = filteredTraveller.isNotEmpty ? filteredTraveller : allTraveller; /* List is Sorting here */ object.sort((a, b) { DateTime dateA = DateTime.parse(a['created_on']); DateTime dateB = DateTime.parse(b['created_on']); return dateB.compareTo(dateA); // Descending: newest first }); /* For pagination for list ... */ List paginatedTraveller = object .skip(currentPage * itemsPerPage) .take(itemsPerPage) .toList(); /* Table ... */ Widget table = LayoutBuilder( builder: (context, constraints) { double minWidth = isDesktop ? constraints.maxWidth : 1300; return ConstrainedBox( constraints: BoxConstraints(minWidth: minWidth), child: DataTable( dividerThickness: 0.5, columnSpacing: isDesktop ? 24.0 : 16.0, border: TableBorder( horizontalInside: BorderSide( width: 0.5, color: Colors.grey.shade200, ), ), columns: [ DataColumn( label: Text( 'Name', style: GoogleFonts.poppins( fontSize: 13, fontWeight: FontWeight.w600, ), ), ), DataColumn( label: Text( 'Email', style: GoogleFonts.poppins( fontSize: 13, fontWeight: FontWeight.w600, ), ), ), DataColumn( label: Text( 'Mobile', style: GoogleFonts.poppins( fontSize: 13, fontWeight: FontWeight.w600, ), ), ), DataColumn( label: Text( 'Status', style: GoogleFonts.poppins( fontSize: 13, fontWeight: FontWeight.w600, ), ), ), DataColumn( label: Text( 'Actions', style: GoogleFonts.poppins( fontSize: 13, fontWeight: FontWeight.w600, ), ), ), ], rows: paginatedTraveller.map((tableObject) { String fullName = '${tableObject['first_name'] ?? ''} ${tableObject['last_name'] ?? ''}'; String travellerId = tableObject['traveller_id'] .toString(); // Get user ID bool isSelected = selectedTravellerId == travellerId; return DataRow( cells: [ DataCell( Text( fullName ?? 'N/A', style: TextStyle( fontSize: 13, fontFamily: "Inter", ), ), ), DataCell( Text( tableObject['email'] ?? 'N/A', style: TextStyle( fontSize: 13, fontFamily: "Inter", ), softWrap: true, overflow: TextOverflow.ellipsis, ), ), DataCell( Text( tableObject['mobile'] ?? 'N/A', style: TextStyle( fontSize: 13, fontFamily: "Inter", ), softWrap: true, overflow: TextOverflow.ellipsis, ), ), DataCell( Text( tableObject['is_active'] == "1" ? 'Active' : 'Inactive', style: TextStyle( fontSize: 13, fontFamily: "Inter", color: tableObject['is_active'] == "1" ? Colors.green : Colors.grey, ), softWrap: true, overflow: TextOverflow.ellipsis, ), ), DataCell( GestureDetector( child: Image.asset( 'assets/images/IconsImg/edit.png', width: 20, height: 15, ), onTap: () async { // final userId = getUserId(user['user_id']); // final usersData = await getUserDetails(userId); // final travellerId = int.tryParse( tableObject['traveller_id'] .toString(), ); if (travellerId != null) { print( "Table cell - traveller Id -- $travellerId", ); final data = await apiService .getTravellerDetailsFind( context, travellerId, ); print("TravellerId -- $data"); showDialog( context: context, builder: (context) => TravellerData( isDesktop: isDesktop, travellerId: travellerId, // Pass the ID travellerData: data, layoutColor: layoutColor!, fetchGetTraveller: refreshData, // role: // "Travel Agent" ), ); } else { print("Invalid ID"); } }, ), ), ], ); }).toList(), ), ); }, ); /* Card ... */ Widget buildMobileCardView(List paginatedUser) { return ListView.builder( itemCount: paginatedUser.length, itemBuilder: (context, index) { final cardObject = paginatedUser[index]; String fullName = '${cardObject['first_name'] ?? ''} ${cardObject['last_name'] ?? ''}'; return Card( color: Colors.white, margin: EdgeInsets.symmetric( horizontal: 12, vertical: 6, ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), elevation: 3, child: Padding( padding: const EdgeInsets.all(12.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Status and Employee Code Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( fullName ?? 'N/A', style: GoogleFonts.poppins( fontSize: 10, color: Colors.black87, fontWeight: FontWeight.w700, ), ), GestureDetector( child: Image.asset( 'assets/images/IconsImg/edit.png', width: 20, height: 15, ), onTap: () async { // final userId = getUserId(user['user_id']); // final usersData = await getUserDetails(userId); // final travellerId = int.tryParse( cardObject['traveller_id'].toString(), ); if (travellerId != null) { print("travellerId -- $travellerId"); final data = await apiService .getTravellerDetailsFind( context, travellerId, ); print("TravellerId -- $data"); showDialog( context: context, builder: (context) => TravellerData( isDesktop: isDesktop, travellerId: travellerId, // Pass the ID travellerData: data, layoutColor: layoutColor!, // fetchGetTraveller: fetchGetTraveller, fetchGetTraveller: refreshData, // role: // "Travel Agent" ), ); } else { print("Invalid ID"); } }, ), ], ), SizedBox(height: 2), // Trip Id and Trip Name // Name Row( children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '${cardObject['email'] ?? 'N/A'}', style: GoogleFonts.poppins( fontSize: 10, color: Colors.black87, ), ), ], ), SizedBox(width: 10), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '${cardObject['mobile'] ?? 'N/A'}', style: GoogleFonts.poppins( fontSize: 10, color: Colors.black87, ), ), ], ), ], ), // Actions // Actions ], ), ), ); }, ); } return Expanded( child: Column( // mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( child: isDesktop ? (searchController.text.isNotEmpty && filteredTraveller.isEmpty ? Center( child: Text( "No Matches Found", style: GoogleFonts.poppins( fontSize: 14, color: Colors.grey, ), ), ) : SingleChildScrollView( scrollDirection: Axis.vertical, child: table, )) : (searchController.text.isNotEmpty && filteredTraveller.isEmpty ? Center( child: Text( "No Matches Found", style: GoogleFonts.poppins( fontSize: 14, color: Colors.grey, ), ), ) : buildMobileCardView( paginatedTraveller, )), ), // Expanded( // child: isDesktop // ? SingleChildScrollView( // scrollDirection: Axis.vertical, // child: table, // <-- your existing table // ) // : buildMobileCardView(paginatedTraveller), // ), PaginationControls( currentPage: currentPage, itemsPerPage: itemsPerPage, totalItems: object.length, activeColor: layoutColor, // your theme color onPageChanged: (page) { setState(() { currentPage = page; }); }, onItemsPerPageChanged: (items) { setState(() { itemsPerPage = items; currentPage = 0; }); }, ), ], ), ); }, ), ], ), ), ), ); } }