<?php
// ── Prepare chart data ─────────────────────────────────────────────────────
$chartLabels  = array_column($salesChart, 'day');
$chartRevenue = array_column($salesChart, 'revenue');
$chartOrders  = array_column($salesChart, 'total_orders');

$statusLabels = array_column($statusDist, 'status');
$statusCounts = array_column($statusDist, 'cnt');

$hour = (int) date('H');
$greeting = $hour < 12 ? 'Good morning' : ($hour < 17 ? 'Good afternoon' : 'Good evening');
?>

<!-- ── Welcome Banner ────────────────────────────────────────────────────────── -->
<div class="dash-welcome mb-4">
    <div class="dash-welcome-text">
        <h1><?= $greeting ?>, <?= e(explode(' ', $authUser['name'])[0]) ?> 👋</h1>
        <p>Here's what's happening at <strong><?= e(APP_NAME) ?></strong> today, <?= date('l, d F Y') ?></p>
    </div>
    <div class="dash-welcome-actions">
        <a href="<?= url('orders/live') ?>" class="btn btn-accent">
            <i class="bi bi-lightning-charge-fill me-1"></i> Live Orders
            <?php if ($stats['pending_orders'] > 0): ?>
            <span class="badge bg-white text-accent ms-1" style="font-size:.7rem;"><?= $stats['pending_orders'] ?></span>
            <?php endif; ?>
        </a>
        <a href="<?= url('orders') ?>" class="btn btn-outline-secondary">
            <i class="bi bi-list-ul me-1"></i> All Orders
        </a>
    </div>
</div>

<!-- ── Stat Cards ────────────────────────────────────────────────────────────── -->
<div class="row g-3 mb-4">

    <div class="col-6 col-lg-3">
        <div class="dash-stat dash-stat--orange">
            <div class="dash-stat-icon"><i class="bi bi-bag-check-fill"></i></div>
            <div class="dash-stat-body">
                <div class="dash-stat-value"><?= number_format($stats['orders_today']) ?></div>
                <div class="dash-stat-label">Orders Today</div>
            </div>
            <?php if ($stats['pending_orders'] > 0): ?>
            <div class="dash-stat-badge"><?= $stats['pending_orders'] ?> pending</div>
            <?php endif; ?>
        </div>
    </div>

    <div class="col-6 col-lg-3">
        <div class="dash-stat dash-stat--green">
            <div class="dash-stat-icon"><i class="bi bi-cash-stack"></i></div>
            <div class="dash-stat-body">
                <div class="dash-stat-value"><?= money($stats['revenue_today']) ?></div>
                <div class="dash-stat-label">Revenue Today</div>
            </div>
            <div class="dash-stat-sub"><?= money($stats['revenue_month']) ?> this month</div>
        </div>
    </div>

    <div class="col-6 col-lg-3">
        <div class="dash-stat dash-stat--blue">
            <div class="dash-stat-icon"><i class="bi bi-people-fill"></i></div>
            <div class="dash-stat-body">
                <div class="dash-stat-value"><?= number_format($stats['total_customers']) ?></div>
                <div class="dash-stat-label">Total Customers</div>
            </div>
        </div>
    </div>

    <div class="col-6 col-lg-3">
        <div class="dash-stat dash-stat--purple">
            <div class="dash-stat-icon"><i class="bi bi-journal-richtext"></i></div>
            <div class="dash-stat-body">
                <div class="dash-stat-value"><?= number_format($stats['total_items']) ?></div>
                <div class="dash-stat-label">Active Menu Items</div>
            </div>
        </div>
    </div>

</div>

<!-- ── Quick Actions ─────────────────────────────────────────────────────────── -->
<div class="quick-actions mb-4">
    <a href="<?= url('orders/live') ?>" class="quick-action">
        <i class="bi bi-lightning-charge-fill"></i><span>Live Board</span>
    </a>
    <a href="<?= url('menu/create') ?>" class="quick-action">
        <i class="bi bi-plus-circle-fill"></i><span>Add Item</span>
    </a>
    <a href="<?= url('reports/sales') ?>" class="quick-action">
        <i class="bi bi-bar-chart-fill"></i><span>Reports</span>
    </a>
    <a href="<?= url('vouchers/create') ?>" class="quick-action">
        <i class="bi bi-ticket-perforated-fill"></i><span>New Voucher</span>
    </a>
    <a href="<?= url('deals/create') ?>" class="quick-action">
        <i class="bi bi-gift-fill"></i><span>New Deal</span>
    </a>
    <a href="<?= url('reports/invoices') ?>" class="quick-action">
        <i class="bi bi-receipt"></i><span>Invoices</span>
    </a>
</div>

