<form method="GET" action="<?= Router::url('reports') ?>" style="display:flex;gap:8px;align-items:center;margin-bottom:18px;flex-wrap:wrap;">
    <label style="font-size:12.5px;font-weight:700;">From</label>
    <input type="date" name="date_from" class="form-control" style="width:auto;" value="<?= e($dateFrom) ?>">
    <label style="font-size:12.5px;font-weight:700;">To</label>
    <input type="date" name="date_to" class="form-control" style="width:auto;" value="<?= e($dateTo) ?>">
    <button type="submit" class="btn btn-secondary"><i class="fa-solid fa-filter"></i> Apply</button>
</form>

<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">Orders</div>
        <div class="stat-value"><?= (int) $salesSummary['order_count'] ?></div>
        <div class="stat-sub">In selected range</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">Revenue</div>
        <div class="stat-value"><?= formatMoney((float) $salesSummary['revenue']) ?></div>
        <div class="stat-sub">Avg order <?= formatMoney((float) $salesSummary['avg_order_value']) ?></div>
    </div>
    <div class="stat-card <?= $pnl['net'] >= 0 ? 'c-green' : 'c-red' ?>">
        <div class="stat-icon"><i class="fa-solid fa-scale-balanced"></i></div>
        <div class="stat-label">Net P&amp;L</div>
        <div class="stat-value"><?= formatMoney($pnl['net']) ?></div>
        <div class="stat-sub">Income − Expenses − Payroll − Purchases</div>
    </div>
    <div class="stat-card c-gold">
        <div class="stat-icon"><i class="fa-solid fa-boxes-stacked"></i></div>
        <div class="stat-label">Stock Value (Current)</div>
        <div class="stat-value"><?= formatMoney(array_sum(array_column($stockValuation, 'stock_value'))) ?></div>
        <div class="stat-sub">Not date-range dependent</div>
    </div>
</div>

<div style="display:flex;gap:6px;margin-bottom:16px;flex-wrap:wrap;">
    <button type="button" class="btn btn-primary rms-tab-btn active" data-tab="sales" onclick="rmsSwitchTab('sales', this)"><i class="fa-solid fa-chart-line"></i> Sales Summary</button>
    <button type="button" class="btn btn-secondary rms-tab-btn" data-tab="items" onclick="rmsSwitchTab('items', this)"><i class="fa-solid fa-utensils"></i> Item Performance</button>
    <button type="button" class="btn btn-secondary rms-tab-btn" data-tab="pnl" onclick="rmsSwitchTab('pnl', this)"><i class="fa-solid fa-scale-balanced"></i> P&amp;L</button>
    <button type="button" class="btn btn-secondary rms-tab-btn" data-tab="stock" onclick="rmsSwitchTab('stock', this)"><i class="fa-solid fa-boxes-stacked"></i> Stock Valuation</button>
    <button type="button" class="btn btn-secondary rms-tab-btn" data-tab="delivery" onclick="rmsSwitchTab('delivery', this)"><i class="fa-solid fa-motorcycle"></i> Delivery Performance</button>
</div>

<!-- Sales Summary Tab -->
<div id="rms-tab-sales" class="rms-tab-panel">
    <div class="panel">
        <div class="panel-head">
            <h3>Daily Sales</h3>
            <a href="<?= Router::url('reports/export/sales?date_from=' . $dateFrom . '&date_to=' . $dateTo) ?>" class="link"><i class="fa-solid fa-file-csv"></i> Export CSV</a>
        </div>
        <table class="data-table">
        <thead><tr><th>Date</th><th>Orders</th><th>Revenue</th></tr></thead>
        <tbody>
        <?php foreach ($dailySales as $d): ?>
        <tr><td><?= date('d M Y (D)', strtotime($d['sales_date'])) ?></td><td><?= (int) $d['order_count'] ?></td><td><?= formatMoney((float) $d['revenue']) ?></td></tr>
        <?php endforeach; ?>
        <?php if (empty($dailySales)): ?>
        <tr><td colspan="3" style="text-align:center;color:var(--color-text-muted);padding:30px;">No sales in this range.</td></tr>
        <?php endif; ?>
        </tbody>
        </table>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
        <div class="panel">
            <h3 style="margin-bottom:12px;">Revenue by Channel</h3>
            <?php foreach ($revenueByChannel as $c): ?>
            <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--color-border);font-size:13px;">
                <span><?= e(str_replace('_', ' ', $c['channel'])) ?> <span class="badge badge-gray"><?= (int) $c['order_count'] ?></span></span>
                <strong><?= formatMoney((float) $c['revenue']) ?></strong>
            </div>
            <?php endforeach; ?>
        </div>
        <div class="panel">
            <h3 style="margin-bottom:12px;">Revenue by Order Status</h3>
            <?php foreach ($revenueByStatus as $s): ?>
            <div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--color-border);font-size:13px;">
                <span><?= e(str_replace('_', ' ', $s['status'])) ?> <span class="badge badge-gray"><?= (int) $s['order_count'] ?></span></span>
                <strong><?= formatMoney((float) $s['revenue']) ?></strong>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Item Performance Tab -->
