package com.example.data.repository import android.content.Context import android.content.SharedPreferences import com.example.data.local.DeliveryRiderDao import com.example.data.local.DeliveryRiderEntity import com.example.data.local.FoodItemDao import com.example.data.local.FoodItemEntity import com.example.data.local.LoveZoneDatabase import com.example.data.local.NotificationDao import com.example.data.local.NotificationEntity import com.example.data.local.OrderDao import com.example.data.local.OrderEntity import com.example.data.local.CartItemDao import com.example.data.local.UserDao import com.example.data.local.UserEntity import com.example.data.model.AdminSettings import com.example.data.model.AppNotification import com.example.data.model.CustomerUser import com.example.data.model.DeliveryRider import com.example.data.model.FoodItem import com.example.data.model.Order import com.example.data.model.OrderItemSummary import com.example.data.model.OrderStatus import com.example.data.model.RiderStatus import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import com.example.data.local.FoodReviewDao import com.example.data.local.FoodReviewEntity import com.example.data.model.FoodReview class LoveZoneRepository( private val foodItemDao: FoodItemDao, private val foodReviewDao: FoodReviewDao, private val orderDao: OrderDao, private val notificationDao: NotificationDao, private val deliveryRiderDao: DeliveryRiderDao, private val userDao: UserDao, private val cartItemDao: CartItemDao, private val context: Context ) { private val prefs: SharedPreferences = context.getSharedPreferences("love_zone_admin_prefs", Context.MODE_PRIVATE) private val userPrefs: SharedPreferences = context.getSharedPreferences("love_zone_user_prefs", Context.MODE_PRIVATE) private val repositoryScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private val _adminSettings = MutableStateFlow(loadAdminSettings()) val adminSettings: StateFlow = _adminSettings.asStateFlow() private val _currentUser = MutableStateFlow(loadCurrentUser()) val currentUser: StateFlow = _currentUser.asStateFlow() val foodItems: Flow> = foodItemDao.getAllFoodItems() .map { list -> list.map { it.toDomain() } } val allOrders: Flow> = orderDao.getAllOrders() .map { list -> list.map { it.toDomain() } } val orders: Flow> = allOrders @OptIn(ExperimentalCoroutinesApi::class) val customerOrders: Flow> = _currentUser .flatMapLatest { user -> val digits = user.phoneDigits if (!user.isLoggedIn || digits.isBlank()) { flowOf(emptyList()) } else { orderDao.getOrdersForCustomer(digits).map { list -> list.map { it.toDomain() } } } } val notifications: Flow> = notificationDao.getAllNotifications() .map { list -> list.map { it.toDomain() } } val riders: Flow> = deliveryRiderDao.getAllRiders() .map { list -> list.map { it.toDomain() } } val allCustomers: Flow> = userDao.getAllUsers() .map { list -> list.map { it.toDomain() } } val allReviews: Flow> = foodReviewDao.getAllReviews() .map { list -> list.map { it.toDomain() } } init { CoroutineScope(Dispatchers.IO).launch { seedInitialDataIfNeeded() } } private suspend fun seedInitialDataIfNeeded() { if (foodItemDao.getCount() < 25) { val initialItems = listOf( // Page 1: Love Zone Special Combos FoodItem( name = "Fried Rice + Chicken Kosha (2 Pcs)", category = "Love Zone Special Combos", price = 199.0, originalPrice = 249.0, description = "Delicious egg-veg fried rice served with 2 pcs Bengali style spicy chicken kosha", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1603133872878-684f208fb84b?w=500", isAvailable = true ), FoodItem( name = "Plain Naan (2 Pcs) + Chicken Butter Masala (2 Pcs)", category = "Love Zone Special Combos", price = 189.0, originalPrice = 239.0, description = "Soft plain tandoori naan (2 pcs) paired with rich boneless chicken butter masala (2 pcs)", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1585937421612-70a008356fbe?w=500", isAvailable = true ), FoodItem( name = "Butter Naan (2 Pcs) + Kadai Chicken (2 Pcs)", category = "Love Zone Special Combos", price = 199.0, originalPrice = 249.0, description = "Butter naan (2 pcs) served with spicy aromatic kadai chicken (2 pcs)", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1603894584373-5ac82b2ae398?w=500", isAvailable = true ), FoodItem( name = "Jeera Rice + Paneer Butter Masala", category = "Love Zone Special Combos", price = 169.0, originalPrice = 219.0, description = "Fragrant cumin basmati rice served with creamy paneer butter masala gravy", isVeg = true, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1631452180519-c014fe946bc7?w=500", isAvailable = true ), FoodItem( name = "Love Zone Special Veg Thali", category = "Love Zone Special Combos", price = 219.0, originalPrice = 269.0, description = "Basmati Rice, Dal Fry, Seasonal Sabzi, Paneer Masala, Salad, Papad & Sweet Gulab Jamun", isVeg = true, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1626777552726-4a6b54c97e46?w=500", isAvailable = true ), FoodItem( name = "Non-Veg Grand Thali", category = "Love Zone Special Combos", price = 249.0, originalPrice = 299.0, description = "Basmati Rice, Dal, Chicken Curry 2 Pcs, Tawa Roti 2 Pcs, Salad, Papad & Sweet Gulab Jamun", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1626777552726-4a6b54c97e46?w=500", isAvailable = true ), FoodItem( name = "Personal Veg Pizza Combo", category = "Love Zone Special Combos", price = 179.0, originalPrice = 229.0, description = "7-inch Veg Supreme Deluxe Pizza + Crispy French Fries + Cold Drink 250ml", isVeg = true, isBestSeller = false, imageUri = "https://images.unsplash.com/photo-1513104890138-7c749659a591?w=500", isAvailable = true ), FoodItem( name = "Chicken Pizza Combo", category = "Love Zone Special Combos", price = 219.0, originalPrice = 279.0, description = "7-inch Chicken Feast Pizza + Crispy French Fries + Cold Drink 250ml", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1513104890138-7c749659a591?w=500", isAvailable = true ), // Page 2: Rice, Biryani, Tarka & Dal FoodItem( name = "Steamed Basmati Rice", category = "Rice & Biryani", price = 60.0, originalPrice = 80.0, description = "Fluffy long grain fragrant steamed basmati rice", isVeg = true, isAvailable = true ), FoodItem( name = "Jeera Rice", category = "Rice & Biryani", price = 80.0, originalPrice = 110.0, description = "Basmati rice tempered with ghee, fresh cumin seeds and coriander", isVeg = true, isAvailable = true ), FoodItem( name = "Veg Fried Rice", category = "Rice & Biryani", price = 110.0, originalPrice = 140.0, description = "Wok-tossed basmati rice with finely chopped carrots, beans & capsicum", isVeg = true, imageUri = "https://images.unsplash.com/photo-1603133872878-684f208fb84b?w=500", isAvailable = true ), FoodItem( name = "Egg Fried Rice", category = "Rice & Biryani", price = 130.0, originalPrice = 160.0, description = "Wok-tossed basmati rice with scrambled eggs and aromatic seasoning", isVeg = false, imageUri = "https://images.unsplash.com/photo-1603133872878-684f208fb84b?w=500", isAvailable = true ), FoodItem( name = "Chicken Fried Rice", category = "Rice & Biryani", price = 150.0, originalPrice = 190.0, description = "Tender shredded chicken wok-tossed with basmati rice and spring onions", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1603133872878-684f208fb84b?w=500", isAvailable = true ), FoodItem( name = "Mixed Fried Rice (Egg & Chicken)", category = "Rice & Biryani", price = 170.0, originalPrice = 210.0, description = "Combination of chicken chunks, scrambled egg & fresh veggies tossed in basmati rice", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1603133872878-684f208fb84b?w=500", isAvailable = true ), FoodItem( name = "Schezwan Chicken Fried Rice", category = "Rice & Biryani", price = 160.0, originalPrice = 200.0, description = "Spicy red schezwan sauce tossed chicken fried rice with red chillies", isVeg = false, isAvailable = true ), FoodItem( name = "Veg Dum Biryani", category = "Rice & Biryani", price = 130.0, originalPrice = 170.0, description = "Aromatic hyderabadi dum cooked basmati rice with veggies & herbs", isVeg = true, imageUri = "https://images.unsplash.com/photo-1563379091339-03b21ab4a4f8?w=500", isAvailable = true ), FoodItem( name = "Egg Biryani (2 Eggs)", category = "Rice & Biryani", price = 140.0, originalPrice = 180.0, description = "Spiced boiled eggs cooked in dum biryani basmati rice with raita", isVeg = false, imageUri = "https://images.unsplash.com/photo-1563379091339-03b21ab4a4f8?w=500", isAvailable = true ), FoodItem( name = "Chicken Dum Biryani (Half - 1 Pc Chicken, 1 Egg)", category = "Rice & Biryani", price = 130.0, originalPrice = 170.0, description = "Dum cooked basmati biryani with 1 tender chicken piece & 1 boiled egg", isVeg = false, isBestSeller = true, imageUri = "img_special_biryani", isAvailable = true ), FoodItem( name = "Chicken Dum Biryani (Full - 2 Pcs Chicken, 1 Egg)", category = "Rice & Biryani", price = 180.0, originalPrice = 240.0, description = "Love Zone Special: 2 succulent chicken pieces, boiled egg & saffron dum basmati rice", isVeg = false, isBestSeller = true, imageUri = "img_special_biryani", isAvailable = true ), FoodItem( name = "Mutton Dum Biryani (Full - 2 Pcs Mutton, 1 Egg)", category = "Rice & Biryani", price = 260.0, originalPrice = 320.0, description = "Slow-cooked tender mutton pieces in fragrant dum biryani rice", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1563379091339-03b21ab4a4f8?w=500", isAvailable = true ), FoodItem( name = "Yellow Dal Fry", category = "Rice & Biryani", price = 90.0, originalPrice = 120.0, description = "Yellow lentils tempered with ghee, cumin, garlic, tomato & cilantro", isVeg = true, isAvailable = true ), FoodItem( name = "Dal Tadka (Butter Fry)", category = "Rice & Biryani", price = 110.0, originalPrice = 140.0, description = "Creamy yellow dal topped with rich butter & red chilli garlic tadka", isVeg = true, isAvailable = true ), FoodItem( name = "Egg Dal Tadka", category = "Rice & Biryani", price = 130.0, originalPrice = 160.0, description = "Spicy dal tadka cooked with scrambled savory egg chunks", isVeg = false, isAvailable = true ), // Page 3: Tandoor, Roti, Naan & Paratha FoodItem( name = "Tawa Roti (Plain)", category = "Tandoor & Roti", price = 12.0, originalPrice = 15.0, description = "Fresh whole wheat tawa roti", isVeg = true, isAvailable = true ), FoodItem( name = "Tawa Butter Roti", category = "Tandoor & Roti", price = 15.0, originalPrice = 20.0, description = "Tawa roti brushed with fresh Amul butter", isVeg = true, isAvailable = true ), FoodItem( name = "Plain Naan", category = "Tandoor & Roti", price = 35.0, originalPrice = 45.0, description = "Soft refined flour naan baked in clay tandoor", isVeg = true, isAvailable = true ), FoodItem( name = "Butter Naan", category = "Tandoor & Roti", price = 45.0, originalPrice = 55.0, description = "Tandoori naan coated with melted butter", isVeg = true, isBestSeller = true, isAvailable = true ), FoodItem( name = "Garlic Butter Naan", category = "Tandoor & Roti", price = 55.0, originalPrice = 70.0, description = "Flavored naan infused with minced garlic & butter", isVeg = true, isBestSeller = true, isAvailable = true ), FoodItem( name = "Cheese Garlic Naan", category = "Tandoor & Roti", price = 75.0, originalPrice = 95.0, description = "Stuffed with mozzarella cheese & minced garlic", isVeg = true, isAvailable = true ), FoodItem( name = "Lachha Paratha", category = "Tandoor & Roti", price = 40.0, originalPrice = 50.0, description = "Multi-layered flaky crispy tandoori paratha", isVeg = true, isAvailable = true ), FoodItem( name = "Aloo Stuffed Paratha (With Curd & Butter)", category = "Tandoor & Roti", price = 60.0, originalPrice = 80.0, description = "Spiced potato stuffed paratha served with fresh curd & butter", isVeg = true, isAvailable = true ), FoodItem( name = "Paneer Stuffed Paratha (With Curd & Butter)", category = "Tandoor & Roti", price = 80.0, originalPrice = 100.0, description = "Grated paneer stuffed paratha served with curd & butter", isVeg = true, isAvailable = true ), FoodItem( name = "Chicken Tandoori (Half - 4 Pcs)", category = "Tandoor & Roti", price = 220.0, originalPrice = 280.0, description = "Charcoal roasted spiced chicken (4 pcs) with mint chutney", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1599487488170-d11ec9c172f0?w=500", isAvailable = true ), FoodItem( name = "Chicken Tandoori (Full - 8 Pcs)", category = "Tandoor & Roti", price = 390.0, originalPrice = 480.0, description = "Full charcoal roasted tandoori chicken (8 pcs) with mint chutney & onion salad", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1599487488170-d11ec9c172f0?w=500", isAvailable = true ), FoodItem( name = "Chicken Tikka (6 Pcs)", category = "Tandoor & Roti", price = 210.0, originalPrice = 260.0, description = "Boneless chicken chunks marinated in yogurt & spices, cooked in tandoor", isVeg = false, imageUri = "https://images.unsplash.com/photo-1599487488170-d11ec9c172f0?w=500", isAvailable = true ), FoodItem( name = "Chicken Reshmi Kebab (6 Pcs)", category = "Tandoor & Roti", price = 230.0, originalPrice = 290.0, description = "Melt-in-mouth cashew & cream marinated tender chicken kebab", isVeg = false, imageUri = "https://images.unsplash.com/photo-1599487488170-d11ec9c172f0?w=500", isAvailable = true ), FoodItem( name = "Paneer Tikka (6 Pcs)", category = "Tandoor & Roti", price = 180.0, originalPrice = 230.0, description = "Cottage cheese cubes with bell peppers marinated & grilled in tandoor", isVeg = true, imageUri = "https://images.unsplash.com/photo-1599487488170-d11ec9c172f0?w=500", isAvailable = true ), // Page 4: Starters & Sharing FoodItem( name = "Veg Crispy Roll (2 Pcs)", category = "Starters & Snacks", price = 90.0, originalPrice = 120.0, description = "Crispy golden fried vegetable rolls with dip", isVeg = true, isAvailable = true ), FoodItem( name = "Veg Manchurian Dry (8 Pcs)", category = "Starters & Snacks", price = 130.0, originalPrice = 160.0, description = "Crispy veggie balls tossed in tangy soya garlic sauce", isVeg = true, isAvailable = true ), FoodItem( name = "Paneer Chilli Dry (8 Pcs)", category = "Starters & Snacks", price = 160.0, originalPrice = 200.0, description = "Crispy cottage cheese cubes tossed with capsicum, onion & green chillies", isVeg = true, isAvailable = true ), FoodItem( name = "Crispy Corn Salt & Pepper", category = "Starters & Snacks", price = 140.0, originalPrice = 180.0, description = "Golden fried sweet corn kernels tossed with black pepper & spring onion", isVeg = true, isAvailable = true ), FoodItem( name = "Chicken 65 (8 Pcs)", category = "Starters & Snacks", price = 180.0, originalPrice = 230.0, description = "Spicy South Indian style fried chicken bites with curry leaves", isVeg = false, imageUri = "https://images.unsplash.com/photo-1562967914-608f82629710?w=500", isAvailable = true ), FoodItem( name = "Chicken Chilli Dry (8 Pcs)", category = "Starters & Snacks", price = 190.0, originalPrice = 240.0, description = "Deep-fried chicken chunks tossed in chili sauce, capsicum & onions", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1562967914-608f82629710?w=500", isAvailable = true ), FoodItem( name = "Chicken Lollipop (6 Pcs)", category = "Starters & Snacks", price = 180.0, originalPrice = 230.0, description = "Frenched chicken winglets fried to perfection, served with schezwan dip", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1562967914-608f82629710?w=500", isAvailable = true ), FoodItem( name = "Drums of Heaven (6 Pcs)", category = "Starters & Snacks", price = 210.0, originalPrice = 260.0, description = "Chicken lollipops tossed in sweet & spicy schezwan garlic glaze", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1562967914-608f82629710?w=500", isAvailable = true ), FoodItem( name = "Crispy Fried Chicken Wings (6 Pcs)", category = "Starters & Snacks", price = 190.0, originalPrice = 240.0, description = "Crunchy breaded chicken wings with fiery mayo dip", isVeg = false, isAvailable = true ), FoodItem( name = "Chicken Pepper Fry", category = "Starters & Snacks", price = 195.0, originalPrice = 250.0, description = "Pan fried chicken seasoned heavily with black pepper & roasted spices", isVeg = false, isAvailable = true ), FoodItem( name = "Love Zone Non-Veg Platter (12 Pcs)", category = "Starters & Snacks", price = 450.0, originalPrice = 550.0, description = "Assorted platter of Tandoori Chicken, Chicken Tikka, Reshmi Kebab & Lollipops", isVeg = false, isBestSeller = true, isAvailable = true ), FoodItem( name = "Love Zone Veg Platter", category = "Starters & Snacks", price = 350.0, originalPrice = 420.0, description = "Paneer Tikka, Veg Manchurian, Crispy Corn & Peri Peri Fries platter", isVeg = true, isAvailable = true ), // Page 5: Main Course FoodItem( name = "Mix Veg Curry", category = "Main Course", price = 130.0, originalPrice = 170.0, description = "Assorted vegetables cooked in North Indian onion tomato gravy", isVeg = true, isAvailable = true ), FoodItem( name = "Kadhai Paneer", category = "Main Course", price = 170.0, originalPrice = 210.0, description = "Cottage cheese & capsicum cooked in coarsely ground kadai masala", isVeg = true, isBestSeller = true, isAvailable = true ), FoodItem( name = "Paneer Butter Masala", category = "Main Course", price = 180.0, originalPrice = 230.0, description = "Rich, sweet and velvety tomato cashew butter gravy with soft paneer", isVeg = true, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1631452180519-c014fe946bc7?w=500", isAvailable = true ), FoodItem( name = "Matar Paneer", category = "Main Course", price = 160.0, originalPrice = 200.0, description = "Green peas and cottage cheese simmered in spiced tomato gravy", isVeg = true, isAvailable = true ), FoodItem( name = "Shahi Paneer", category = "Main Course", price = 190.0, originalPrice = 240.0, description = "Royal white gravy paneer infused with cream, cashew & aromatic spices", isVeg = true, isAvailable = true ), FoodItem( name = "Mushroom Masala", category = "Main Course", price = 180.0, originalPrice = 220.0, description = "Button mushrooms cooked in thick spicy onion gravy", isVeg = true, isAvailable = true ), FoodItem( name = "Chicken Curry / Bengali Home Style (Full - 4 Pcs)", category = "Main Course", price = 200.0, originalPrice = 250.0, description = "Homestyle chicken curry cooked with potatoes in light spicy gravy", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1603894584373-5ac82b2ae398?w=500", isAvailable = true ), FoodItem( name = "Chicken Kosha (Spicy Dark Gravy - 4 Pcs)", category = "Main Course", price = 220.0, originalPrice = 280.0, description = "Authentic Bengali slow-cooked spicy chicken curry in caramelized dark gravy", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1603894584373-5ac82b2ae398?w=500", isAvailable = true ), FoodItem( name = "Chicken Butter Masala (Boneless - 4 Pcs)", category = "Main Course", price = 240.0, originalPrice = 300.0, description = "Tender boneless chicken in buttery creamy rich cashew gravy", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1603894584373-5ac82b2ae398?w=500", isAvailable = true ), FoodItem( name = "Kadhai Chicken (4 Pcs)", category = "Main Course", price = 230.0, originalPrice = 290.0, description = "Chicken pieces tossed with diced capsicum & onions in spicy kadai gravy", isVeg = false, isAvailable = true ), FoodItem( name = "Chicken Do Pyaza (4 Pcs)", category = "Main Course", price = 230.0, originalPrice = 290.0, description = "Delicious chicken curry cooked with double quantity of caramelized onions", isVeg = false, isAvailable = true ), FoodItem( name = "Mutton Curry (Classic Bengali - 4 Pcs)", category = "Main Course", price = 320.0, originalPrice = 390.0, description = "Traditional Bengali style mutton curry with tender potatoes", isVeg = false, isBestSeller = true, isAvailable = true ), FoodItem( name = "Mutton Kosha (Rich Roasted Gravy - 4 Pcs)", category = "Main Course", price = 350.0, originalPrice = 430.0, description = "Rich roasted spicy dark mutton curry simmered for hours", isVeg = false, isBestSeller = true, isAvailable = true ), // Page 6: Noodles, Chowmein, Momos & Soups FoodItem( name = "Veg Chowmein / Noodles", category = "Noodles & Momos", price = 90.0, originalPrice = 120.0, description = "Wok tossed hakka noodles with crisp cabbage, capsicum & carrots", isVeg = true, imageUri = "https://images.unsplash.com/photo-1585032226651-759b368d7246?w=500", isAvailable = true ), FoodItem( name = "Egg Chowmein", category = "Noodles & Momos", price = 110.0, originalPrice = 140.0, description = "Stir fried noodles tossed with shredded scrambled egg & spices", isVeg = false, imageUri = "https://images.unsplash.com/photo-1585032226651-759b368d7246?w=500", isAvailable = true ), FoodItem( name = "Chicken Chowmein", category = "Noodles & Momos", price = 130.0, originalPrice = 170.0, description = "Popular street-style noodles tossed with boneless chicken pieces & soya sauce", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1585032226651-759b368d7246?w=500", isAvailable = true ), FoodItem( name = "Mixed Hakka Noodles (Egg & Chicken)", category = "Noodles & Momos", price = 150.0, originalPrice = 190.0, description = "Special combo noodles tossed with egg, chicken & veggies", isVeg = false, isAvailable = true ), FoodItem( name = "Schezwan Chicken Noodles", category = "Noodles & Momos", price = 140.0, originalPrice = 180.0, description = "Spicy schezwan sauce tossed chicken chowmein", isVeg = false, isAvailable = true ), FoodItem( name = "Veg Steamed Momos (6 Pcs)", category = "Noodles & Momos", price = 80.0, originalPrice = 110.0, description = "Juicy steamed dumplings stuffed with finely minced vegetables, served with spicy red chutney", isVeg = true, imageUri = "https://images.unsplash.com/photo-1625220194771-7ebdea0b70b9?w=500", isAvailable = true ), FoodItem( name = "Veg Fried Momos (6 Pcs)", category = "Noodles & Momos", price = 90.0, originalPrice = 120.0, description = "Crispy golden fried veg momos served with fiery chili dip", isVeg = true, imageUri = "https://images.unsplash.com/photo-1625220194771-7ebdea0b70b9?w=500", isAvailable = true ), FoodItem( name = "Chicken Steamed Momos (6 Pcs)", category = "Noodles & Momos", price = 110.0, originalPrice = 140.0, description = "Steamed dumplings filled with savory minced chicken & coriander", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1625220194771-7ebdea0b70b9?w=500", isAvailable = true ), FoodItem( name = "Chicken Fried Momos (6 Pcs)", category = "Noodles & Momos", price = 120.0, originalPrice = 150.0, description = "Crispy deep-fried chicken momos served with mayo and red schezwan sauce", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1625220194771-7ebdea0b70b9?w=500", isAvailable = true ), FoodItem( name = "Chicken Kurkure Momos (Crispy 6 Pcs)", category = "Noodles & Momos", price = 150.0, originalPrice = 190.0, description = "Ultra crunchy cornflake coated fried chicken momos", isVeg = false, isBestSeller = true, isAvailable = true ), FoodItem( name = "Veg Clear Soup", category = "Noodles & Momos", price = 70.0, originalPrice = 90.0, description = "Light healthy broth with fresh aromatic diced vegetables", isVeg = true, isAvailable = true ), FoodItem( name = "Chicken Manchow Soup (With Crispy Noodles)", category = "Noodles & Momos", price = 110.0, originalPrice = 140.0, description = "Spicy garlic flavored brown soup served with crunchy fried noodles", isVeg = false, isAvailable = true ), FoodItem( name = "Chicken Hot & Sour Soup", category = "Noodles & Momos", price = 110.0, originalPrice = 140.0, description = "Zesty sour and spicy soup filled with shredded chicken & egg drop", isVeg = false, isAvailable = true ), // Page 7: Pizza, Burgers, Sandwiches, Rolls, Fries, Maggi FoodItem( name = "Margherita Cheese Pizza (7 inch)", category = "Pizza, Burgers & Rolls", price = 140.0, originalPrice = 180.0, description = "Classic mozzarella cheese pizza with Italian basil sauce", isVeg = true, imageUri = "https://images.unsplash.com/photo-1513104890138-7c749659a591?w=500", isAvailable = true ), FoodItem( name = "Veg Supreme Deluxe Pizza (7 inch)", category = "Pizza, Burgers & Rolls", price = 180.0, originalPrice = 220.0, description = "Loaded with capsicum, onion, tomato, sweet corn & extra cheese", isVeg = true, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1513104890138-7c749659a591?w=500", isAvailable = true ), FoodItem( name = "Paneer Tikka Special Pizza (7 inch)", category = "Pizza, Burgers & Rolls", price = 210.0, originalPrice = 260.0, description = "Topped with tandoori paneer tikka chunks & spicy pizza sauce", isVeg = true, imageUri = "https://images.unsplash.com/photo-1513104890138-7c749659a591?w=500", isAvailable = true ), FoodItem( name = "Chicken Feast Pizza (7 inch)", category = "Pizza, Burgers & Rolls", price = 230.0, originalPrice = 280.0, description = "Loaded with spiced roasted chicken, capsicum & liquid cheese", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1513104890138-7c749659a591?w=500", isAvailable = true ), FoodItem( name = "Classic Veg Burger", category = "Pizza, Burgers & Rolls", price = 79.0, originalPrice = 100.0, description = "Crispy veg patty with fresh lettuce, mayo & tomato slice", isVeg = true, imageUri = "https://images.unsplash.com/photo-1568901346375-23c9450c58cd?w=500", isAvailable = true ), FoodItem( name = "Crispy Chicken Burger", category = "Pizza, Burgers & Rolls", price = 109.0, originalPrice = 149.0, description = "Crispy chicken patty with lettuce, creamy mayo in sesame bun", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1568901346375-23c9450c58cd?w=500", isAvailable = true ), FoodItem( name = "Double Cheese Chicken Burger", category = "Pizza, Burgers & Rolls", price = 139.0, originalPrice = 180.0, description = "Juicy chicken patty layered with double cheese slice & secret sauce", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1568901346375-23c9450c58cd?w=500", isAvailable = true ), FoodItem( name = "Veg Grilled Cheese Sandwich", category = "Pizza, Burgers & Rolls", price = 89.0, originalPrice = 120.0, description = "Toasted bread with vegetable stuffing & melted cheese slice", isVeg = true, isAvailable = true ), FoodItem( name = "Chicken Tikka Club Sandwich", category = "Pizza, Burgers & Rolls", price = 119.0, originalPrice = 150.0, description = "Triple decker toasted sandwich filled with chicken tikka & mayo", isVeg = false, isAvailable = true ), FoodItem( name = "Single Egg Roll", category = "Pizza, Burgers & Rolls", price = 50.0, originalPrice = 70.0, description = "Flaky paratha layered with single egg, sliced onions & sauces", isVeg = false, imageUri = "https://images.unsplash.com/photo-1626700051175-6818013e1d4f?w=500", isAvailable = true ), FoodItem( name = "Double Egg Roll", category = "Pizza, Burgers & Rolls", price = 70.0, originalPrice = 90.0, description = "Paratha layered with 2 eggs, crunchy onions & spicy tangy sauce", isVeg = false, imageUri = "https://images.unsplash.com/photo-1626700051175-6818013e1d4f?w=500", isAvailable = true ), FoodItem( name = "Chicken Egg Roll", category = "Pizza, Burgers & Rolls", price = 99.0, originalPrice = 130.0, description = "Egg wrapped paratha filled with spiced chicken kebabs & sliced onions", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1626700051175-6818013e1d4f?w=500", isAvailable = true ), FoodItem( name = "Special Double Chicken Roll", category = "Pizza, Burgers & Rolls", price = 129.0, originalPrice = 160.0, description = "Double egg paratha stuffed with extra chicken chunks & special sauces", isVeg = false, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1626700051175-6818013e1d4f?w=500", isAvailable = true ), FoodItem( name = "Crispy French Fries (Classic Salted)", category = "Pizza, Burgers & Rolls", price = 60.0, originalPrice = 80.0, description = "Golden salted potato fries served with tomato ketchup", isVeg = true, imageUri = "https://images.unsplash.com/photo-1576107232684-1279f390859f?w=500", isAvailable = true ), FoodItem( name = "Peri Peri Fries", category = "Pizza, Burgers & Rolls", price = 80.0, originalPrice = 110.0, description = "Crispy fries tossed in zesty spicy peri peri masala", isVeg = true, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1576107232684-1279f390859f?w=500", isAvailable = true ), FoodItem( name = "Veg Masala Maggi", category = "Pizza, Burgers & Rolls", price = 45.0, originalPrice = 60.0, description = "Classic masala noodles with peas, capsicum & tomatoes", isVeg = true, isAvailable = true ), FoodItem( name = "Egg Cheese Maggi", category = "Pizza, Burgers & Rolls", price = 65.0, originalPrice = 85.0, description = "Masala Maggi cooked with butter, scramble egg & melted cheese", isVeg = false, isBestSeller = true, isAvailable = true ), // Page 8: Beverages, Shakes & Desserts FoodItem( name = "Kulhad Masala Chai", category = "Beverages & Shakes", price = 25.0, originalPrice = 35.0, description = "Authentic ginger cardamom tea served hot in earthen kulhad cup", isVeg = true, isAvailable = true ), FoodItem( name = "Hot Coffee (Cappuccino Style)", category = "Beverages & Shakes", price = 40.0, originalPrice = 60.0, description = "Frothy creamy hot coffee made with rich roasted espresso blend", isVeg = true, imageUri = "https://images.unsplash.com/photo-1517701604599-bb29b565090c?w=500", isAvailable = true ), FoodItem( name = "Cold Coffee with Ice Cream", category = "Beverages & Shakes", price = 90.0, originalPrice = 120.0, description = "Chilled thick coffee topped with a scoop of vanilla ice cream", isVeg = true, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1517701604599-bb29b565090c?w=500", isAvailable = true ), FoodItem( name = "Virgin Mojito (Mint & Lime)", category = "Beverages & Shakes", price = 80.0, originalPrice = 110.0, description = "Refreshing sparkling soda cooler infused with muddled mint leaves & lemon juice", isVeg = true, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1517701604599-bb29b565090c?w=500", isAvailable = true ), FoodItem( name = "Blue Lagoon Cooler", category = "Beverages & Shakes", price = 90.0, originalPrice = 120.0, description = "Citrusy blue curaçao flavored fizzy mocktail", isVeg = true, imageUri = "https://images.unsplash.com/photo-1517701604599-bb29b565090c?w=500", isAvailable = true ), FoodItem( name = "Fresh Lemon Soda", category = "Beverages & Shakes", price = 50.0, originalPrice = 70.0, description = "Sparkling lemon soda available sweet or salted", isVeg = true, isAvailable = true ), FoodItem( name = "Chocolate Oreo Thick Shake", category = "Beverages & Shakes", price = 110.0, originalPrice = 150.0, description = "Blend of rich chocolate ice cream, crushed Oreo cookies & chocolate syrup", isVeg = true, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1572490122747-3968b75cc699?w=500", isAvailable = true ), FoodItem( name = "Strawberry Deluxe Shake", category = "Beverages & Shakes", price = 100.0, originalPrice = 140.0, description = "Creamy strawberry thick shake topped with berry drizzle", isVeg = true, imageUri = "https://images.unsplash.com/photo-1572490122747-3968b75cc699?w=500", isAvailable = true ), FoodItem( name = "Mango Thick Shake", category = "Beverages & Shakes", price = 100.0, originalPrice = 140.0, description = "Rich Alphonso mango milkshake made with real mango pulp", isVeg = true, imageUri = "https://images.unsplash.com/photo-1572490122747-3968b75cc699?w=500", isAvailable = true ), FoodItem( name = "Cold Drink Can (300ml)", category = "Beverages & Shakes", price = 40.0, originalPrice = 50.0, description = "Chilled 300ml soft drink can (Thums Up / Coca Cola / Sprite / 7Up)", isVeg = true, isAvailable = true ), FoodItem( name = "Gulab Jamun (2 Pcs)", category = "Beverages & Shakes", price = 50.0, originalPrice = 70.0, description = "Warm soft sweet gulab jamuns dipped in cardamom sugar syrup", isVeg = true, isBestSeller = true, imageUri = "https://images.unsplash.com/photo-1601050690597-df0568f70950?w=500", isAvailable = true ) ) foodItemDao.insertAll(initialItems.map { FoodItemEntity.fromDomain(it) }) // Seed initial sample past orders val sampleOrder1 = Order( orderId = "OD-11-01-LZ-7890", customerName = "Joydip", customerPhone = "+91 7005149514", deliveryAddress = "Kumarghat halaimura near bhairav thali, Tripura 799290", items = listOf( OrderItemSummary("Chicken Dum Biryani (Full)", 1, 180.0, isVeg = false), OrderItemSummary("Crispy French Fries", 1, 55.0, isVeg = true) ), itemTotal = 235.0, deliveryFee = 0.0, discount = 50.0, grandTotal = 185.0, paymentMethod = "UPI_QR", paymentStatus = "PAID", upiTransactionId = "UPI-202611019876", orderStatus = OrderStatus.DELIVERED, assignedRiderName = "Bikash Debbarma", assignedRiderPhone = "+91 7005149514", assignedRiderVehicle = "Honda Activa (TR-02-A-4521)", timestamp = System.currentTimeMillis() - 86400000L ) val sampleOrder2 = Order( orderId = "OD-10-28-LZ-4321", customerName = "Joydip", customerPhone = "+91 7005149514", deliveryAddress = "Kumarghat halaimura near bhairav thali, Tripura 799290", items = listOf( OrderItemSummary("Double Egg Chicken Roll", 2, 99.0, isVeg = false) ), itemTotal = 198.0, deliveryFee = 30.0, discount = 0.0, grandTotal = 228.0, paymentMethod = "CASH_ON_DELIVERY", paymentStatus = "CASH_ON_DELIVERY", orderStatus = OrderStatus.DELIVERED, assignedRiderName = "Rahul Das", assignedRiderPhone = "+91 7005149514", assignedRiderVehicle = "TVS Jupiter (TR-02-B-8832)", timestamp = System.currentTimeMillis() - 259200000L ) orderDao.insertOrder(OrderEntity.fromDomain(sampleOrder1)) orderDao.insertOrder(OrderEntity.fromDomain(sampleOrder2)) // Seed initial welcome notifications notificationDao.insertNotification( NotificationEntity( title = "Welcome to Love Zone Restaurant! ❤️", message = "Get FLAT 50% OFF up to ₹100 on your first food order. Use code LOVE50 at checkout!", timestamp = System.currentTimeMillis() - 3600000L, isRead = false, type = "OFFER" ) ) notificationDao.insertNotification( NotificationEntity( title = "Weekend Biryani Festival is LIVE! 🔥", message = "Order our chef special Chicken Dum Biryani with complimentary Raita & Salan.", timestamp = System.currentTimeMillis() - 7200000L, isRead = false, type = "OFFER" ) ) } // Seed Kumarghat Delivery Riders fleet if empty if (deliveryRiderDao.getCount() == 0) { val initialRiders = listOf( DeliveryRider( name = "Bikash Debbarma", phone = "+91 7005149514", vehicleNumber = "Honda Activa (TR-02-A-4521)", status = RiderStatus.AVAILABLE, totalDeliveries = 142, rating = 4.9f ), DeliveryRider( name = "Rahul Das", phone = "+91 7005149514", vehicleNumber = "TVS Jupiter (TR-02-B-8832)", status = RiderStatus.AVAILABLE, totalDeliveries = 98, rating = 4.8f ), DeliveryRider( name = "Suman Paul", phone = "+91 7005149514", vehicleNumber = "Hero Splendor (TR-02-C-1944)", status = RiderStatus.OFFLINE, totalDeliveries = 65, rating = 4.7f ) ) deliveryRiderDao.insertAll(initialRiders.map { DeliveryRiderEntity.fromDomain(it) }) } // Seed initial default customer Joydip if database is fresh if (userDao.getCount() == 0) { val initialUser = UserEntity( phone = "7005149514", name = "Joydip", email = "dbna8546@gmail.com", alternatePhone = "", houseNo = "House #12", streetArea = "Halaimura", landmark = "Near Bhairav Thali", zone = "Kumarghat", pincode = "799290", fullAddress = "Kumarghat halaimura near bhairav thali, Tripura 799290", dietaryPreference = "Both", dateOfBirth = "", deliveryNote = "", walletBalance = 0.0, password = "admin123" ) userDao.insertUser(initialUser) } // Seed initial customer reviews if database is fresh if (foodReviewDao.getCount() == 0) { val sampleReviews = listOf( FoodReviewEntity( foodItemId = 1, foodName = "Fried Rice + Chicken Kosha (2 Pcs)", customerName = "Joydip", customerPhone = "+91 7005149514", rating = 5.0f, reviewText = "Super tasty combo! Bengali style Chicken Kosha is extremely delicious & authentic flavor.", timestamp = System.currentTimeMillis() - 86400000L ), FoodReviewEntity( foodItemId = 19, foodName = "Chicken Dum Biryani (Full - 2 Pcs Chicken, 1 Egg)", customerName = "Bikash Debbarma", customerPhone = "+91 9862123456", rating = 5.0f, reviewText = "Best biryani in Kumarghat! Rice quality is top notch and chicken is very tender.", timestamp = System.currentTimeMillis() - 172800000L ), FoodReviewEntity( foodItemId = 38, foodName = "Chicken Tandoori (Full - 8 Pcs)", customerName = "Rahul Das", customerPhone = "+91 8794123890", rating = 4.8f, reviewText = "Charcoal roasted flavor is incredible. Green chutney combination makes it perfect!", timestamp = System.currentTimeMillis() - 259200000L ), FoodReviewEntity( foodItemId = 74, foodName = "Chicken Chowmein", customerName = "Priya Roy", customerPhone = "+91 9436123412", rating = 4.7f, reviewText = "Street style chowmein taste. Fresh vegetables and generous chicken pieces.", timestamp = System.currentTimeMillis() - 345600000L ) ) for (rev in sampleReviews) { foodReviewDao.insertReview(rev) } } } // --- Reviews & Ratings Functions --- fun getReviewsForFoodItem(foodItemId: Long): Flow> { return foodReviewDao.getReviewsForFoodItem(foodItemId).map { list -> list.map { it.toDomain() } } } suspend fun submitFoodReview(review: FoodReview) { foodReviewDao.insertReview(FoodReviewEntity.fromDomain(review)) val count = foodReviewDao.getReviewCountForItem(review.foodItemId) val avg = foodReviewDao.getAverageRatingForItem(review.foodItemId) ?: 5.0 foodItemDao.updateItemRating(review.foodItemId, avg.toFloat(), count) notificationDao.insertNotification( NotificationEntity( title = "⭐ NAYA RATING & REVIEW! (${review.rating.toInt()}★)", message = "${review.customerName} reviewed ${review.foodName}: \"${review.reviewText}\"", timestamp = System.currentTimeMillis(), isRead = false, type = "REVIEW" ) ) } suspend fun verifyAndCompleteOnlinePayment(orderId: String, upiTxnId: String): Boolean { orderDao.updateOrderPayment(orderId, "CUSTOMER_PAYMENT_RECEIVED", upiTxnId) orderDao.updateOrderStatus(orderId, OrderStatus.PLACED.name) com.example.util.CloudSyncManager.updateOrderStatusCentrally(orderId, OrderStatus.PLACED) val order = orderDao.getOrderById(orderId)?.toDomain() if (order != null) { com.example.util.OrderSoundHelper.triggerNewOrderAlert( context, order.orderId, order.customerName, order.grandTotal ) } notificationDao.insertNotification( NotificationEntity( title = "✅ ONLINE PAYMENT RECEIVED!", message = "Customer payment of ₹${order?.grandTotal?.toInt() ?: 0} received for Order #$orderId (Txn: $upiTxnId). Order is active!", timestamp = System.currentTimeMillis(), isRead = false, type = "PAYMENT_RECEIVED" ) ) return true } // --- Customer Functions --- suspend fun isUtrAlreadyUsed(utr: String): Boolean { val clean = utr.trim() if (clean.isBlank()) return false return orderDao.countOrdersWithUpiTxnId(clean) > 0 } suspend fun placeOrder(order: Order): Boolean { orderDao.insertOrder(OrderEntity.fromDomain(order)) // Push order to central cloud DB so Admin phone receives it com.example.util.CloudSyncManager.pushOrderCentrally(order) // Trigger Sound Alert and System Notification on device com.example.util.OrderSoundHelper.triggerNewOrderAlert(context, order.orderId, order.customerName, order.grandTotal) // Customer Notification notificationDao.insertNotification( NotificationEntity( title = "Order Placed Successfully! #${order.orderId}", message = "Love Zone Restaurant has received your order of ₹${order.grandTotal.toInt()}. Our chef is preparing your meal fresh!", timestamp = System.currentTimeMillis(), isRead = false, type = "ORDER_UPDATE" ) ) // Admin Segment Panel Notification notificationDao.insertNotification( NotificationEntity( title = "🚨 NAYA ORDER AAYA HAI! #${order.orderId}", message = "Customer ${order.customerName} (${order.customerPhone}) placed order of ₹${order.grandTotal.toInt()} (${order.items.size} items). Address: ${order.deliveryAddress}", timestamp = System.currentTimeMillis() + 1, isRead = false, type = "NEW_ORDER" ) ) return true } suspend fun syncCentralCloudOrders() { try { // 1. Sync Central Users across all devices to local Room DB for Admin list val remoteUsers = com.example.util.CloudSyncManager.fetchAllUsersCentrally() if (remoteUsers.isNotEmpty()) { for (remoteUser in remoteUsers) { val digits = remoteUser.phoneDigits if (digits.length >= 10 && userDao.countUserWithPhone(digits) == 0) { userDao.insertUser(UserEntity.fromDomain(remoteUser)) } } } // 1b. Ensure any local users (e.g. initial demo/test users) are backed up to Firestore val localUsers = userDao.getAllUsersList() for (local in localUsers) { val cleanDigits = local.phone.filter { it.isDigit() }.let { if (it.length > 10) it.takeLast(10) else it } if (cleanDigits.length >= 10 && remoteUsers.none { it.phoneDigits == cleanDigits }) { com.example.util.CloudSyncManager.registerUserCentrally(local.toDomain()) } } // 2. Sync Central Orders across all devices to local Room DB val remoteOrders = com.example.util.CloudSyncManager.fetchAllOrdersCentrally() if (remoteOrders.isNotEmpty()) { val currentAdminDigits = _currentUser.value.phoneDigits val isOwnerAdminLoggedIn = (currentAdminDigits == "7005149514") for (remote in remoteOrders) { val existing = orderDao.getOrderById(remote.orderId) if (existing == null) { orderDao.insertOrder(OrderEntity.fromDomain(remote)) // Play sound alert on Admin device when new remote customer order arrives! if (isOwnerAdminLoggedIn) { com.example.util.OrderSoundHelper.triggerNewOrderAlert( context, remote.orderId, remote.customerName, remote.grandTotal ) } } else if (existing.orderStatus != remote.orderStatus.name || existing.assignedRiderName != remote.assignedRiderName || existing.paymentStatus != remote.paymentStatus) { orderDao.insertOrder(OrderEntity.fromDomain(remote)) } } } // 3. Sync Remote Menu Items to local Room DB (so price updates appear on every device) val remoteMenuItems = com.example.util.CloudSyncManager.fetchAllMenuItemsCentrally() if (remoteMenuItems.isNotEmpty()) { for (remoteItem in remoteMenuItems) { val localItem = foodItemDao.getFoodItemById(remoteItem.id) if (localItem == null) { foodItemDao.insertItem(FoodItemEntity.fromDomain(remoteItem)) } else if (localItem.price != remoteItem.price || localItem.isAvailable != remoteItem.isAvailable || localItem.name != remoteItem.name) { foodItemDao.updateItem(FoodItemEntity.fromDomain(remoteItem)) } } } else { // If cloud menu is empty, upload local seeded items once so other devices get it! val localItems = foodItemDao.getAllFoodItemsList() for (item in localItems) { com.example.util.CloudSyncManager.pushMenuItemCentrally(item.toDomain()) } } // 4. Sync Remote Admin Settings (domain, announcement, open/close status) val remoteSettings = com.example.util.CloudSyncManager.fetchAdminSettingsCentrally() if (remoteSettings != null && remoteSettings != _adminSettings.value) { updateAdminSettings(remoteSettings) } else if (remoteSettings == null) { com.example.util.CloudSyncManager.pushAdminSettingsCentrally(_adminSettings.value) } } catch (e: Exception) { android.util.Log.e("LoveZoneRepo", "syncCentralCloudOrders error: ${e.message}", e) } } suspend fun markNotificationsRead() { notificationDao.markAllAsRead() } // --- User Session / Registration --- private fun loadCurrentUser(): CustomerUser { val name = userPrefs.getString("user_name", "") ?: "" val phone = userPrefs.getString("user_phone", "") ?: "" val email = userPrefs.getString("user_email", "") ?: "" val alternatePhone = userPrefs.getString("user_alt_phone", "") ?: "" val houseNo = userPrefs.getString("user_house_no", "") ?: "" val streetArea = userPrefs.getString("user_street_area", "") ?: "" val landmark = userPrefs.getString("user_landmark", "") ?: "" val zone = userPrefs.getString("user_zone", "Kumarghat") ?: "Kumarghat" val pincode = userPrefs.getString("user_pincode", "799290") ?: "799290" val address = userPrefs.getString("user_address", "") ?: "" val dietaryPreference = userPrefs.getString("user_dietary", "Both") ?: "Both" val dateOfBirth = userPrefs.getString("user_dob", "") ?: "" val deliveryNote = userPrefs.getString("user_delivery_note", "") ?: "" val wallet = userPrefs.getFloat("user_wallet", 0f).toDouble() val profileImageUri = userPrefs.getString("user_profile_image", "") ?: "" val isLoggedIn = userPrefs.getBoolean("is_logged_in", false) return CustomerUser( name = if (name.isNotBlank()) name else "Guest Customer", phone = phone, email = email, alternatePhone = alternatePhone, houseNo = houseNo, streetArea = streetArea, landmark = landmark, zone = zone, pincode = pincode, address = address, dietaryPreference = dietaryPreference, dateOfBirth = dateOfBirth, deliveryNote = deliveryNote, walletBalance = wallet, profileImageUri = profileImageUri, isLoggedIn = isLoggedIn ) } suspend fun fetchUserByPhone(phoneRaw: String): CustomerUser? { val digits = phoneRaw.filter { it.isDigit() }.let { if (it.length > 10) it.takeLast(10) else it } if (digits.length < 10) return null val localUser = userDao.getUserByPhone(digits) if (localUser != null) { return localUser.toDomain() } return com.example.util.CloudSyncManager.fetchUserCentrally(digits) } suspend fun isUserRegistered(phoneRaw: String): Boolean { val digits = phoneRaw.filter { it.isDigit() }.let { if (it.length > 10) it.takeLast(10) else it } if (digits.length < 10) return false // Check local DB first if (userDao.countUserWithPhone(digits) > 0) return true // Check central cloud database across all devices globally in Firestore val remoteUser = com.example.util.CloudSyncManager.fetchUserCentrally(digits) if (remoteUser != null) { userDao.insertUser(UserEntity.fromDomain(remoteUser)) return true } return false } suspend fun updateUser(user: CustomerUser) { val entity = UserEntity.fromDomain(user) userDao.insertUser(entity) com.example.util.CloudSyncManager.registerUserCentrally(user) } suspend fun registerUser(user: CustomerUser): Boolean { val digits = user.phoneDigits // 1. Insert into local Room DB val entity = UserEntity.fromDomain(user) userDao.insertUser(entity) // 2. Register centrally in Cloud DB so all devices know this phone is taken! com.example.util.CloudSyncManager.registerUserCentrally(user) userPrefs.edit() .putString("user_name", user.name) .putString("user_phone", user.phone) .putString("user_email", user.email) .putString("user_alt_phone", user.alternatePhone) .putString("user_house_no", user.houseNo) .putString("user_street_area", user.streetArea) .putString("user_landmark", user.landmark) .putString("user_zone", user.zone) .putString("user_pincode", user.pincode) .putString("user_address", user.address) .putString("user_dietary", user.dietaryPreference) .putString("user_dob", user.dateOfBirth) .putString("user_delivery_note", user.deliveryNote) .putFloat("user_wallet", user.walletBalance.toFloat()) .putString("user_profile_image", user.profileImageUri) .putString("current_logged_in_phone", digits) .putBoolean("is_logged_in", true) .apply() _currentUser.value = user.copy(isLoggedIn = true) return true } suspend fun loginUserWithPhone(phoneRaw: String): Boolean { val digits = phoneRaw.filter { it.isDigit() }.let { if (it.length > 10) it.takeLast(10) else it } if (digits.length < 10) return false var entity = userDao.getUserByPhone(digits) // If not found in local DB, check central Cloud DB if (entity == null) { val remoteUser = com.example.util.CloudSyncManager.fetchUserCentrally(digits) if (remoteUser != null) { entity = UserEntity.fromDomain(remoteUser) userDao.insertUser(entity) } else { val savedName = userPrefs.getString("user_name", "") ?: "" val savedAddress = userPrefs.getString("user_address", "") ?: "" entity = UserEntity( phone = digits, name = if (savedName.isNotBlank()) savedName else "Customer $digits", email = userPrefs.getString("user_email", "") ?: "", houseNo = userPrefs.getString("user_house_no", "House #12") ?: "House #12", streetArea = userPrefs.getString("user_street_area", "Halaimura") ?: "Halaimura", landmark = userPrefs.getString("user_landmark", "Near Bhairav Thali") ?: "Near Bhairav Thali", zone = userPrefs.getString("user_zone", "Kumarghat") ?: "Kumarghat", pincode = userPrefs.getString("user_pincode", "799290") ?: "799290", fullAddress = if (savedAddress.isNotBlank()) savedAddress else "Kumarghat halaimura near bhairav thali, Tripura 799290", dietaryPreference = userPrefs.getString("user_dietary", "Both") ?: "Both", profileImageUri = userPrefs.getString("user_profile_image", "") ?: "" ) userDao.insertUser(entity) } } val user = entity.toDomain(isLoggedIn = true) userPrefs.edit() .putString("user_name", user.name) .putString("user_phone", user.phone) .putString("user_email", user.email) .putString("user_alt_phone", user.alternatePhone) .putString("user_house_no", user.houseNo) .putString("user_street_area", user.streetArea) .putString("user_landmark", user.landmark) .putString("user_zone", user.zone) .putString("user_pincode", user.pincode) .putString("user_address", user.address) .putString("user_dietary", user.dietaryPreference) .putString("user_dob", user.dateOfBirth) .putString("user_delivery_note", user.deliveryNote) .putFloat("user_wallet", user.walletBalance.toFloat()) .putString("user_profile_image", user.profileImageUri) .putString("current_logged_in_phone", digits) .putBoolean("is_logged_in", true) .apply() _currentUser.value = user return true } fun setGuestSession() { userPrefs.edit() .putString("user_name", "Guest User") .putString("user_phone", "") .putBoolean("is_logged_in", false) .apply() _currentUser.value = CustomerUser( id = "cust_guest", name = "Guest User", phone = "", email = "", address = "", isLoggedIn = false ) } fun logoutUser() { userPrefs.edit().putBoolean("is_logged_in", false).apply() _currentUser.value = _currentUser.value.copy(isLoggedIn = false) } suspend fun updateProfilePicture(uri: String) { val user = _currentUser.value if (user.isLoggedIn) { val digits = user.phoneDigits userDao.updateProfileImage(digits, uri) userPrefs.edit().putString("user_profile_image", uri).apply() _currentUser.value = user.copy(profileImageUri = uri) } } fun registerOrUpdateUser(name: String, phone: String, email: String, address: String) { val digits = phone.filter { it.isDigit() }.let { if (it.length > 10) it.takeLast(10) else it } userPrefs.edit() .putString("user_name", name) .putString("user_phone", phone) .putString("user_email", email) .putString("user_address", address) .putString("current_logged_in_phone", digits) .putBoolean("is_logged_in", true) .apply() _currentUser.value = loadCurrentUser() } fun loginUser(phone: String) { val digits = phone.filter { it.isDigit() }.let { if (it.length > 10) it.takeLast(10) else it } userPrefs.edit() .putString("user_phone", phone) .putString("current_logged_in_phone", digits) .putBoolean("is_logged_in", true) .apply() _currentUser.value = _currentUser.value.copy(phone = phone, isLoggedIn = true) } // --- Admin Functions --- private fun loadAdminSettings(): AdminSettings { val domain = prefs.getString("custom_domain", "https://lovezonerasturant.shop") ?: "https://lovezonerasturant.shop" com.example.util.ShareAppHelper.updateDomain(domain) return AdminSettings( restaurantName = prefs.getString("rest_name", "Love Zone Restaurant") ?: "Love Zone Restaurant", upiId = prefs.getString("upi_id", "lovezonerestaurant@okaxis") ?: "lovezonerestaurant@okaxis", qrImageUri = prefs.getString("qr_image_uri", "") ?: "", isOpen = prefs.getBoolean("is_open", true), freeDeliveryThreshold = prefs.getFloat("free_delivery_min", 199f).toDouble(), deliveryFee = prefs.getFloat("delivery_fee", 30f).toDouble(), announcement = prefs.getString("announcement", "Welcome to Love Zone Restaurant! Order delicious meals now.") ?: "", customDomain = domain ) } fun updateAdminSettings(settings: AdminSettings) { prefs.edit() .putString("rest_name", settings.restaurantName) .putString("upi_id", settings.upiId) .putString("qr_image_uri", settings.qrImageUri) .putBoolean("is_open", settings.isOpen) .putFloat("free_delivery_min", settings.freeDeliveryThreshold.toFloat()) .putFloat("delivery_fee", settings.deliveryFee.toFloat()) .putString("announcement", settings.announcement) .putString("custom_domain", settings.customDomain) .apply() com.example.util.ShareAppHelper.updateDomain(settings.customDomain) _adminSettings.value = settings repositoryScope.launch { com.example.util.CloudSyncManager.pushAdminSettingsCentrally(settings) } } suspend fun updateItemImage(id: Long, imageUri: String) { foodItemDao.updateItemImage(id, imageUri) } suspend fun saveFoodItem(item: FoodItem) { if (item.id == 0L) { val newId = foodItemDao.insertItem(FoodItemEntity.fromDomain(item)) com.example.util.CloudSyncManager.pushMenuItemCentrally(item.copy(id = newId)) } else { foodItemDao.updateItem(FoodItemEntity.fromDomain(item)) com.example.util.CloudSyncManager.pushMenuItemCentrally(item) } } suspend fun deleteFoodItem(item: FoodItem) { foodItemDao.deleteItem(FoodItemEntity.fromDomain(item)) } suspend fun updateOrderStatus(orderId: String, newStatus: OrderStatus) { orderDao.updateOrderStatus(orderId, newStatus.name) // Push updated status centrally to Cloud DB for all customer devices com.example.util.CloudSyncManager.updateOrderStatusCentrally(orderId, newStatus) val statusMsg = when (newStatus) { OrderStatus.PREPARING -> "Chef is preparing your meal hot and fresh!" OrderStatus.OUT_FOR_DELIVERY -> "Our rider is on the way to your delivery address!" OrderStatus.DELIVERED -> "Your order has been delivered! Enjoy your meal from Love Zone ❤️" OrderStatus.CANCELLED -> "Your order was cancelled by restaurant. Any refund will be credited to wallet." OrderStatus.PLACED -> "Order confirmed by Love Zone." } notificationDao.insertNotification( NotificationEntity( title = "Order Update: ${newStatus.label}", message = "Order #$orderId: $statusMsg", timestamp = System.currentTimeMillis(), isRead = false, type = "ORDER_UPDATE" ) ) } suspend fun broadcastNotification(title: String, message: String, type: String = "OFFER") { notificationDao.insertNotification( NotificationEntity( title = title, message = message, timestamp = System.currentTimeMillis(), isRead = false, type = type ) ) } // --- Rider Management Functions --- suspend fun saveRider(rider: DeliveryRider) { if (rider.id == 0L) { deliveryRiderDao.insertRider(DeliveryRiderEntity.fromDomain(rider)) } else { deliveryRiderDao.updateRider(DeliveryRiderEntity.fromDomain(rider)) } } suspend fun deleteRider(rider: DeliveryRider) { deliveryRiderDao.deleteRider(DeliveryRiderEntity.fromDomain(rider)) } suspend fun updateRiderStatus(riderId: Long, status: RiderStatus, currentOrderId: String = "") { deliveryRiderDao.updateRiderStatus(riderId, status.name, currentOrderId) } suspend fun assignRiderToOrder(orderId: String, rider: DeliveryRider) { orderDao.assignRider(orderId, rider.name, rider.phone, rider.vehicleNumber) orderDao.updateOrderStatus(orderId, OrderStatus.OUT_FOR_DELIVERY.name) com.example.util.CloudSyncManager.assignRiderCentrally(orderId, rider.name, rider.phone, rider.vehicleNumber) deliveryRiderDao.updateRiderStatus(rider.id, RiderStatus.ON_DELIVERY.name, orderId) notificationDao.insertNotification( NotificationEntity( title = "Rider Assigned! # $orderId", message = "${rider.name} (${rider.phone}) is out for delivery with your meal on ${rider.vehicleNumber}!", timestamp = System.currentTimeMillis(), isRead = false, type = "ORDER_UPDATE" ) ) } companion object { @Volatile private var INSTANCE: LoveZoneRepository? = null fun getInstance(context: Context): LoveZoneRepository { return INSTANCE ?: synchronized(this) { val db = LoveZoneDatabase.getDatabase(context) val repo = LoveZoneRepository( foodItemDao = db.foodItemDao(), foodReviewDao = db.foodReviewDao(), orderDao = db.orderDao(), notificationDao = db.notificationDao(), deliveryRiderDao = db.deliveryRiderDao(), userDao = db.userDao(), cartItemDao = db.cartItemDao(), context = context.applicationContext ) INSTANCE = repo repo } } } }