// Dashboard functionality
document.addEventListener('DOMContentLoaded', async () => {
    // Check if user has dashboard permission - if not, redirect to login
    const userRole = localStorage.getItem('role');
    const userPermsStr = localStorage.getItem('permissions');

    let permissions = [];
    try {
        permissions = JSON.parse(userPermsStr) || [];
    } catch (e) {
        permissions = [];
    }

    // Admin has full access
    if (userRole !== 'Admin' && !permissions.includes('dashboard.html') && !permissions.includes('*')) {
        // User doesn't have dashboard permission - redirect to login
        localStorage.removeItem('isLoggedIn');
        localStorage.removeItem('user');
        localStorage.removeItem('role');
        localStorage.removeItem('permissions');
        localStorage.removeItem('status');
        window.location.href = 'login.html';
        return;
    }

    await loadDashboardData();
    await loadRecentTransactions();

    // Hide quick action buttons based on permissions
    updateQuickActionVisibility();
});

// Update quick action button visibility based on user permissions
function updateQuickActionVisibility() {
    const userRole = localStorage.getItem('role');
    const userPermsStr = localStorage.getItem('permissions');

    let permissions = [];
    try {
        permissions = JSON.parse(userPermsStr) || [];
    } catch (e) {
        permissions = [];
    }

    // Admin has full access
    if (userRole === 'Admin' || permissions.includes('*')) {
        // Show all buttons
        document.querySelectorAll('.quick-action-btn').forEach(btn => {
            btn.style.display = 'block';
        });
        return;
    }

    // Hide buttons based on permissions
    const billingBtn = document.querySelector('a[href="pages/billing.html"]');
    const invoicesBtn = document.querySelector('a[href="pages/invoices.html"]');
    const returnsBtn = document.querySelector('a[href="pages/returns.html"]');
    const inventoryBtn = document.querySelector('a[href="pages/inventory.html"]');

    if (billingBtn) {
        billingBtn.style.display = permissions.includes('billing.html') ? 'block' : 'none';
    }

    if (invoicesBtn) {
        invoicesBtn.style.display = permissions.includes('invoices.html') ? 'block' : 'none';
    }

    if (returnsBtn) {
        returnsBtn.style.display = permissions.includes('returns.html') ? 'block' : 'none';
    }

    if (inventoryBtn) {
        inventoryBtn.style.display = permissions.includes('inventory.html') ? 'block' : 'none';
    }
}

async function loadDashboardData() {
    try {
        const data = await app.apiGet('/dashboard');

        // Update stat cards
        document.getElementById('inventoryValue').textContent = app.formatCurrency(data.inventory_value);
        document.getElementById('todaySales').textContent = app.formatCurrency(data.today_sales_total);
        document.getElementById('salesCount').textContent = `${data.today_sales_count} transactions`;
        document.getElementById('outstandingCredit').textContent = app.formatCurrency(data.outstanding_credit);
        document.getElementById('todayExpenses').textContent = app.formatCurrency(data.today_expenses);

    } catch (error) {
        console.error('Error loading dashboard data:', error);
        app.showNotification('Failed to load dashboard data', 'error');
    }
}

async function loadRecentTransactions() {
    try {
        const transactions = await app.apiGet('/transactions');
        const container = document.getElementById('recentTransactions');

        if (transactions.length === 0) {
            container.innerHTML = '<p class="loading">No recent transactions</p>';
            return;
        }

        // Show only last 5 transactions
        const recentTransactions = transactions.slice(0, 5);

        container.innerHTML = recentTransactions.map(transaction => `
            <div class="activity-item fade-in">
                <div class="activity-info">
                    <h4>${transaction.customer_name || 'Walk-in Customer'}</h4>
                    <p>${app.formatDate(transaction.transaction_date)} • <span class="badge badge-${transaction.payment_type.toLowerCase()}">${transaction.payment_type}</span></p>
                </div>
                <div class="activity-amount">
                    ${app.formatCurrency(transaction.total_amount)}
                </div>
            </div>
        `).join('');

    } catch (error) {
        console.error('Error loading recent transactions:', error);
        document.getElementById('recentTransactions').innerHTML = '<p class="loading">Failed to load transactions</p>';
    }
}
