<?php
require_once(__DIR__ . "/includes/auth.php");

// ---- Order actions (process before any output, then PRG redirect) ----
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $oid = (int)($_POST['order_id'] ?? 0);
    $act = $_POST['action'] ?? '';
    // ownership: order must belong to this staff member's restaurant
    $own = $conn->prepare("SELECT id, order_status FROM orders WHERE id=? AND restaurant_id=?");
    $own->bind_param("ii", $oid, $__rest_id); $own->execute();
    $ord = $own->get_result()->fetch_assoc();
    if ($ord) {
        if ($act === 'accept' && in_array($ord['order_status'], ['pending','confirmed'], true)) {
            $u = $conn->prepare("UPDATE orders SET order_status='preparing', updated_at=NOW() WHERE id=?");
            $u->bind_param("i", $oid); $u->execute();
        } elseif ($act === 'ready' && $ord['order_status'] === 'preparing') {
            $u = $conn->prepare("UPDATE orders SET order_status='ready', updated_at=NOW() WHERE id=?");
            $u->bind_param("i", $oid); $u->execute();
        } elseif ($act === 'rush') {
            $label = '#' . str_pad($oid, 4, '0', STR_PAD_LEFT);
            // Promote the order: persistent rush flag (defensive) so it
            // escalates on both the kitchen and the waiter screens.
            if ($rs = $conn->prepare("UPDATE orders SET is_rushed=1 WHERE id=? AND restaurant_id=?")) {
                $rs->bind_param("ii", $oid, $__rest_id); $rs->execute();
            }
            $msg = "Kitchen flagged order $label as RUSH — please prioritise.";
            if ($ins = $conn->prepare("INSERT INTO notifications (restaurant_id, type, title, message, related_id) VALUES (?, 'new_order', 'Order Rushed', ?, ?)")) {
                $ins->bind_param("isi", $__rest_id, $msg, $oid); $ins->execute();
            }
            $_SESSION['staff_flash'] = "Order $label rushed.";
        }
    }
    header("Location: kitchen.php"); exit;
}

$flash = $_SESSION['staff_flash'] ?? ''; unset($_SESSION['staff_flash']);

// ---- Data ----
$today0 = date('Y-m-d 00:00:00');
$eff = null; $eff_done = 0;
if ($e = $conn->prepare("SELECT SUM(order_status='completed') done, SUM(order_status='completed' AND TIMESTAMPDIFF(MINUTE,created_at,COALESCE(updated_at,NOW()))<=15) ontime FROM orders WHERE restaurant_id=? AND created_at>=?")) {
    $e->bind_param("is", $__rest_id, $today0); $e->execute();
    $r = $e->get_result()->fetch_assoc();
    $eff_done = (int)($r['done'] ?? 0);
    if ($eff_done > 0) $eff = (int)round(($r['ontime'] / $eff_done) * 100);
}

