<?php
$hour = (int) date('G');
$greeting = $hour < 12 ? 'Good Morning' : ($hour < 17 ? 'Good Afternoon' : 'Good Evening');
$salesChange = $yesterdaySales > 0 ? round((($todaySales - $yesterdaySales) / $yesterdaySales) * 100, 1) : null;
$statusBadge = ['PENDING' => 'badge-gray', 'CONFIRMED' => 'badge-blue', 'PREPARING' => 'badge-gold', 'READY' => 'badge-gold', 'OUT_FOR_DELIVERY' => 'badge-blue', 'COMPLETED' => 'badge-green', 'CANCELLED' => 'badge-red'];
?>

<div class="greeting-banner">
    <div>
        <h2><?= $greeting ?>, <?= e(Auth::user()['full_name']) ?>!</h2>
        <div class="meta">
            <span><i class="fa-regular fa-calendar"></i> <?= date('l, d M Y') ?></span>
            <span><i class="fa-solid fa-shop"></i> <?= e(setting('company_name', 'Rice & Curry')) ?></span>
            <span><i class="fa-regular fa-clock"></i> <?= date('H:i:s') ?></span>
        </div>
    </div>
    <div class="banner-actions">
        <a href="<?= Router::url('reports') ?>" class="btn btn-outline"><i class="fa-solid fa-file-lines"></i> Daily Report</a>
        <a href="<?= Router::url('orders/create') ?>" class="btn btn-teal"><i class="fa-solid fa-plus"></i> New Order</a>
    </div>
</div>

<!-- Smart Alerts -->
<?php if (!empty($alerts)): ?>
<div class="smart-alerts">
    <?php foreach ($alerts as $a): ?>
    <a href="<?= Router::url($a['link']) ?>" class="smart-alert sa-<?= $a['color'] ?>">
        <i class="fa-solid <?= $a['icon'] ?>"></i>
        <span><?= e($a['text']) ?></span>
        <i class="fa-solid fa-arrow-right sa-arrow"></i>
    </a>
    <?php endforeach; ?>
</div>
<?php else: ?>
<div class="smart-alerts">
    <div class="smart-alert sa-green"><i class="fa-solid fa-circle-check"></i><span>All clear — no urgent issues right now.</span></div>
</div>
<?php endif; ?>

<!-- Quick Actions -->
<div class="quick-actions">
    <a href="<?= Router::url('orders/create') ?>" class="qa-btn"><i class="fa-solid fa-plus"></i> New Order</a>
    <a href="<?= Router::url('menu/items/create') ?>" class="qa-btn"><i class="fa-solid fa-utensils"></i> Add Menu Item</a>
    <a href="<?= Router::url('attendance') ?>" class="qa-btn"><i class="fa-solid fa-clipboard-check"></i> Mark Attendance</a>
    <a href="<?= Router::url('delivery') ?>" class="qa-btn"><i class="fa-solid fa-motorcycle"></i> Delivery Board</a>
    <a href="<?= Router::url('reports') ?>" class="qa-btn"><i class="fa-solid fa-chart-line"></i> View Reports</a>
</div>

<a href="<?= Router::url('app-customers') ?>" style="text-decoration:none;display:block;margin-bottom:20px;">
    <div style="background:linear-gradient(120deg, #1B5FA8, #123E70);border-radius:var(--radius);padding:16px 20px;color:#fff;display:flex;align-items:center;justify-content:space-between;">
        <div style="display:flex;align-items:center;gap:14px;">
            <div style="width:42px;height:42px;border-radius:11px;background:rgba(255,255,255,0.15);display:flex;align-items:center;justify-content:center;font-size:18px;"><i class="fa-solid fa-users"></i></div>
            <div>
                <div style="font-size:11px;color:rgba(255,255,255,0.7);text-transform:uppercase;letter-spacing:0.04em;font-weight:700;">App Customers</div>
                <div style="font-size:16px;font-weight:700;">
                    <span style="display:inline-flex;align-items:center;gap:5px;"><i class="fa-solid fa-circle" style="font-size:8px;color:#8FE0A0;"></i> <?= (int) $appCustomersOnline ?> Online Now</span>
                    <span style="font-size:12px;font-weight:400;color:rgba(255,255,255,0.75);"> · <?= (int) $appCustomersTotal ?> registered total</span>
                </div>
            </div>
        </div>
        <i class="fa-solid fa-arrow-right" style="opacity:0.7;"></i>
    </div>
</a>

