<div class="dashboard-container">
    <!-- Welcome Banner/Header -->
    <div class="card p-0" style="background-color: var(--primary); color: #fff; border: none;">
        <div class="card-body d-flex justify-between align-center">
            <div>
                <h1 class="m-0" style="color: var(--accent); font-size: 2em;">خوش آمدید!</h1>
                <p class="m-0 opacity-80">بابا نوید ٹریڈرز اینڈ کمیشن ایجنٹ — غلہ منڈی، اوکاڑہ</p>
            </div>
            <div class="text-right">
                <div id="dashDate" class="fw-bold" style="font-size: 1.2em;"></div>
                <!-- <div class="badge badge-accent">Phase 1: Frontend Live</div> -->
            </div>
        </div>
    </div>

    <!-- Dynamic Alerts Area -->
    <div id="dashboardAlerts" style="margin-bottom: var(--sp-4);"></div>

    <!-- Summary Stats Grid -->
    <div class="form-grid-4" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: var(--sp-4); margin-bottom: var(--sp-6);">
        <div class="card m-0">
            <div class="card-body p-4 d-flex align-center gap-4">
                <div style="background: var(--accent-light); padding: 15px; border-radius: var(--radius-md);">
                    <i class="fas fa-cart-arrow-down fa-2x" style="color: var(--primary);"></i>
                </div>
                <div>
                    <div class="text-muted" style="font-size: 0.9em;">آج کی خریداری</div>
                    <div class="fw-bold" style="font-size: 1.4em;" id="todayPurchasesAmt">0.00 <small>روپے</small></div>
                </div>
            </div>
        </div>
        <div class="card m-0">
            <div class="card-body p-4 d-flex align-center gap-4">
                <div style="background: #e8f5e9; padding: 15px; border-radius: var(--radius-md);">
                    <i class="fas fa-cash-register fa-2x" style="color: var(--success);"></i>
                </div>
                <div>
                    <div class="text-muted" style="font-size: 0.9em;">آج کی فروخت</div>
                    <div class="fw-bold" style="font-size: 1.4em;" id="todaySalesAmt">0.00 <small>روپے</small></div>
                </div>
            </div>
        </div>
        <div class="card m-0">
            <div class="card-body p-4 d-flex align-center gap-4">
                <div style="background: #e3f2fd; padding: 15px; border-radius: var(--radius-md);">
                    <i class="fas fa-boxes fa-2x" style="color: var(--info);"></i>
                </div>
                <div>
                    <div class="text-muted" style="font-size: 0.9em;">فعال ڈیریاں (Lots)</div>
                    <div class="fw-bold" style="font-size: 1.4em;" id="inventoryLotsCount">0</div>
                </div>
            </div>
        </div>
        <div class="card m-0">
            <div class="card-body p-4 d-flex align-center gap-4">
                <div style="background: #fff3e0; padding: 15px; border-radius: var(--radius-md);">
                    <i class="fas fa-wallet fa-2x" style="color: var(--warning);"></i>
                </div>
                <div>
                    <div class="text-muted" style="font-size: 0.9em;">نقد بیلنس (Cash)</div>
                    <div class="fw-bold" style="font-size: 1.4em;" id="cashBalanceAmt">0.00 <small>روپے</small></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions & Recent Activity -->
    <div class="form-grid-2">
        <!-- Quick Actions -->
        <div class="card m-0">
            <div class="card-header">
                <h3 class="card-title">فوری کمالات (Quick Actions)</h3>
            </div>
            <div class="card-body">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                    <a href="#purchase" class="btn btn-primary w-100 flex-column" style="height: 100px; justify-content: center;">
                        <i class="fas fa-plus-circle"></i> نئی کچی پرچی
                    </a>
                    <a href="#sale" class="btn btn-accent w-100 flex-column" style="height: 100px; justify-content: center;">
                        <i class="fas fa-file-invoice"></i> نئی پکی پرچی
                    </a>
                    <a href="#ledger" class="btn btn-outline w-100 flex-column" style="height: 100px; justify-content: center;">
                        <i class="fas fa-search-dollar"></i> کھاتہ دیکھیں
                    </a>
                    <a href="#cash-bank" class="btn btn-outline w-100 flex-column" style="height: 100px; justify-content: center;">
                        <i class="fas fa-exchange-alt"></i> نقد ادائیگی
                    </a>
                </div>
            </div>
        </div>

        <!-- Recent Activity -->
        <div class="card m-0">
            <div class="card-header">
                <h3 class="card-title">حالیہ سرگرمی</h3>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table m-0">
                        <thead>
                            <tr>
                                <th>پرچی #</th>
                                <th>پارٹی</th>
                                <th>رقم</th>
                                <th>قسم</th>
                            </tr>
                        </thead>
                        <tbody id="recentActivityBody">
                            <!-- Populated via initDashboard -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
