<?php
include 'db.php';

header('Content-Type: application/json');

try {
    $result = $conn->query("
      SELECT ho.*, dt.table_name,
        CONCAT('HOLD-', LPAD(ho.id, 6, '0')) as reference
      FROM hold_orders ho
      LEFT JOIN dinein_tables dt ON ho.table_id = dt.id
      ORDER BY ho.created_at DESC
    ");

    if (!$result) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $orders = [];

    while ($row = $result->fetch_assoc()) {
        $orders[] = $row;
    }

    echo json_encode($orders);

} catch (Exception $e) {
    error_log("Error fetching held orders: " . $e->getMessage());
    echo json_encode([]);
}
