<div class="page-header">
    <div>
        <h1>Welcome back, <?= e(explode(' ', Auth::user()['name'])[0]) ?></h1>
        <div class="page-subtitle">Here's what's happening in your store today.</div>
    </div>
    <div class="flex gap-2">
        <a href="<?= APP_URL ?>/sales/pos" class="btn btn-primary">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg>
            Open POS
        </a>
    </div>
</div>

<?php if ($subscription && $subscription['slug'] === 'free'): ?>
<div class="alert alert-info">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
    <div>
        <strong>You are on the Free plan.</strong> Upgrade to Pro or Business to unlock advanced reports, multiple locations, and unlimited products. 
        <a href="<?= APP_URL ?>/billing" style="text-decoration:underline;">Upgrade now</a>.
    </div>
</div>
<?php endif; ?>

<!-- Stats Grid -->
<div class="stats-grid">
    <?php if (Auth::can('dashboard.sales_today')): ?>
    <a href="<?= APP_URL ?>/reports?report=sales&date_from=<?= $todayDate ?>&date_to=<?= $todayDate ?>" class="stat-card" style="text-decoration: none; cursor: pointer;">
        <div class="stat-icon primary">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="1" x2="12" y2="23"></line><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path></svg>
        </div>
        <div class="stat-info">
            <div class="stat-label">Sales Today</div>
            <div class="stat-value"><?= money($todaySales['revenue']) ?></div>
            <div class="stat-change text-muted"><?= number_format($todaySales['count']) ?> receipts</div>
        </div>
    </a>
    <?php endif; ?>

    <?php if (Auth::can('dashboard.purchase_today')): ?>
    <a href="<?= APP_URL ?>/reports?report=purchases&date_from=<?= $todayDate ?>&date_to=<?= $todayDate ?>" class="stat-card" style="text-decoration: none; cursor: pointer;">
        <div class="stat-icon purple">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 3h18v18H3zM3 9h18M9 21V9"/></svg>
        </div>
        <div class="stat-info">
            <div class="stat-label">Purchase Today</div>
            <div class="stat-value"><?= money($todayPurchases['total']) ?></div>
            <div class="stat-change text-muted"><?= number_format($todayPurchases['count']) ?> orders</div>
        </div>
    </a>
    <?php endif; ?>

    <?php if (Auth::can('dashboard.total_products')): ?>
    <a href="<?= APP_URL ?>/products" class="stat-card" style="text-decoration: none; cursor: pointer;">
        <div class="stat-icon success">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path></svg>
        </div>
        <div class="stat-info">
            <div class="stat-label">Total Products</div>
            <div class="stat-value"><?= number_format($totalProducts) ?></div>
            <div class="stat-change text-muted">Active items</div>
        </div>
    </a>
    <?php endif; ?>

    <?php if (Auth::can('dashboard.alerts')): ?>
    <a href="<?= APP_URL ?>/reports?report=inventory" class="stat-card" style="text-decoration: none; cursor: pointer;">
        <div class="stat-icon danger">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>
        </div>
        <div class="stat-info">
            <div class="stat-label">Alerts</div>
            <div class="stat-value"><?= number_format($lowStockCount + $expiringCount) ?></div>
            <div class="stat-change text-muted">
                <span class="<?= $lowStockCount>0?'text-danger':'' ?>"><?= $lowStockCount ?> low st.</span>,
                <span class="<?= $expiringCount>0?'text-danger':'' ?>"><?= $expiringCount ?> exp.</span>
            </div>
        </div>
    </a>
    <?php endif; ?>

    <?php if (Auth::can('dashboard.sales_today')): ?>
    <a href="<?= APP_URL ?>/sales" class="stat-card" style="text-decoration: none; cursor: pointer;">
        <div class="stat-icon danger">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path></svg>
        </div>
        <div class="stat-info">
            <div class="stat-label">Customer Due</div>
            <div class="stat-value"><?= money($totalCustomerDue) ?></div>
            <div class="stat-change text-muted">Total outstanding</div>
        </div>
    </a>
    <?php endif; ?>

    <?php if (Auth::can('dashboard.total_products')): ?>
    <a href="<?= APP_URL ?>/reports?report=stock-valuation" class="stat-card" style="text-decoration: none; cursor: pointer;">
        <div class="stat-icon success">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path></svg>
        </div>
        <div class="stat-info">
            <div class="stat-label">Stock Value</div>
            <div class="stat-value"><?= money($stockValue) ?></div>
            <div class="stat-change text-muted">At cost price</div>
        </div>
    </a>
    <?php endif; ?>

    <?php if (Auth::can('dashboard.total_products')): ?>
    <a href="<?= APP_URL ?>/reports?report=stock-valuation" class="stat-card" style="text-decoration: none; cursor: pointer;">
        <div class="stat-icon primary">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path></svg>
        </div>
        <div class="stat-info">
            <div class="stat-label">Stock Value</div>
            <div class="stat-value"><?= money($stockValueRetail) ?></div>
            <div class="stat-change text-muted">At sales price</div>
        </div>
    </a>
    <?php endif; ?>

    <?php if (Auth::can('dashboard.total_month')): ?>
    <a href="<?= APP_URL ?>/reports?report=sales&date_from=<?= date('Y-m-01') ?>&date_to=<?= date('Y-m-t') ?>" class="stat-card" style="text-decoration: none; cursor: pointer;">
        <div class="stat-icon accent">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="1" x2="12" y2="23"></line><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path></svg>
        </div>
        <div class="stat-info">
            <div class="stat-label">Total This Month</div>
            <div class="stat-value"><?= money($monthSales['revenue']) ?></div>
            <div class="stat-change text-muted"><?= number_format($monthSales['count']) ?> receipts</div>
        </div>
    </a>
    <?php endif; ?>
