<?php
include 'db.php';

$hold_id = intval($_GET['id'] ?? 0);

// Optional: Only print newly added items if passed
$new_item_ids = [];
if (!empty($_GET['items'])) {
    $raw = explode(',', $_GET['items']);
    $new_item_ids = array_map('intval', $raw);
}

$order = $conn->query("SELECT * FROM hold_orders WHERE id = $hold_id")->fetch_assoc();

// 🟡 Item filtering
$items_query = "SELECT * FROM hold_items WHERE hold_id = $hold_id";
if (!empty($new_item_ids)) {
    $ids_list = implode(',', $new_item_ids);
    $items_query .= " AND item_id IN ($ids_list)";
}
$items = $conn->query($items_query);
?>

<!DOCTYPE html>
<html>
<head>
  <title>KOT</title>
  <style>
    body {
      font-family: monospace;
      font-size: 15px;
      margin: 0;
      padding: 10px;
      width: 80mm;
    }
    h2 {
      font-size: 18px;
      text-align: center;
      margin-bottom: 10px;
    }
    p {
      margin: 0 0 6px;
    }
    table {
      width: 100%;
      border-collapse: collapse;
    }
    td {
      padding: 4px 0;
    }
    .text-right {
      text-align: right;
    }
    .line {
      border-top: 1px dashed #000;
      margin: 10px 0;
    }
  </style>
</head>
<body>

  <h2>KITCHEN ORDER TICKET</h2>
  <p><strong>Customer:</strong> <?= htmlspecialchars($order['customer_name']) ?></p>
  <?php if (!empty($order['order_mode'])): ?>
    <p><strong>Mode:</strong> <?= strtoupper($order['order_mode']) ?></p>
  <?php endif; ?>

  <?php if (!empty($order['table_id'])):
    $table = $conn->query("SELECT table_name FROM dinein_tables WHERE id = " . intval($order['table_id']))->fetch_assoc();
    if ($table):
  ?>
    <p><strong>Table:</strong> <?= htmlspecialchars($table['table_name']) ?></p>
  <?php endif; endif; ?>

  <div class="line"></div>

  <table>
    <?php if ($items->num_rows > 0): ?>
      <?php while($row = $items->fetch_assoc()): ?>
        <tr>
          <td><?= htmlspecialchars($row['item_name']) ?></td>
          <td class="text-right">x <?= intval($row['quantity']) ?></td>
        </tr>
      <?php endwhile; ?>
    <?php else: ?>
      <tr><td colspan="2">No items found.</td></tr>
    <?php endif; ?>
  </table>

  <div class="line"></div>
  <p style="text-align:center;">--- END OF KOT ---</p>

  <script>
    window.onload = function () {
      window.print();
      setTimeout(() => window.close(), 500);
    };
  </script>

</body>
</html>