<!-- ── Charts Row ─────────────────────────────────────────────────────────────── -->
<div class="row g-3 mb-4">

    <div class="col-12 col-xl-8">
        <div class="card h-100">
            <div class="card-header">
                <i class="bi bi-graph-up-arrow text-accent"></i>
                <h6 class="card-title">Revenue & Orders — Last 7 Days</h6>
                <span class="ms-auto badge" style="background:var(--accent-soft);color:var(--accent);font-size:.72rem;font-weight:600;padding:4px 10px;border-radius:20px;">
                    7-day view
                </span>
            </div>
            <div class="card-body">
                <?php if (empty($salesChart)): ?>
                <div class="text-center py-5 text-secondary">
                    <i class="bi bi-graph-up fs-1 d-block mb-2 opacity-25"></i>
                    No sales data yet — orders will appear here.
                </div>
                <?php else: ?>
                <canvas id="revenueChart" height="105"></canvas>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="col-12 col-xl-4">
        <div class="card h-100">
            <div class="card-header">
                <i class="bi bi-pie-chart-fill text-accent"></i>
                <h6 class="card-title">Order Status</h6>
                <span class="ms-auto" style="font-size:.72rem;color:var(--text-secondary);">30 days</span>
            </div>
            <div class="card-body d-flex align-items-center justify-content-center">
                <?php if (empty($statusDist)): ?>
                <div class="text-center text-secondary py-4">
                    <i class="bi bi-pie-chart fs-1 d-block mb-2 opacity-25"></i>No data yet
                </div>
                <?php else: ?>
                <canvas id="statusChart" style="max-height:220px;"></canvas>
                <?php endif; ?>
            </div>
        </div>
    </div>

</div>

<!-- ── Bottom Row ─────────────────────────────────────────────────────────────── -->
<div class="row g-3">

    <!-- Recent Orders -->
    <div class="col-12 col-xl-7">
        <div class="card">
            <div class="card-header">
                <i class="bi bi-clock-history text-accent"></i>
                <h6 class="card-title">Recent Orders</h6>
                <a href="<?= url('orders') ?>" class="btn btn-sm btn-outline-secondary ms-auto" style="font-size:.78rem;">
                    View All <i class="bi bi-arrow-right ms-1"></i>
                </a>
            </div>
            <div class="card-body p-0">
                <?php if (empty($recentOrders)): ?>
                <div class="p-5 text-center text-secondary">
                    <i class="bi bi-inbox fs-1 d-block mb-2 opacity-25"></i>
                    No orders yet — they will appear here.
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table mb-0">
                        <thead>
                            <tr>
                                <th>Order</th>
                                <th>Customer</th>
                                <th>Status</th>
                                <th>Amount</th>
                                <th class="d-none d-md-table-cell">Time</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recentOrders as $order): ?>
                            <tr>
                                <td>
                                    <span class="fw-700" style="font-size:.82rem;"><?= e($order['order_number']) ?></span>
                                </td>
                                <td style="font-size:.85rem;"><?= e($order['customer_name']) ?></td>
                                <td><?= order_status_badge($order['status']) ?></td>
                                <td class="fw-700" style="font-size:.85rem;"><?= money((float)$order['total_amount']) ?></td>
                                <td class="d-none d-md-table-cell text-secondary" style="font-size:.78rem;white-space:nowrap;"><?= time_ago($order['placed_at']) ?></td>
                                <td>
                                    <a href="<?= url('orders/' . $order['id']) ?>" class="btn btn-sm btn-outline-secondary rounded-pill">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Right column: Top Items + Revenue summary -->
    <div class="col-12 col-xl-5">

        <!-- Top Selling Items -->
        <div class="card mb-3">
            <div class="card-header">
                <i class="bi bi-trophy-fill text-warning"></i>
                <h6 class="card-title">Top Selling Items</h6>
                <span class="ms-auto" style="font-size:.72rem;color:var(--text-secondary);">Last 30 days</span>
            </div>
            <div class="card-body p-0">
                <?php if (empty($topItems)): ?>
                <div class="p-4 text-center text-secondary">
                    <i class="bi bi-bar-chart fs-1 d-block mb-2 opacity-25"></i>No sales data yet.
                </div>
                <?php else: ?>
                <?php foreach ($topItems as $i => $item): ?>
                <div class="top-item-row">
                    <div class="top-item-rank <?= $i === 0 ? 'rank-gold' : ($i === 1 ? 'rank-silver' : ($i === 2 ? 'rank-bronze' : '')) ?>">
                        <?= $i + 1 ?>
                    </div>
                    <div class="flex-grow-1 overflow-hidden">
                        <div class="fw-600" style="font-size:.85rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?= e($item['name']) ?></div>
                        <div style="font-size:.73rem;color:var(--text-secondary);"><?= number_format((float)$item['total_qty']) ?> sold</div>
                    </div>
                    <div class="fw-700 text-success" style="font-size:.85rem;white-space:nowrap;"><?= money((float)$item['total_revenue']) ?></div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Revenue Summary card -->
        <div class="card">
            <div class="card-header">
                <i class="bi bi-wallet2 text-accent"></i>
                <h6 class="card-title">Revenue Summary</h6>
            </div>
            <div class="card-body p-0">
                <div class="rev-summary-row">
                    <div class="rev-summary-icon" style="background:#fff4ee;color:#f97316;"><i class="bi bi-sun-fill"></i></div>
                    <div class="flex-grow-1">
                        <div class="rev-summary-label">Today</div>
                        <div class="rev-summary-val"><?= money($stats['revenue_today']) ?></div>
                    </div>
                </div>
                <div class="rev-summary-row">
                    <div class="rev-summary-icon" style="background:#f0fdf4;color:#22c55e;"><i class="bi bi-calendar-month-fill"></i></div>
                    <div class="flex-grow-1">
                        <div class="rev-summary-label">This Month</div>
                        <div class="rev-summary-val"><?= money($stats['revenue_month']) ?></div>
                    </div>
                </div>
                <div class="rev-summary-row" style="border-bottom:none;">
                    <div class="rev-summary-icon" style="background:#eff6ff;color:#3b82f6;"><i class="bi bi-bag-check-fill"></i></div>
                    <div class="flex-grow-1">
                        <div class="rev-summary-label">Orders Today</div>
                        <div class="rev-summary-val"><?= number_format($stats['orders_today']) ?></div>
                    </div>
                </div>
            </div>
        </div>

    </div>