</div>

<!-- Charts & Tables -->
<?php if (Auth::can('dashboard.revenue_chart') || Auth::can('dashboard.recent_sales')): ?>
<div class="grid-2 mb-6">
    <?php if (Auth::can('dashboard.revenue_chart')): ?>
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Revenue (Last 7 Days)</h3>
        </div>
        <div style="height: 300px; position: relative;">
            <canvas id="revenueChart"></canvas>
        </div>
    </div>
    <?php endif; ?>

    <?php if (Auth::can('dashboard.recent_sales')): ?>
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Recent Sales</h3>
            <a href="<?= APP_URL ?>/sales" class="btn btn-outline btn-sm">View All</a>
        </div>
        <?php if ($recentSales): ?>
            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th>Ref No</th>
                            <th>Customer</th>
                            <th>Amount</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recentSales as $sale): ?>
                        <tr>
                            <td><strong><?= e($sale['sale_no']) ?></strong></td>
                            <td><?= e($sale['customer_name'] ?? 'Walk-in') ?></td>
                            <td><?= money($sale['total']) ?></td>
                            <td>
                                <?php if ($sale['payment_status'] === 'paid'): ?>
                                    <span class="badge badge-success">Paid</span>
                                <?php elseif ($sale['payment_status'] === 'partial'): ?>
                                    <span class="badge badge-info">Partial</span>
                                <?php else: ?>
                                    <span class="badge badge-danger">Credit</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="empty-state" style="padding: 30px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
                <h3 style="color:var(--text-muted);">No sales yet</h3>
                <p>Start selling through the POS to see records here.</p>
            </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php if (Auth::can('dashboard.low_stock')): ?>