<div id="rms-tab-items" class="rms-tab-panel" style="display:none;">
    <div class="panel">
        <div class="panel-head">
            <h3>Top Selling Items</h3>
            <a href="<?= Router::url('reports/export/items?date_from=' . $dateFrom . '&date_to=' . $dateTo) ?>" class="link"><i class="fa-solid fa-file-csv"></i> Export CSV</a>
        </div>
        <table class="data-table">
        <thead><tr><th>#</th><th>Item</th><th>Qty Sold</th><th>Revenue</th></tr></thead>
        <tbody>
        <?php foreach ($topItems as $i => $it): ?>
        <tr><td><?= $i + 1 ?></td><td><strong><?= e($it['item_name']) ?></strong></td><td><?= (int) $it['qty_sold'] ?></td><td><?= formatMoney((float) $it['revenue']) ?></td></tr>
        <?php endforeach; ?>
        <?php if (empty($topItems)): ?>
        <tr><td colspan="4" style="text-align:center;color:var(--color-text-muted);padding:30px;">No item sales in this range.</td></tr>
        <?php endif; ?>
        </tbody>
        </table>
    </div>
</div>

<!-- P&L Tab -->
<div id="rms-tab-pnl" class="rms-tab-panel" style="display:none;">
    <div class="panel">
        <div class="panel-head">
            <h3>Profit &amp; Loss (Cash Basis)</h3>
            <a href="<?= Router::url('reports/export/pnl?date_from=' . $dateFrom . '&date_to=' . $dateTo) ?>" class="link"><i class="fa-solid fa-file-csv"></i> Export CSV</a>
        </div>
        <div style="max-width:420px;">
            <div style="display:flex;justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--color-border);"><span>Income (Payments Collected)</span><strong style="color:var(--color-success);">+<?= formatMoney($pnl['income']) ?></strong></div>
            <div style="display:flex;justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--color-border);"><span>Expenses</span><strong style="color:var(--color-danger);">-<?= formatMoney($pnl['expenses']) ?></strong></div>
            <div style="display:flex;justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--color-border);"><span>Payroll Paid</span><strong style="color:var(--color-danger);">-<?= formatMoney($pnl['payroll']) ?></strong></div>
            <div style="display:flex;justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--color-border);"><span>Supplier Payments</span><strong style="color:var(--color-danger);">-<?= formatMoney($pnl['purchases']) ?></strong></div>
            <div style="display:flex;justify-content:space-between;padding:14px 0;font-size:16px;font-weight:700;"><span>Net P&amp;L</span><span style="color:<?= $pnl['net'] >= 0 ? 'var(--color-success)' : 'var(--color-danger)' ?>;"><?= formatMoney($pnl['net']) ?></span></div>
        </div>
        <div style="font-size:11.5px;color:var(--color-text-muted);margin-top:10px;">
            Cash-basis: counts money actually collected/paid within the date range (not accrual). Payments collected may include orders placed before this range; expenses/payroll/purchases are counted on their paid date.
        </div>
    </div>
</div>

<!-- Stock Valuation Tab -->
<div id="rms-tab-stock" class="rms-tab-panel" style="display:none;">
    <div class="panel">
        <h3 style="margin-bottom:12px;">Current Stock Valuation <span style="font-weight:400;color:var(--color-text-muted);font-size:12px;">(snapshot — not date-range dependent)</span></h3>
        <table class="data-table">
        <thead><tr><th>Material</th><th>Current Stock</th><th>Unit Cost</th><th>Stock Value</th></tr></thead>
        <tbody>
        <?php foreach ($stockValuation as $s): ?>
        <tr>
            <td><?= e($s['material_name']) ?></td>
            <td><?= number_format((float) $s['current_stock'], 2) ?> <?= e($s['unit']) ?></td>
            <td><?= formatMoney((float) $s['unit_cost']) ?></td>
            <td><strong><?= formatMoney((float) $s['stock_value']) ?></strong></td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($stockValuation)): ?>
        <tr><td colspan="4" style="text-align:center;color:var(--color-text-muted);padding:30px;">No raw materials tracked yet.</td></tr>
        <?php endif; ?>
        </tbody>
        </table>
    </div>
</div>

<!-- Delivery Performance Tab -->
<div id="rms-tab-delivery" class="rms-tab-panel" style="display:none;">
    <div class="panel">
        <h3 style="margin-bottom:12px;">Rider Performance</h3>
        <table class="data-table">
        <thead><tr><th>Rider</th><th>Delivered</th><th>Failed</th><th>Success Rate</th></tr></thead>
        <tbody>
        <?php foreach ($deliveryPerf as $d):
            $total = $d['delivered'] + $d['failed'];
            $rate = $total > 0 ? round(($d['delivered'] / $total) * 100, 1) : 0;
        ?>
        <tr>
            <td><?= e($d['rider_name'] ?? 'Unassigned') ?></td>
            <td><span class="badge badge-green"><?= (int) $d['delivered'] ?></span></td>
            <td><span class="badge badge-red"><?= (int) $d['failed'] ?></span></td>
            <td><?= $rate ?>%</td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($deliveryPerf)): ?>
        <tr><td colspan="4" style="text-align:center;color:var(--color-text-muted);padding:30px;">No delivery data in this range.</td></tr>
        <?php endif; ?>
        </tbody>
        </table>
    </div>
</div>

<script>
function rmsSwitchTab(tab, btn) {
    document.querySelectorAll('.rms-tab-panel').forEach(p => p.style.display = 'none');
    document.getElementById('rms-tab-' + tab).style.display = 'block';
    document.querySelectorAll('.rms-tab-btn').forEach(b => { b.classList.remove('btn-primary'); b.classList.add('btn-secondary'); });
    btn.classList.remove('btn-secondary'); btn.classList.add('btn-primary');
}
</script>