<div class="grid-cards">
    <div class="stat-card c-blue">
        <div class="stat-icon"><i class="fa-solid fa-receipt"></i></div>
        <div class="stat-label">Today's Sales</div>
        <div class="stat-value"><?= formatMoney((float) $todaySales) ?></div>
        <div class="stat-sub">
            <?= (int) $todayOrderCount ?> orders
            <?php if ($salesChange !== null): ?>
            · <i class="fa-solid <?= $salesChange >= 0 ? 'fa-arrow-up' : 'fa-arrow-down' ?>"></i> <?= abs($salesChange) ?>% vs yesterday
            <?php endif; ?>
        </div>
    </div>
    <div class="stat-card c-green">
        <div class="stat-icon"><i class="fa-solid fa-arrow-trend-up"></i></div>
        <div class="stat-label">MTD Sales</div>
        <div class="stat-value"><?= formatMoney((float) $mtdSales) ?></div>
        <div class="stat-sub">This month so far</div>
    </div>
    <div class="stat-card c-purple">
        <div class="stat-icon"><i class="fa-solid fa-motorcycle"></i></div>
        <div class="stat-label">Out for Delivery</div>
        <div class="stat-value"><?= (int) $outForDelivery ?></div>
        <div class="stat-sub"><?= (int) $pendingOrders ?> pending in kitchen</div>
    </div>
    <div class="stat-card c-red">
        <div class="stat-icon"><i class="fa-solid fa-chart-pie"></i></div>
        <div class="stat-label">MTD Net (Sales − Expenses)</div>
        <div class="stat-value"><?= formatMoney((float) $netMtd) ?></div>
        <div class="stat-sub">Expenses <?= formatMoney((float) $totalExpenses) ?></div>
    </div>
</div>

<div style="display:grid;grid-template-columns:1.6fr 1fr;gap:18px;align-items:start;">
    <div>
        <div class="panel">
            <div class="panel-head">
                <h3><i class="fa-solid fa-chart-line" style="color:var(--color-teal);margin-right:6px;"></i>Sales Trend — Last 7 Days</h3>
            </div>
            <canvas id="rmsSalesTrendChart" height="90"></canvas>
        </div>

        <div class="panel">
            <div class="panel-head">
                <h3><i class="fa-solid fa-receipt" style="color:var(--color-teal);margin-right:6px;"></i>Recent Orders</h3>
                <a href="<?= Router::url('orders') ?>" class="link">View All <i class="fa-solid fa-arrow-right"></i></a>
            </div>
            <table class="data-table">
            <thead><tr><th>Order #</th><th>Customer</th><th>Total</th><th>Status</th><th>Placed</th></tr></thead>
            <tbody>
            <?php foreach ($recentOrders as $o): ?>
            <tr>
                <td><a href="<?= Router::url('orders/show?id=' . $o['id']) ?>"><strong><?= e($o['order_number']) ?></strong></a></td>
                <td><?= e($o['customer_name'] ?? 'Walk-in') ?></td>
                <td><?= formatMoney((float) $o['total_amount']) ?></td>
                <td><span class="badge <?= $statusBadge[$o['status']] ?? 'badge-gray' ?>"><?= e(str_replace('_', ' ', $o['status'])) ?></span></td>
                <td><?= date('d M, h:i A', strtotime($o['created_at'])) ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($recentOrders)): ?>
            <tr><td colspan="5" style="text-align:center;color:var(--color-text-muted);padding:20px;">No orders yet.</td></tr>
            <?php endif; ?>
            </tbody>
            </table>
        </div>

        <div class="panel">
            <div class="panel-head">
                <h3><i class="fa-solid fa-chart-line" style="color:var(--color-teal);margin-right:6px;"></i>Accounting Snapshot — <?= date('F Y') ?></h3>
                <a href="<?= Router::url('finance') ?>" class="link">Full Finance <i class="fa-solid fa-arrow-right"></i></a>
            </div>
            <div class="snapshot-grid">
                <div class="snapshot-card sc-red">
                    <div class="s-label">Net (MTD)</div>
                    <div class="s-value"><?= formatMoney((float) $netMtd) ?></div>
                    <div class="s-sub">Sales − Expenses</div>
                </div>
                <div class="snapshot-card sc-blue">
                    <div class="s-label">Cash &amp; Bank</div>
                    <div class="s-value"><?= formatMoney((float) $cashBalance) ?></div>
                    <div class="s-sub">All active accounts</div>
                </div>
                <div class="snapshot-card sc-gold">
                    <div class="s-label">Expenses (MTD)</div>
                    <div class="s-value"><?= formatMoney((float) $totalExpenses) ?></div>
                    <a href="<?= Router::url('finance') ?>" class="s-link">View Expenses <i class="fa-solid fa-arrow-right"></i></a>
                </div>
                <div class="snapshot-card sc-red">
                    <div class="s-label">Payables</div>
                    <div class="s-value"><?= formatMoney((float) $totalPayables) ?></div>
                    <a href="<?= Router::url('suppliers') ?>" class="s-link">View Suppliers <i class="fa-solid fa-arrow-right"></i></a>
                </div>
            </div>
        </div>
    </div>

    <div>
        <div class="panel">
            <h3 style="margin-bottom:12px;"><i class="fa-solid fa-trophy" style="color:var(--color-accent);margin-right:6px;"></i>Today's Top Items</h3>
            <?php foreach ($topItemsToday as $i => $it): ?>
            <div class="top-item-row">
                <div class="ti-rank">#<?= $i + 1 ?></div>
                <div class="ti-body">
                    <div class="ti-name"><?= e($it['item_name']) ?></div>
                    <div class="ti-sub"><?= (int) $it['qty_sold'] ?> sold</div>
                </div>
                <div class="ti-revenue"><?= formatMoney((float) $it['revenue']) ?></div>
            </div>
            <?php endforeach; ?>
            <?php if (empty($topItemsToday)): ?>
            <div style="text-align:center;color:var(--color-text-muted);font-size:12.5px;padding:20px 0;">No sales yet today.</div>
            <?php endif; ?>
        </div>

        <div class="panel">
            <h3 style="margin-bottom:12px;"><i class="fa-solid fa-clock-rotate-left" style="color:var(--color-teal);margin-right:6px;"></i>Recent Activity</h3>
            <?php foreach ($recentActivity as $log): ?>
            <div class="activity-row">
                <div class="ar-dot"></div>
                <div class="ar-body">
                    <div class="ar-text"><strong><?= e($log['full_name'] ?? 'System') ?></strong> <?= e(strtolower(str_replace('_', ' ', $log['action']))) ?></div>
                    <div class="ar-time"><?= date('d M, h:i A', strtotime($log['created_at'])) ?></div>
                </div>
            </div>
            <?php endforeach; ?>
            <?php if (empty($recentActivity)): ?>
            <div style="text-align:center;color:var(--color-text-muted);font-size:12.5px;padding:20px 0;">No activity yet.</div>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