function fetch_orders($conn, $rid, $statuses) {
    $in = "'" . implode("','", $statuses) . "'";
    $st = $conn->prepare("SELECT o.*, u.name AS customer_name, rt.label AS loc_label,
                                 (SELECT COUNT(*) FROM order_items WHERE order_id=o.id) item_count
                          FROM orders o
                          LEFT JOIN users u ON u.id = o.user_id
                          LEFT JOIN restaurant_tables rt ON rt.restaurant_id = o.restaurant_id AND rt.table_number = o.table_number
                          WHERE o.restaurant_id=? AND o.order_status IN ($in) ORDER BY o.created_at ASC");
    $st->bind_param("i", $rid); $st->execute();
    return $st->get_result()->fetch_all(MYSQLI_ASSOC);
}
$new_orders  = fetch_orders($conn, $__rest_id, ['pending','confirmed']);
$preparing   = fetch_orders($conn, $__rest_id, ['preparing']);

// Rushed orders bubble to the top of the prep queue.
usort($preparing, function ($a, $b) {
    $r = ((int)($b['is_rushed'] ?? 0)) <=> ((int)($a['is_rushed'] ?? 0));
    return $r !== 0 ? $r : (strtotime($a['created_at']) <=> strtotime($b['created_at']));
});
$rush_count = 0; foreach ($preparing as $o) { if (!empty($o['is_rushed'])) $rush_count++; }

// items for preparing orders (grouped)
$prep_items = [];
$ids = array_column($preparing, 'id');
if ($ids) {
    $idlist = implode(',', array_map('intval', $ids));
    $res = $conn->query("SELECT order_id, item_name, quantity FROM order_items WHERE order_id IN ($idlist) ORDER BY id ASC");
    while ($row = $res->fetch_assoc()) { $prep_items[$row['order_id']][] = $row; }
}

function elapsed_parts($created) {
    $mins = max(0, (int)floor((time() - strtotime($created)) / 60));
    $cls  = $mins < 10 ? 'ok' : ($mins <= 15 ? 'warn' : 'late');
    $pct  = min(100, (int)round($mins / 20 * 100));
    return [$mins, $cls, $pct];
}

$page_title = 'Kitchen Portal';
$active_nav = 'orders';
include("includes/header.php");
?>

<style>
.kp-stat{background:linear-gradient(135deg,var(--primary) 0%,var(--primary-dark) 100%);border-radius:20px;padding:20px;color:#fff;box-shadow:0 10px 26px rgba(34,90,227,.28);margin-bottom:24px}
.kp-stat .s-top{display:flex;align-items:center;justify-content:space-between;font-size:.84rem;opacity:.9;margin-bottom:8px}
.kp-stat .s-val{font-size:2.4rem;font-weight:800;letter-spacing:-.03em;line-height:1}
.kp-stat .s-sub{font-size:.8rem;opacity:.85;margin-top:4px}
.sec-head{display:flex;align-items:center;justify-content:space-between;margin:8px 2px 12px}
.sec-head h2{font-size:1.15rem;font-weight:800;letter-spacing:-.02em}
.sec-head .pill{font-size:.7rem;font-weight:800;background:var(--primary-bg);color:var(--primary);padding:4px 10px;border-radius:20px}
.new-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:22px}
.new-card{background:#fff;border:1px solid var(--border);border-radius:16px;box-shadow:0 4px 18px rgba(15,23,42,.06);padding:14px}
.new-card .n-ref{font-size:.72rem;font-weight:800;color:var(--primary);margin-bottom:4px}
.new-card .n-title{font-weight:800;font-size:.95rem}
.new-card .n-meta{font-size:.74rem;color:var(--text-muted);margin:2px 0 10px;line-height:1.5}
.new-card .n-note{display:flex;gap:6px;align-items:flex-start;background:var(--warning-bg);color:#92400e;border-radius:9px;padding:7px 9px;font-size:.72rem;line-height:1.4;margin-bottom:10px}
.new-card .n-note svg{flex-shrink:0;margin-top:1px}
.prep-card .p-sub{font-size:.76rem;color:var(--text-muted);margin-top:3px}
.prep-card .p-from{font-size:1.1rem;font-weight:800;letter-spacing:-.02em;line-height:1.15}
.btn{width:100%;border:none;border-radius:12px;font-family:var(--font);font-weight:700;font-size:.9rem;cursor:pointer;padding:12px;display:flex;align-items:center;justify-content:center;gap:8px}
.btn-primary{background:var(--primary);color:#fff}
.btn-primary:active{background:var(--primary-dark)}
.btn-danger{background:var(--error);color:#fff}
.legend{background:#fff;border:1px solid var(--border);border-radius:14px;box-shadow:0 4px 18px rgba(15,23,42,.06);padding:14px;margin-bottom:24px}
.legend .l-top{display:flex;align-items:center;gap:8px;font-size:.82rem;font-weight:700;color:var(--text-muted);margin-bottom:12px}
.legend .l-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;text-align:center}
.legend .l-grid > div{font-size:.7rem;color:var(--text-muted)}
.legend .bar{height:4px;border-radius:3px;margin-bottom:6px}
.legend .b-ok{background:var(--success)}.legend .b-warn{background:var(--warning)}.legend .b-late{background:var(--error)}
.legend .l-name{font-weight:700;color:var(--text)}
.prep-card{background:#fff;border:1px solid var(--border);border-radius:18px;box-shadow:0 4px 18px rgba(15,23,42,.06);padding:18px;margin-bottom:16px}
.prep-card .p-top{display:flex;justify-content:space-between;gap:12px;margin-bottom:10px}
.prep-card .p-tag{font-size:.68rem;font-weight:800;letter-spacing:.04em;padding:3px 9px;border-radius:20px;display:inline-block;margin-bottom:6px}
.p-tag.crit{background:var(--error-bg);color:var(--error)}
.p-tag.prog{background:var(--primary-bg);color:var(--primary)}
.p-tag.fresh{background:var(--success-bg);color:var(--success)}
.prep-card .p-title{font-size:1.15rem;font-weight:800;letter-spacing:-.02em;line-height:1.2}
.prep-card .p-timer{text-align:right;flex-shrink:0}
.prep-card .p-timer .t-val{font-size:1.2rem;font-weight:800;display:flex;align-items:center;gap:4px;justify-content:flex-end}
.prep-card .p-timer .t-lbl{font-size:.66rem;color:var(--text-muted);font-weight:700}
.t-ok{color:var(--success)}.t-warn{color:var(--warning)}.t-late{color:var(--error)}
.prep-items{list-style:none;margin:8px 0 12px;padding:0}
.prep-items li{font-size:.84rem;color:var(--text);padding:3px 0;display:flex;align-items:center;gap:8px}
.prep-items li::before{content:'';width:6px;height:6px;border-radius:50%;background:var(--primary);flex-shrink:0}
.cust-note{background:var(--bg);border-radius:12px;padding:12px;margin-bottom:12px}
.cust-note .cn-l{font-size:.64rem;font-weight:800;letter-spacing:.08em;color:var(--text-light);margin-bottom:4px}
.cust-note .cn-t{font-size:.82rem;color:var(--text-muted);font-style:italic;line-height:1.4}
.track{height:6px;border-radius:4px;background:var(--border);overflow:hidden;margin-bottom:14px}
.track > span{display:block;height:100%;border-radius:4px}
.fill-ok{background:var(--success)}.fill-warn{background:var(--warning)}.fill-late{background:var(--error)}
.empty{text-align:center;color:var(--text-muted);font-size:.86rem;padding:24px;background:#fff;border:1px dashed var(--border);border-radius:14px;margin-bottom:20px}
.prep-card.rushed{border-color:var(--error);box-shadow:0 0 0 2px rgba(220,38,38,.16),0 6px 20px rgba(220,38,38,.12)}
.escalation{display:flex;align-items:center;gap:10px;background:var(--error);color:#fff;border-radius:14px;padding:13px 16px;margin-bottom:16px;font-weight:700;font-size:.86rem;box-shadow:0 8px 22px rgba(220,38,38,.3)}
.escalation svg{flex-shrink:0}
</style>

<div class="page-head">
  <h1>Kitchen Portal</h1>
  <p>Welcome back, <?php echo htmlspecialchars(explode(' ', $__name)[0]); ?></p>
</div>

<?php if ($flash): ?><div class="banner ok"><?php echo htmlspecialchars($flash); ?></div><?php endif; ?>
<?php if ($rush_count > 0): ?>
<div class="escalation">
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
  Kitchen Escalation — <?php echo $rush_count; ?> rushed order<?php echo $rush_count === 1 ? '' : 's'; ?> need priority.
</div>
<?php endif; ?>

<div style="font-size:1rem;font-weight:800;margin:0 2px 8px">Live Orders</div>
<p style="font-size:.82rem;color:var(--text-muted);margin:0 2px 14px">Real-time elapsed tracking for kitchen efficiency.</p>

<div class="kp-stat">
  <div class="s-top"><span>Shift Efficiency (on-time today)</span><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg></div>
  <div class="s-val"><?php echo $eff === null ? '—' : $eff . '%'; ?></div>
  <div class="s-sub"><?php echo $eff === null ? 'No completed orders yet today' : $eff_done . ' order' . ($eff_done === 1 ? '' : 's') . ' completed today'; ?></div>
</div>

<div class="sec-head">
  <h2>New Orders</h2>
  <?php if ($new_orders): ?><span class="pill"><?php echo count($new_orders); ?> NEW</span><?php endif; ?>
</div>
<?php if (!$new_orders): ?>
  <div class="empty">No new orders right now.</div>
<?php else: ?>
  <div class="new-grid">
    <?php foreach ($new_orders as $o):
      [$src, $sec] = order_source_label($o);
      $cust = trim((string)($o['customer_name'] ?? ''));
      $nnote = trim((string)$o['note']); if (strtoupper($nnote) === 'DEMO') $nnote = '';
    ?>
    <div class="new-card">
      <div class="n-ref">#<?php echo str_pad($o['id'],4,'0',STR_PAD_LEFT); ?></div>
      <div class="n-title"><?php echo htmlspecialchars($src); ?></div>
      <div class="n-meta">
        <?php if ($sec): ?><?php echo htmlspecialchars($sec); ?> · <?php endif; ?><?php echo (int)$o['item_count']; ?> item<?php echo $o['item_count']==1?'':'s'; ?>
        <?php if ($cust): ?><br><span style="color:var(--text)"><?php echo htmlspecialchars($cust); ?></span><?php endif; ?>
      </div>
      <?php if ($nnote): ?><div class="n-note"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg><?php echo htmlspecialchars($nnote); ?></div><?php endif; ?>
      <form method="POST"><input type="hidden" name="order_id" value="<?php echo $o['id']; ?>"><input type="hidden" name="action" value="accept"><button class="btn btn-primary" type="submit">Accept</button></form>
    </div>
    <?php endforeach; ?>
  </div>
<?php endif; ?>

<div class="legend">
  <div class="l-top"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg> Status Legend</div>
  <div class="l-grid">
    <div><div class="bar b-ok"></div><div class="l-name">Normal</div>0–10m</div>
    <div><div class="bar b-warn"></div><div class="l-name">Warning</div>10–15m</div>
    <div><div class="bar b-late"></div><div class="l-name">Late</div>15m+</div>
  </div>
</div>

<div class="sec-head">
  <h2>Preparing</h2>
  <span class="pill" style="background:var(--bg);color:var(--text-muted)"><?php echo count($preparing); ?> Active</span>
</div>
<?php if (!$preparing): ?>
  <div class="empty">Nothing in the kitchen queue.</div>
<?php else: foreach ($preparing as $o):
  [$mins, $cls, $pct] = elapsed_parts($o['created_at']);
  $rushed = !empty($o['is_rushed']);
  if ($rushed) { $cls = 'late'; $pct = 100; }
  $tag = $rushed ? ['crit','RUSH'] : ($cls === 'late' ? ['crit','CRITICAL'] : ($cls === 'warn' ? ['prog','In Progress'] : ['fresh','In Progress']));
  $note = trim((string)$o['note']);
  if (strtoupper($note) === 'DEMO') $note = '';
  $items = $prep_items[$o['id']] ?? [];
  [$src, $sec] = order_source_label($o);
  $cust = trim((string)($o['customer_name'] ?? ''));
  $sub  = '#' . str_pad($o['id'],4,'0',STR_PAD_LEFT) . ($sec ? ' · ' . $sec : '') . ($cust ? ' · ' . $cust : '');
?>
<div class="prep-card <?php echo $rushed ? 'rushed' : ''; ?>">
  <div class="p-top">
    <div>
      <span class="p-tag <?php echo $tag[0]; ?>"><?php echo $tag[1]; ?></span>
      <div class="p-from">From <?php echo htmlspecialchars($src); ?></div>
      <div class="p-sub"><?php echo htmlspecialchars($sub); ?></div>
    </div>
    <div class="p-timer">
      <div class="t-val t-<?php echo $cls; ?>"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="13" r="8"/><path d="M12 9v4l2 2M9 2h6"/></svg><?php echo $mins; ?>m</div>
      <div class="t-lbl">Elapsed Time</div>
    </div>
  </div>
  <?php if ($items): ?>
  <ul class="prep-items">
    <?php foreach ($items as $it): ?><li><?php echo (int)$it['quantity']; ?>x <?php echo htmlspecialchars($it['item_name']); ?></li><?php endforeach; ?>
  </ul>
  <?php endif; ?>
  <?php if ($note): ?>
  <div class="cust-note"><div class="cn-l">CUSTOMER NOTE</div><div class="cn-t">"<?php echo htmlspecialchars($note); ?>"</div></div>
  <?php endif; ?>
  <div class="track"><span class="fill-<?php echo $cls; ?>" style="width:<?php echo max(6,$pct); ?>%"></span></div>
  <?php if ($cls === 'late' && !$rushed): ?>
    <div style="display:flex;gap:10px">
      <form method="POST" style="flex:1"><input type="hidden" name="order_id" value="<?php echo $o['id']; ?>"><input type="hidden" name="action" value="rush"><button class="btn btn-danger" type="submit"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>Rush</button></form>
      <form method="POST" style="flex:1.4"><input type="hidden" name="order_id" value="<?php echo $o['id']; ?>"><input type="hidden" name="action" value="ready"><button class="btn btn-primary" type="submit">Mark as Ready</button></form>
    </div>
  <?php else: ?>
    <form method="POST"><input type="hidden" name="order_id" value="<?php echo $o['id']; ?>"><input type="hidden" name="action" value="ready"><button class="btn btn-primary" type="submit">Mark as Ready</button></form>
  <?php endif; ?>
</div>
<?php endforeach; endif; ?>

<script>setTimeout(function(){location.reload();}, 25000);</script>

<?php include("includes/footer.php"); ?>