<div class="card mb-6">
    <div class="card-header">
        <h3 class="card-title">Low Stock Items</h3>
        <a href="<?= APP_URL ?>/reports/inventory" class="btn btn-outline btn-sm">Full Report</a>
    </div>
    <?php if ($lowStockItems): ?>
        <div class="grid-3">
            <?php foreach ($lowStockItems as $item): ?>
            <div style="padding:16px; border:1px solid var(--border); border-radius:var(--radius-sm); display:flex; justify-content:space-between; align-items:center;">
                <div>
                    <div style="font-weight:600; font-size:0.9rem; margin-bottom:2px;"><?= e($item['name']) ?></div>
                    <div style="font-size:0.75rem; color:var(--text-muted);">SKU: <?= e($item['sku']) ?></div>
                </div>
                <div style="text-align:right;">
                    <div style="font-size:1.1rem; font-weight:800; color:var(--danger);"><?= (float)$item['total'] ?></div>
                    <div style="font-size:0.65rem; color:var(--text-muted);">Alert at <?= (float)$item['alert_qty'] ?></div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="empty-state" style="padding: 20px;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
            <h3 style="color:var(--success);">All stock levels are healthy!</h3>
        </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php if (Auth::can('dashboard.expiring')): ?>
<div class="card mb-6">
    <div class="card-header">
        <h3 class="card-title">Expiring Products</h3>
        <a href="<?= APP_URL ?>/reports?report=expiry" class="btn btn-outline btn-sm">Full Report</a>
    </div>
    <?php if ($expiringItems): ?>
        <div class="grid-3">
            <?php foreach ($expiringItems as $item): ?>
            <?php
            $isExpired = $item['days_to_expiry'] < 0;
            $isExpiringSoon = $item['days_to_expiry'] <= 30 && $item['days_to_expiry'] >= 0;
            $textColor = $isExpired ? 'var(--danger)' : ($isExpiringSoon ? 'var(--warning)' : 'var(--text)');
            $bgColor = $isExpired ? 'rgba(239,68,68,0.1)' : ($isExpiringSoon ? 'rgba(245,158,11,0.1)' : 'transparent');
            ?>
            <div style="padding:16px; border:1px solid var(--border); border-radius:var(--radius-sm); display:flex; justify-content:space-between; align-items:center; background:<?= $bgColor ?>;">
                <div>
                    <div style="font-weight:600; font-size:0.9rem; margin-bottom:2px;"><?= e($item['product']) ?></div>
                    <div style="font-size:0.75rem; color:var(--text-muted);">Batch: <?= e($item['batch_no']) ?></div>
                </div>
                <div style="text-align:right;">
                    <div style="font-size:1.1rem; font-weight:800; color:<?= $textColor ?>;">
                        <?= $isExpired ? abs($item['days_to_expiry']) . 'd ago' : $item['days_to_expiry'] . 'd' ?>
                    </div>
                    <div style="font-size:0.65rem; color:var(--text-muted);">Qty: <?= (float)$item['quantity'] ?></div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="empty-state" style="padding: 20px;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line></svg>
            <h3 style="color:var(--success);">No products expiring soon!</h3>
        </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- Chart.js -->
<script src="<?= APP_URL ?>/assets/chart.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('revenueChart');
    if (!ctx) {
        console.error('revenueChart canvas not found');
        return;
    }

    // Prepare data
    const rawData = <?= json_encode($weeklyRevenue) ?>;
    console.log('Weekly revenue data:', rawData);

    const labels = [];
    const dataObj = {};
    
    // Fill last 7 days
    for (let i=6; i>=0; i--) {
        const d = new Date();
        d.setDate(d.getDate() - i);
        const dateStr = d.toISOString().split('T')[0];
        labels.push(d.toLocaleDateString('en-US', {weekday:'short', month:'short', day:'numeric'}));
        dataObj[dateStr] = 0;
    }
    
    rawData.forEach(row => {
        if(dataObj[row.date] !== undefined) {
            dataObj[row.date] = parseFloat(row.revenue);
        }
    });

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Revenue',
                data: Object.values(dataObj),
                borderColor: '#6366f1',
                backgroundColor: 'rgba(99,102,241,0.1)',
                borderWidth: 3,
                pointBackgroundColor: '#818cf8',
                pointBorderColor: '#fff',
                pointRadius: 4,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: { color: 'rgba(255,255,255,0.05)', drawBorder: false },
                    ticks: { color: '#94a3b8' }
                },
                x: {
                    grid: { display: false, drawBorder: false },
                    ticks: { color: '#94a3b8' }
                }
            }
        }
    });
});
</script>
