import 'dart:io'; import 'package:intl/intl.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:quantity_input/quantity_input.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:youmazgestion/Views/particles.dart' show ParticleBackground; import 'package:youmazgestion/Views/produitsCard.dart'; import 'Components/appDrawer.dart'; import 'Components/app_bar.dart'; import 'Components/cartItem.dart'; import 'Models/produit.dart'; import 'Services/OrderDatabase.dart'; import 'Services/productDatabase.dart'; import 'Views/ticketPage.dart'; import 'controller/userController.dart'; import 'my_app.dart'; import 'Services/workDatabase.dart'; class AccueilPage extends StatefulWidget { const AccueilPage({super.key}); @override _AccueilPageState createState() => _AccueilPageState(); } class _AccueilPageState extends State { final UserController userController = Get.put(UserController()); final ProductDatabase productDatabase = ProductDatabase(); late Future>> productsFuture; final OrderDatabase orderDatabase = OrderDatabase.instance; final WorkDatabase workDatabase = WorkDatabase.instance; String? username; String? role; DateTime? startDate; int orderId = 0; List selectedProducts = []; int selectedQuantity = 1; double totalCartPrice = 0; double amountPaid = 0; @override void initState() { super.initState(); initorder(); initwork(); loadUserData(); productsFuture = _initDatabaseAndFetchProducts(); _initializeRegister(); super.initState(); _initializeDatabases(); loadUserData(); productsFuture = _initDatabaseAndFetchProducts(); } Future _initializeDatabases() async { await orderDatabase.initDatabase(); await workDatabase.initDatabase(); // Attendre l'initialisation complète await _initializeRegister(); } Future _initializeRegister() async { if (!MyApp.isRegisterOpen) { setState(() { MyApp.isRegisterOpen = true; String formattedDate = DateFormat('yyyy-MM-dd').format(DateTime.now()); startDate = DateFormat('yyyy-MM-dd').parse(formattedDate); MyApp.startDate = startDate; workDatabase.insertDate(formattedDate); }); } } Future loadUserData() async { final prefs = await SharedPreferences.getInstance(); setState(() { username = prefs.getString('username') ?? 'Nom inconnu'; role = prefs.getString('role') ?? 'Rôle inconnu'; }); } Future saveOrderToDatabase() async { final totalPrice = calculateTotalPrice(); final dateTime = DateTime.now().toString(); String user = userController.username; orderId = await orderDatabase.insertOrder( totalPrice, dateTime, MyApp.startDate!, user); for (final cartItem in selectedProducts) { final product = cartItem.product; final quantity = cartItem.quantity; final price = product.price * quantity; await orderDatabase.insertOrderItem( orderId, product.name, quantity, price); final updatedStock = product.stock! - quantity; await productDatabase.updateStock(product.id!, updatedStock); } showTicketPage(); } Future>> _initDatabaseAndFetchProducts() async { await productDatabase.initDatabase(); final categories = await productDatabase.getCategories(); final productsByCategory = >{}; categories.sort(); for (final categoryName in categories) { final products = await productDatabase.getProductsByCategory(categoryName); productsByCategory[categoryName] = products; } return productsByCategory; } void initorder() async { await orderDatabase.initDatabase(); } void initwork() async { await workDatabase.initDatabase(); } double calculateTotalPrice() { double totalPrice = 0; for (final cartItem in selectedProducts) { totalPrice += cartItem.product.price * cartItem.quantity; } return totalPrice; } void addToCartWithDetails(Product product, int quantity) { setState(() { final existingCartItem = selectedProducts.firstWhere( (cartItem) => cartItem.product.id == product.id, orElse: () => CartItem(product, 0), ); if (existingCartItem.quantity == 0) { selectedProducts.add(CartItem(product, quantity)); } else { existingCartItem.quantity += quantity; } }); Get.snackbar( 'Produit ajouté', '${product.name} (x$quantity) ajouté au panier', snackPosition: SnackPosition.TOP, duration: const Duration(seconds: 1), backgroundColor: Colors.green, colorText: Colors.white, ); } void showTicketPage() { final double totalCartPrice = calculateTotalPrice(); if (selectedProducts.isNotEmpty) { if (amountPaid >= totalCartPrice) { Get.offAll(TicketPage( businessName: 'Youmaz', businessAddress: 'quartier escale, Diourbel, Sénégal, en face de Sonatel', businessPhoneNumber: '77 446 92 68', cartItems: selectedProducts, totalCartPrice: totalCartPrice, amountPaid: amountPaid, )); } else { Get.snackbar( 'Paiement incomplet', 'Le montant payé est insuffisant.', snackPosition: SnackPosition.BOTTOM, duration: const Duration(seconds: 3), backgroundColor: Colors.red, colorText: Colors.white, ); } } else { Get.snackbar( 'Panier vide', 'Ajoutez des produits avant de passer commande.', snackPosition: SnackPosition.BOTTOM, duration: const Duration(seconds: 3), backgroundColor: Colors.red, colorText: Colors.white, ); } } @override @override Widget build(BuildContext context) { return Scaffold( appBar: CustomAppBar( title: "Accueil", subtitle: Text('Bienvenue $username ! (Rôle: $role)'), ), drawer: CustomDrawer(), body: ParticleBackground( child: Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [Colors.white, Color.fromARGB(255, 4, 54, 95)]), ), child: FutureBuilder>>( future: productsFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Center(child: CircularProgressIndicator()); } else if (snapshot.hasError) { return const Center(child: Text("Erreur de chargement")); } else if (snapshot.hasData) { final productsByCategory = snapshot.data!; final categories = productsByCategory.keys.toList(); return Row( children: [ Expanded( flex: 3, child: ListView.builder( itemCount: categories.length, itemBuilder: (context, index) { final category = categories[index]; final products = productsByCategory[category]!; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Center( child: Padding( padding: const EdgeInsets.all(10.0), child: Text( category, style: const TextStyle( fontSize: 22, fontWeight: FontWeight.bold, ), ), ), ), GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 4, childAspectRatio: 1, ), shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: products.length, itemBuilder: (context, index) { final product = products[index]; return ProductCard( product: product, onAddToCart: (product, quantity) { addToCartWithDetails(product, quantity); }, ); }, ), ], ); }, ), ), Expanded( flex: 1, child: Container( decoration: BoxDecoration( color: Colors.grey[200], borderRadius: const BorderRadius.only( topLeft: Radius.circular(20), bottomLeft: Radius.circular(20), ), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.1), blurRadius: 10, spreadRadius: 2, ), ], ), padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const Text( 'Panier', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), textAlign: TextAlign.center, ), const SizedBox(height: 16), Expanded( child: selectedProducts.isEmpty ? const Center( child: Text( "Votre panier est vide", style: TextStyle(fontSize: 16), ), ) : ListView.builder( itemCount: selectedProducts.length, itemBuilder: (context, index) { final cartItem = selectedProducts[index]; return Card( margin: const EdgeInsets.symmetric( vertical: 4), child: ListTile( title: Text( cartItem.product.name, style: const TextStyle( fontWeight: FontWeight.bold), ), subtitle: Text( '${NumberFormat('#,##0').format(cartItem.product.price)} FCFA x ${cartItem.quantity}', style: const TextStyle( fontSize: 14), ), trailing: IconButton( icon: const Icon(Icons.delete, color: Colors.red), onPressed: () { setState(() { selectedProducts .removeAt(index); }); }, ), ), ); }, ), ), const Divider(thickness: 1), Padding( padding: const EdgeInsets.symmetric(vertical: 8), child: Text( 'Total: ${NumberFormat('#,##0.00').format(calculateTotalPrice())} FCFA', style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), textAlign: TextAlign.center, ), ), TextField( keyboardType: TextInputType.number, decoration: InputDecoration( labelText: 'Montant payé', border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), filled: true, fillColor: Colors.white, ), onChanged: (value) { amountPaid = double.tryParse(value) ?? 0; }, ), const SizedBox(height: 16), ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.green, padding: const EdgeInsets.symmetric(vertical: 16), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), onPressed: saveOrderToDatabase, child: const Text( 'Valider la commande', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white), ), ), ], ), ), ), ], ); } else { return const Center(child: Text("Aucun produit disponible")); } }, ), ), ), ); } }