<?php
// dashboards/dispatch.php — included by dashboard.php (session already started)
$username = $_SESSION['username'] ?? 'Dispatch';

// ── QUERY DATA SERVER-SIDE ────────────────────────────────
$db = new db_safeguard();

// Low stock (status <= 1)
$low_res  = $db->query("stock",
    "SELECT stock_no, item_name, type, size, unit_of_measure, status
     FROM stock
     WHERE status <= 1
     ORDER BY status ASC, item_name ASC"
);
$low_stock = [];
while ($row = $low_res->fetch_assoc()) $low_stock[] = $row;

// Booked out stock
// ⚠️ Change 'BOOKED' to match your actual status value if different
$booked_res = $db->query("stock_trans",
    "SELECT st.stock_no, st.item_name, st.quantity, st.order_no,
            st.datetime_created, st.status,
            s.type, s.size, s.unit_of_measure
     FROM stock_trans st
     LEFT JOIN stock s ON s.stock_no = st.stock_no
     WHERE st.status = 'BOOKED'
     ORDER BY st.datetime_created DESC"
);
$booked_stock = [];
while ($row = $booked_res->fetch_assoc()) $booked_stock[] = $row;

function d_esc($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dispatch Dashboard</title>
    <link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=DM+Sans:wght@300;400;500;600&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        :root {
            --bg:         #f0f4fa;
            --surface:    #ffffff;
            --border:     #d0daea;
            --blue:       #1a56c4;
            --blue-light: #e8f0fd;
            --orange:     #e8720a;
            --red:        #dc2626;
            --red-light:  #fee2e2;
            --text:       #0f1e3d;
            --muted:      #6b7fa8;
            --white:      #ffffff;
            --radius:     8px;
        }
        html, body { height:100%; background:var(--bg); color:var(--text);
            font-family:'DM Sans', sans-serif; }
        .shell { display:grid; grid-template-rows:52px 1fr; height:100vh; }

        /* TOPBAR */
        .topbar { display:flex; align-items:center; justify-content:space-between;
            padding:0 24px; background:var(--blue); gap:16px; }
        .topbar-left { display:flex; align-items:center; gap:14px; }
        .logo-mark { width:28px; height:28px; background:var(--orange); flex-shrink:0;
            clip-path:polygon(50% 0%,100% 25%,100% 75%,50% 100%,0% 75%,0% 25%); }
        .page-title { font-family:'Bebas Neue'; font-size:20px; letter-spacing:2px; color:#fff; }
        .page-title span { color:var(--orange); }
        .divider-v { width:1px; height:24px; background:rgba(255,255,255,.25); }
        .role-badge { padding:3px 10px; border-radius:20px; background:var(--orange);
            font-size:11px; font-weight:700; letter-spacing:1px; color:#fff; text-transform:uppercase; }
        .user-name { font-size:13px; color:rgba(255,255,255,.85); font-weight:500; }
        .btn-refresh { display:flex; align-items:center; gap:6px; padding:6px 14px;
            background:rgba(255,255,255,.12); border:1px solid rgba(255,255,255,.25);
            color:#fff; border-radius:var(--radius); font-family:'DM Sans'; font-size:12px;
            font-weight:600; cursor:pointer; text-decoration:none; transition:background .2s; }
        .btn-refresh:hover { background:rgba(255,255,255,.22); }

        /* GRID */
        .main { display:grid; grid-template-columns:1fr 1fr; gap:12px;
            padding:12px; overflow:hidden; height:100%; }

        /* PANEL */
        .panel { background:var(--white); border:1px solid var(--border);
            border-radius:var(--radius); display:flex; flex-direction:column;
            overflow:hidden; position:relative; box-shadow:0 1px 4px rgba(26,86,196,.07); }
        .panel::before { content:''; position:absolute; top:0; left:0; right:0; height:3px;
            border-radius:var(--radius) var(--radius) 0 0; }
        .panel-low::before  { background:linear-gradient(90deg, var(--red), var(--orange)); }
        .panel-book::before { background:linear-gradient(90deg, var(--blue), var(--orange)); }

        .panel-head { display:flex; align-items:center; justify-content:space-between;
            padding:10px 14px; border-bottom:1px solid var(--border); flex-shrink:0; }
        .panel-label { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:1.5px; }
        .panel-low  .panel-label { color: var(--red); }
        .panel-book .panel-label { color: var(--blue); }
        .badge { font-family:'DM Mono'; font-size:10px; padding:2px 8px; border-radius:20px;
            background:var(--blue-light); border:1px solid var(--border); color:var(--blue); font-weight:600; }
        .badge-alert { background:var(--red-light); border-color:#fca5a5; color:var(--red); }
        .panel-body { flex:1; overflow:hidden; display:flex; flex-direction:column; }

        /* SEARCH */
        .search-bar { padding:8px 12px; border-bottom:1px solid var(--border); flex-shrink:0; }
        .search-input { width:100%; padding:6px 10px; border:1px solid var(--border);
            border-radius:var(--radius); font-family:'DM Sans'; font-size:12px;
            background:var(--bg); color:var(--text); transition:border-color .2s; }
        .search-input:focus { outline:none; border-color:var(--blue); }

        /* TABLE */
        .tbl-wrap { flex:1; overflow-y:auto; }
        .tbl-wrap::-webkit-scrollbar { width:4px; }
        .tbl-wrap::-webkit-scrollbar-thumb { background:var(--border); border-radius:4px; }
        table { width:100%; border-collapse:collapse; }
        thead th { position:sticky; top:0; padding:8px 12px; font-size:10px; font-weight:700;
            text-transform:uppercase; letter-spacing:1px; text-align:left;
            border-bottom:1px solid var(--border); }
        .panel-low  thead th { background:var(--red-light);  color:var(--red); }
        .panel-book thead th { background:var(--blue-light); color:var(--blue); }
        tbody tr { border-bottom:1px solid var(--border); transition:background .15s; }
        .panel-low  tbody tr:hover { background:#fff5f5; }
        .panel-book tbody tr:hover { background:var(--blue-light); }
        tbody td { padding:8px 12px; font-size:12px; color:var(--text); }
        .td-mono  { font-family:'DM Mono'; font-size:11px; }
        .td-muted { color:var(--muted); font-size:11px; }
        tr.hidden-row { display:none; }

        /* QTY BADGES */
        .qty-badge { display:inline-block; padding:2px 8px; border-radius:20px;
            font-weight:700; font-size:11px; }
        .qty-out { background:var(--red-light); color:var(--red); }
        .qty-low { background:#fff7ed; color:#c2410c; }

        /* EMPTY STATE */
        .empty-state td { text-align:center; padding:32px; color:var(--muted);
            font-size:12px; font-style:italic; }

        /* ── MOBILE OVERRIDES ── */
        @media (max-width: 767px) {
            html, body      { overflow-x: hidden; }
            .shell, .shell-switcher { overflow-x: hidden; width: 100%; }

            /* Topbar */
            .topbar         { height: 80px; padding: 0 14px; }
            .page-title     { font-size: 40px !important; }
            .btn-refresh,
            .btn-logout     { font-size: 30px !important; padding: 10px 16px; }

            /* Switcher */
            .switcher       { overflow-x: auto; scrollbar-width: none; top: 80px; }
            .switcher::-webkit-scrollbar { display: none; }
            .switcher-btn   { font-size: 28px !important; padding: 0 18px; height: 56px; flex-shrink: 0; white-space: nowrap; min-width: max-content; }
            .sw-count       { font-size: 22px !important; height: 28px; min-width: 28px; }

            /* Dev tab bar */
            .tab-bar        { overflow-x: auto; scrollbar-width: none; }
            .tab-bar::-webkit-scrollbar { display: none; }
            .tab-btn        { font-size: 28px !important; padding: 0 18px; height: 56px; flex-shrink: 0; white-space: nowrap; }
            .tab-count      { font-size: 20px !important; }

            /* Stat tiles */
            .stat-strip     { grid-template-columns: repeat(2, 1fr) !important; gap: 10px; }
            .stat-tile      { padding: 16px; gap: 16px; }
            .stat-icon      { width: 50px; height: 50px; }
            .stat-icon svg  { width: 26px; height: 26px; }
            .stat-num       { font-size: 70px; }
            .stat-lbl       { font-size: 28px !important; }

            /* Panels */
            .panel          { min-height: 280px; }
            .panel-head     { padding: 16px 14px; }
            .panel-body     { padding: 16px; }
            .panel-label    { font-size: 40px !important; }
            .badge          { font-size: 28px !important; padding: 5px 12px; }

            /* Stat cards */
            .stat-card      { padding: 16px; min-height: 80px; }
            .stat-card-label { font-size: 28px !important; }
            .stat-card-sub  { font-size: 24px !important; }
            .stat-card-value { font-size: 56px !important; }

            /* Big stat */
            .big-stat-num   { font-size: 100px !important; }
            .big-stat-sub   { font-size: 28px !important; }

            /* KPI cards */
            .kpi-val        { font-size: 56px !important; }
            .kpi-lbl        { font-size: 26px !important; }
            .kpi-sub        { font-size: 24px !important; }

            /* Search / toolbar */
            .toolbar        { padding: 12px; gap: 10px; }
            .search-bar     { padding: 12px; }
            .search-input   { font-size: 35px !important; padding: 12px; }
            .filter-select  { font-size: 35px !important; padding: 10px 12px; }

            /* Tables */
            table           { min-width: 700px; }
            .tbl-wrap       { max-height: 500px; }
            thead th        { font-size: 30px !important; padding: 12px 10px; }
            tbody td        { font-size: 30px !important; padding: 12px 10px; }
            .td-mono        { font-size: 30px !important; }
            .td-muted       { font-size: 28px !important; }

            /* Qty badge & action buttons */
            .qty            { font-size: 28px !important; height: 48px; min-width: 48px; }
            .btn-in,
            .btn-out        { font-size: 28px !important; padding: 10px 16px; }
            .days-badge     { font-size: 28px !important; padding: 6px 12px; }
            .type-pill      { font-size: 26px !important; padding: 5px 12px; }
            .pill-repair    { font-size: 26px !important; padding: 5px 12px; }

            /* Team sections */
            .team-section   { padding: 14px 16px; }
            .team-section-name { font-size: 32px !important; }
            .team-open-count { font-size: 56px !important; }
            .bar-label      { font-size: 26px !important; width: 70px; }
            .bar-track      { height: 10px; }
            .bar-count      { font-size: 26px !important; width: 32px; }
            .team-done-note { font-size: 24px !important; }
            .team-scroll    { max-height: 500px; }

            /* Members */
            .member-row     { padding: 14px; gap: 14px; }
            .member-avatar  { width: 50px; height: 50px; font-size: 20px; }
            .member-name    { font-size: 32px !important; }

            /* Time cards */
            .time-cards     { gap: 10px; }
            .time-card      { padding: 14px 16px; }
            .time-card-name  { font-size: 28px !important; }
            .time-card-value { font-size: 48px !important; }
            .time-dot       { width: 14px; height: 14px; }
            .time-bar-track { height: 8px; }

            /* Transactions */
            .trans-list     { max-height: 500px; }
            .trans-item     { padding: 16px 14px; gap: 14px; }
            .trans-dot      { width: 14px; height: 14px; margin-top: 8px; }
            .trans-name     { font-size: 40px !important; white-space: normal; }
            .trans-meta     { font-size: 36px !important; }
            .trans-badge    { font-size: 36px !important; padding: 6px 14px; }

            /* Water cards */
            .water-card     { padding: 14px 16px; }
            .water-name     { font-size: 32px !important; }
            .water-addr     { font-size: 28px !important; }
            .water-badge    { font-size: 28px !important; padding: 5px 12px; }

            /* Dispatch panels */
            .panel-low, .panel-book { min-height: 360px; }

            /* Depth tag */
            .depth-tag      { font-size: 28px !important; }
        }
    </style>
    <link rel="stylesheet" href="/app/dashboard/dashboard_responsive.css">
</head>
<body>
<div class="shell">

    <header class="topbar">
        <div class="topbar-left">
            <div class="logo-mark"></div>
            <span class="page-title">DISPATCH <span>DASHBOARD</span></span>
            <div class="divider-v"></div>
            <span class="role-badge">Dispatch</span>
            <span class="user-name"><?= d_esc($username) ?></span>
        </div>
        <a class="btn-refresh" href="?">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/>
                <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/>
            </svg>
            Refresh
        </a>
    </header>

    <main class="main">

        <!-- LOW STOCK ──────────────────────────────── -->
        <div class="panel panel-low">
            <div class="panel-head">
                <span class="panel-label">⚠ Critical Stock (≤ 1)</span>
                <span class="badge badge-alert">
                    <?= count($low_stock) ?> item<?= count($low_stock) !== 1 ? 's' : '' ?>
                </span>
            </div>
            <div class="panel-body">
                <div class="search-bar">
                    <input type="text" class="search-input"
                           placeholder="Search stock no, item, type…"
                           oninput="filterTable(this,'low-tbody')">
                </div>
                <div class="tbl-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Stock No</th>
                                <th>Item</th>
                                <th>Type</th>
                                <th>Size</th>
                                <th>Qty</th>
                            </tr>
                        </thead>
                        <tbody id="low-tbody">
                        <?php if (empty($low_stock)): ?>
                            <tr class="empty-state"><td colspan="5">All stock levels are fine ✓</td></tr>
                        <?php else: ?>
                            <?php foreach ($low_stock as $item):
                                $qty = (int) $item['status'];
                                $qtyBadge = $qty <= 0
                                    ? '<span class="qty-badge qty-out">OUT</span>'
                                    : '<span class="qty-badge qty-low">1</span>';
                            ?>
                            <tr>
                                <td class="td-mono"><?= d_esc($item['stock_no']) ?></td>
                                <td><strong><?= d_esc($item['item_name']) ?></strong></td>
                                <td class="td-muted"><?= d_esc($item['type'] ?? '—') ?></td>
                                <td class="td-muted"><?= d_esc($item['size'] ?? '—') ?></td>
                                <td><?= $qtyBadge ?></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- BOOKED OUT ─────────────────────────────── -->
        <div class="panel panel-book">
            <div class="panel-head">
                <span class="panel-label">Booked Out Stock</span>
                <span class="badge">
                    <?= count($booked_stock) ?> item<?= count($booked_stock) !== 1 ? 's' : '' ?>
                </span>
            </div>
            <div class="panel-body">
                <div class="search-bar">
                    <input type="text" class="search-input"
                           placeholder="Search stock no, item, order no…"
                           oninput="filterTable(this,'booked-tbody')">
                </div>
                <div class="tbl-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Stock No</th>
                                <th>Item</th>
                                <th>Qty</th>
                                <th>Order No</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody id="booked-tbody">
                        <?php if (empty($booked_stock)): ?>
                            <tr class="empty-state"><td colspan="5">No items currently booked out</td></tr>
                        <?php else: ?>
                            <?php foreach ($booked_stock as $item): ?>
                            <tr>
                                <td class="td-mono"><?= d_esc($item['stock_no']) ?></td>
                                <td><strong><?= d_esc($item['item_name']) ?></strong></td>
                                <td><strong><?= d_esc($item['quantity']) ?></strong></td>
                                <td class="td-mono"><?= d_esc($item['order_no'] ?? '—') ?></td>
                                <td class="td-muted"><?= d_esc(substr($item['datetime_created'] ?? '', 0, 10)) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </main>
</div>

<script>
function filterTable(input, tbodyId) {
    const q    = input.value.toLowerCase();
    const rows = document.querySelectorAll('#' + tbodyId + ' tr:not(.empty-state)');
    rows.forEach(row => {
        row.classList.toggle('hidden-row', !row.textContent.toLowerCase().includes(q));
    });
}
</script>
</body>
</html>