async function initDashboard() {
    $('#dashDate').text(Utils.getTodayUrdu());
    
    // 1. Fetch Stats & Recent Activity
    try {
        const [statsRes, purchasesRes, salesRes] = await Promise.all([
            API.get('/dashboard/stats'),
            API.get('/purchases'),
            API.get('/sales')
        ]);

        const stats = statsRes.data;
        
        // 2. Update Summary Cards
        // Today Purchases
        $('#todayPurchasesAmt').html(`${Utils.formatNumber(stats.today_purchases.total)} <small>روپے</small>`);
        
        // Today Sales
        $('#todaySalesAmt').html(`${Utils.formatNumber(stats.today_sales.total)} <small>روپے</small>`);
        
        // Active Inventory Lots (Shared Data)
        $('#inventoryLotsCount').text(stats.inventory_lots);
        
        // Cash in Hand
        $('#cashBalanceAmt').html(`${Utils.formatNumber(stats.cash_in_hand)} <small>روپے</small>`);

        // 2.5 Render Due Alerts
        if (stats.due_alerts && stats.due_alerts.length > 0) {
            let alertHtml = '';
            stats.due_alerts.forEach(alert => {
                alertHtml += `
                    <div class="card" style="background-color: #fff3cd; border-right: 4px solid #ffc107; margin-bottom: 10px; display:none;">
                        <div class="card-body p-3 d-flex justify-between align-center">
                            <div>
                                <i class="fas fa-exclamation-triangle text-warning" style="margin-left: 10px;"></i>
                                <strong>بل واجب الادا:</strong> 
                                پارٹی <strong>${alert.khareedar_name}</strong> کی پرچی <strong>${alert.voucher_no}</strong> 
                                کا بقایا <strong>${Utils.formatNumber(alert.remaining_balance)} روپے</strong> 
                                <strong>(تاریخ: ${Utils.formatDate(alert.due_date)})</strong> ادا کرنا ہے۔
                            </div>
                            <div>
                                <a href="#sale?id=${alert.id}" class="btn btn-sm btn-outline">دیکھیں</a>
                            </div>
                        </div>
                    </div>
                `;
            });
            $('#dashboardAlerts').html(alertHtml);
        } else {
            $('#dashboardAlerts').empty();
        }

        // 2.6 Render Account Alerts (Credit Card deadlines etc.)
        if (stats.account_alerts && stats.account_alerts.length > 0) {
            let accAlertHtml = '';
            stats.account_alerts.forEach(alert => {
                accAlertHtml += `
                    <div class="card" style="background-color: #f8d7da; border-right: 4px solid #dc3545; margin-bottom: 10px;">
                        <div class="card-body p-3 d-flex justify-between align-center">
                            <div>
                                <i class="fas fa-credit-card text-danger" style="margin-left: 10px;"></i>
                                <strong>اکاؤنٹ ڈیڈ لائن:</strong> 
                                اکاؤنٹ <strong>${alert.name}</strong> کی ادائیگی کی تاریخ <strong>${Utils.formatDate(alert.alert_date)}</strong> قریب ہے!
                            </div>
                            <div class="d-flex gap-2">
                                ${alert.alert_interval_days > 0 ? `
                                    <button class="btn btn-sm btn-accent" onclick="renewAccAlert(${alert.id}, '${alert.name}', ${alert.alert_interval_days})">
                                        <i class="fas fa-sync-alt"></i> اگلی تاریخ (${alert.alert_interval_days} دن)
                                    </button>
                                ` : ''}
                                <a href="#setup-account" class="btn btn-sm btn-outline-danger">تفصیل دیکھیں</a>
                            </div>
                        </div>
                    </div>
                `;
            });
            $('#dashboardAlerts').append(accAlertHtml);
        }

        // 3. Populate Recent Activity (Mixed)
        const recent = [];
        const purchases = purchasesRes.data.data || [];
        const sales = salesRes.data.data || [];

        purchases.slice(0, 5).forEach(p => {
            recent.push({ id: p.voucher_no, party: p.zamidar_name, amount: (p.total_gross_amount || p.gross_amount), type: 'خرید', date: p.voucher_date });
        });
        sales.slice(0, 5).forEach(s => {
            recent.push({ id: s.voucher_no, party: s.khareedar_name, amount: s.gross_amount, type: 'فروخت', date: s.voucher_date });
        });

        // Sort by date/id descending
        recent.sort((a, b) => b.id.localeCompare(a.id));

        let html = '';
        recent.slice(0, 8).forEach(row => {
            html += `
                <tr>
                    <td>${row.id}</td>
                    <td>${row.party}</td>
                    <td class="fw-bold">${Utils.formatNumber(row.amount)}</td>
                    <td><span class="badge ${row.type === 'خرید' ? 'badge-info' : 'badge-success'}">${row.type}</span></td>
                </tr>
            `;
        });
        
        if (recent.length === 0) {
            html = '<tr><td colspan="4" class="text-center">آج کوئی سرگرمی نہیں ملی۔</td></tr>';
        }
        
        $('#recentActivityBody').html(html);

    } catch (err) {
        console.error("Dashboard Load Error:", err);
    }
}

// Function to push alert forward by interval days
async function renewAccAlert(id, name, days) {
    if (!confirm(`کیا آپ "${name}" کا الرٹ اگلے ${days} دن کیلئے بڑھانا چاہتے ہیں؟`)) return;
    
    try {
        const res = await API.post(`/accounts/${id}/renew-alert`);
        if (res.success) {
            Toast.success(res.message);
            initDashboard(); // Refresh dash to update date
        }
    } catch (err) {
        console.error("Renew Alert Error:", err);
    }
}
</script>