.smart-alerts { display: flex; flex-direction: column; gap: 8px; margin-bottom: 18px; }
.smart-alert {
    display: flex; align-items: center; gap: 10px; padding: 12px 16px; border-radius: 10px; font-size: 13px; font-weight: 600;
    border: 1px solid transparent;
}
.smart-alert .sa-arrow { margin-left: auto; opacity: 0.6; font-size: 11px; }
.sa-red { background: #FBEBEB; border-color: #F2D2D2; color: #8A2A2A; }
.sa-gold { background: #FDF3E4; border-color: #F5E0BC; color: #8A611F; }
.sa-blue { background: #EAF1FB; border-color: #CFDFF5; color: #2E5FB0; }
.sa-green { background: #EEF3EA; border-color: #D3E0CA; color: #3D5830; }

.quick-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 20px; }
.qa-btn {
    flex: 1; min-width: 140px; display: flex; align-items: center; justify-content: center; gap: 8px;
    padding: 12px 14px; background: var(--color-surface); border: 1px solid var(--color-border); border-radius: 10px;
    font-size: 12.5px; font-weight: 700; color: var(--color-text); box-shadow: var(--shadow-sm);
    transition: transform 0.15s ease, box-shadow 0.15s ease;
}
.qa-btn:hover { transform: translateY(-2px); box-shadow: var(--shadow-md); color: var(--color-teal); }
.qa-btn i { color: var(--color-accent); }

.top-item-row { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-bottom: 1px solid var(--color-border); }
.top-item-row:last-child { border-bottom: none; }
.ti-rank { width: 26px; height: 26px; border-radius: 50%; background: var(--color-bg); color: var(--color-text-muted); font-size: 11px; font-weight: 700; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.ti-body { flex: 1; min-width: 0; }
.ti-name { font-size: 12.5px; font-weight: 700; }
.ti-sub { font-size: 11px; color: var(--color-text-muted); }
.ti-revenue { font-size: 12.5px; font-weight: 700; color: var(--color-accent); white-space: nowrap; }

.activity-row { display: flex; gap: 10px; padding: 8px 0; border-bottom: 1px solid var(--color-border); }
.activity-row:last-child { border-bottom: none; }
.ar-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--color-teal); margin-top: 5px; flex-shrink: 0; }
.ar-text { font-size: 12px; }
.ar-time { font-size: 10.5px; color: var(--color-text-muted); margin-top: 2px; }
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
<script>
const rmsCtx = document.getElementById('rmsSalesTrendChart');
new Chart(rmsCtx, {
    type: 'line',
    data: {
        labels: <?= json_encode($salesTrendLabels) ?>,
        datasets: [{
            label: 'Revenue',
            data: <?= json_encode($salesTrendData) ?>,
            borderColor: '#1D7A8C',
            backgroundColor: 'rgba(29,122,140,0.1)',
            fill: true,
            tension: 0.35,
            pointBackgroundColor: '#1D7A8C',
            pointRadius: 4,
        }]
    },
    options: {
        responsive: true,
        plugins: { legend: { display: false } },
        scales: {
            y: { beginAtZero: true, ticks: { callback: v => 'Rs.' + v } },
            x: { grid: { display: false } }
        }
    }
});
</script>
