window.BackendLoader = {
    isLoaded: false,
    init: async function() {
        if (!window.POSApiService) {
            console.error("POSApiService is not loaded.");
            return;
        }
        try {
            const [products, customers, expenses, suppliers, transactions, promotions, users] = await Promise.all([
                window.POSApiService.getAllProducts(),
                window.POSApiService.getAllCustomers(),
                window.POSApiService.getAllExpenses(),
                window.POSApiService.getAllSuppliers(),
                window.POSApiService.getAllTransactions(),
                window.POSApiService.getAllPromotions(),
                window.POSApiService.get('auth.php?action=get_all')
            ]);

            if (Array.isArray(products)) {
                window.MockData.products = products.map(p => ({
                    ...p,
                    category: p.category || p.category_name || 'Uncategorized',
                    image: p.image_url || p.image || 'https://via.placeholder.com/300'
                }));
            }
            if (Array.isArray(customers)) window.MockData.customers = customers;
            if (Array.isArray(expenses)) window.MockData.expenses = expenses;
            if (Array.isArray(suppliers)) window.MockData.suppliers = suppliers;
            if (Array.isArray(users)) window.MockData.users = users;

            // Normalize transactions: map all backend field names to what the frontend expects
            const rawTransactions = transactions && transactions.data
                ? transactions.data
                : (Array.isArray(transactions) ? transactions : []);

            window.MockData.transactions = rawTransactions.map(t => {
                // Capitalize status so filters like t.status === 'Completed' work
                const rawStatus = t.status || 'completed';
                const normalizedStatus = rawStatus.charAt(0).toUpperCase() + rawStatus.slice(1);

                return {
                    ...t,
                    // Date field
                    date: t.transaction_date || t.date || '',
                    // Total — prefer final_amount (after discount), fallback to total_amount
                    total: parseFloat(t.final_amount || t.total_amount || t.total || 0),
                    // Payment method label
                    payment: t.payment_method
                        ? (t.payment_method.charAt(0).toUpperCase() + t.payment_method.slice(1))
                        : (t.payment || 'Cash'),
                    // Status with capital first letter
                    status: normalizedStatus,
                    // Customer name
                    customer: t.customer_name || t.customer || 'Guest',
                    customerId: t.customer_id || t.customerId || null,
                    // Cashier ID — used in Reports to look up cashier name
                    cashierId: t.cashier_id || t.cashierId || 'admin',
                    // Item count (from DB it's not included; default to 0 for now)
                    items: Array.isArray(t.items) ? t.items.length : (t.items || 0)
                };
            });

            // Empty out static Mock arrays that aren't tied to the DB yet
            window.MockData.creditNotes = [];
            window.MockData.stats = {
                salesToday: 0, salesMonth: 0, ordersToday: 0, returnsToday: 0,
                lowStockItems: 0, totalInventoryValue: 0, creditsIssuedToday: 0,
                creditsRedeemedToday: 0, outstandingCreditValue: 0
            };
            window.MockData.logs = [];

            this.isLoaded = true;
            console.log(`BackendLoader: Loaded ${window.MockData.transactions.length} transactions, ${window.MockData.products.length} products.`);
        } catch(err) {
            console.error("Failed to load backend data:", err);
            // Fallback for UI visualization
            this.isLoaded = true;
        }
    }
};
