38682-vm/api/kitchen.php
2026-02-23 07:27:10 +00:00

108 lines
3.7 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';
$pdo = db();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// Fetch active kitchen orders
try {
$outlet_id = isset($_GET['outlet_id']) ? intval($_GET['outlet_id']) : 1;
// We want orders that are NOT completed or cancelled
// Status flow: pending -> preparing -> ready -> completed
// Kitchen sees: pending, preparing, ready
$stmt = $pdo->prepare("
SELECT
o.id, o.table_number, o.order_type, o.status, o.created_at, o.customer_name,
oi.quantity, p.name as product_name, v.name as variant_name
FROM orders o
JOIN order_items oi ON o.id = oi.order_id
JOIN products p ON oi.product_id = p.id
LEFT JOIN product_variants v ON oi.variant_id = v.id
WHERE o.status IN ('pending', 'preparing', 'ready')
AND o.outlet_id = :outlet_id
ORDER BY o.created_at ASC
");
$stmt->execute(['outlet_id' => $outlet_id]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$orders = [];
foreach ($rows as $row) {
$id = $row['id'];
if (!isset($orders[$id])) {
$orders[$id] = [
'id' => $row['id'],
'table_number' => $row['table_number'],
'order_type' => $row['order_type'],
'status' => $row['status'],
'created_at' => $row['created_at'],
'customer_name' => $row['customer_name'],
'items' => []
];
}
$orders[$id]['items'][] = [
'quantity' => $row['quantity'],
'product_name' => $row['product_name'],
'variant_name' => $row['variant_name']
];
}
echo json_encode(array_values($orders));
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Update order status or bulk action
$data = json_decode(file_get_contents('php://input'), true);
$action = $data['action'] ?? null;
$outletId = $data['outlet_id'] ?? null;
if ($action === 'serve_all') {
if (!$outletId) {
http_response_code(400);
echo json_encode(['error' => 'Missing outlet_id for serve_all']);
exit;
}
try {
$stmt = $pdo->prepare("UPDATE orders SET status = 'completed' WHERE outlet_id = ? AND status IN ('pending', 'preparing', 'ready')");
$stmt->execute([$outletId]);
echo json_encode(['success' => true]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
exit;
}
$orderId = $data['order_id'] ?? null;
$newStatus = $data['status'] ?? null;
if (!$orderId || !$newStatus) {
http_response_code(400);
echo json_encode(['error' => 'Missing order_id or status']);
exit;
}
$allowedStatuses = ['pending', 'preparing', 'ready', 'completed', 'cancelled'];
if (!in_array($newStatus, $allowedStatuses)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid status']);
exit;
}
try {
$stmt = $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?");
$stmt->execute([$newStatus, $orderId]);
echo json_encode(['success' => true]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
exit;
}