</div>

<!-- ── Chart.js ───────────────────────────────────────────────────────────────── -->
<?php ob_start(); ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
<script>
(function () {
    const accent  = '#f97316';
    const accentT = 'rgba(249,115,22,.13)';

    // Revenue Line Chart
    const revCtx = document.getElementById('revenueChart');
    if (revCtx) {
        new Chart(revCtx, {
            type: 'line',
            data: {
                labels: <?= json_encode(array_map(fn($d) => date('d M', strtotime($d)), $chartLabels)) ?>,
                datasets: [{
                    label:           'Revenue (Rs.)',
                    data:            <?= json_encode(array_map('floatval', $chartRevenue)) ?>,
                    borderColor:     accent,
                    backgroundColor: accentT,
                    fill:            true,
                    tension:         .4,
                    pointRadius:     5,
                    pointBackgroundColor: '#fff',
                    pointBorderColor: accent,
                    pointBorderWidth: 2,
                    borderWidth:     2.5,
                }, {
                    label:           'Orders',
                    data:            <?= json_encode(array_map('intval', $chartOrders)) ?>,
                    borderColor:     '#3b82f6',
                    backgroundColor: 'rgba(59,130,246,.08)',
                    fill:            true,
                    tension:         .4,
                    pointRadius:     5,
                    pointBackgroundColor: '#fff',
                    pointBorderColor: '#3b82f6',
                    pointBorderWidth: 2,
                    borderWidth:     2.5,
                    yAxisID:         'y1',
                }]
            },
            options: {
                responsive: true,
                interaction: { mode: 'index', intersect: false },
                plugins: {
                    legend: { position: 'top', labels: { usePointStyle: true, boxWidth: 7, font: { size: 12 } } }
                },
                scales: {
                    x: { grid: { color: '#f1f3f5' }, ticks: { font: { size: 11 } } },
                    y:  {
                        beginAtZero: true,
                        grid: { color: '#f1f3f5' },
                        ticks: { callback: v => 'Rs.' + v.toLocaleString(), font: { size: 11 } }
                    },
                    y1: {
                        beginAtZero: true,
                        position: 'right',
                        grid: { drawOnChartArea: false },
                        ticks: { stepSize: 1, font: { size: 11 } }
                    },
                }
            }
        });
    }

    // Status Donut
    const stCtx = document.getElementById('statusChart');
    if (stCtx) {
        const colorMap = {
            pending:    '#f59e0b', confirmed: '#3b82f6', cooking: '#06b6d4',
            ready:      '#6b7280', picked_up: '#1e2235', on_the_way: '#7c3aed',
            delivered:  '#22c55e', cancelled: '#ef4444'
        };
        const labels = <?= json_encode($statusLabels) ?>;
        new Chart(stCtx, {
            type: 'doughnut',
            data: {
                labels: labels.map(l => l.replace(/_/g,' ').replace(/\b\w/g,c=>c.toUpperCase())),
                datasets: [{
                    data: <?= json_encode(array_map('intval', $statusCounts)) ?>,
                    backgroundColor: labels.map(l => colorMap[l] ?? '#cdd0d8'),
                    borderWidth: 0,
                    hoverOffset: 6,
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: { position: 'bottom', labels: { usePointStyle: true, boxWidth: 8, padding: 12, font: { size: 11 } } }
                },
                cutout: '68%'
            }
        });
    }
})();
</script>
<?php $extraJs = ob_get_clean(); ?>
