38682-vm/api/recall_orders.php
2026-02-23 03:43:41 +00:00

97 lines
3.5 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';
$pdo = db();
$action = $_GET['action'] ?? 'list';
try {
if ($action === 'list') {
$outlet_id = $_GET['outlet_id'] ?? 1;
$stmt = $pdo->prepare("
SELECT o.id, o.customer_name, o.customer_phone, o.total_amount, o.created_at, o.table_number, o.order_type,
(SELECT COUNT(*) FROM order_items WHERE order_id = o.id) as item_count
FROM orders o
WHERE o.outlet_id = ?
AND o.status = 'pending'
AND (o.payment_type_id IS NULL OR o.payment_type_id = 0)
ORDER BY o.created_at DESC
");
$stmt->execute([$outlet_id]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Format date for JS
foreach ($orders as &$o) {
$o['time_formatted'] = date('H:i', strtotime($o['created_at']));
}
echo json_encode(['success' => true, 'orders' => $orders]);
exit;
}
if ($action === 'details') {
$order_id = $_GET['id'] ?? null;
if (!$order_id) {
echo json_encode(['success' => false, 'error' => 'Missing ID']);
exit;
}
// Fetch Order
$stmt = $pdo->prepare("SELECT * FROM orders WHERE id = ?");
$stmt->execute([$order_id]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$order) {
echo json_encode(['success' => false, 'error' => 'Order not found']);
exit;
}
// Fetch Items
$stmtItems = $pdo->prepare("
SELECT oi.*, p.name as product_name, p.price as base_price, v.name as variant_name, v.price_adjustment
FROM order_items oi
JOIN products p ON oi.product_id = p.id
LEFT JOIN product_variants v ON oi.variant_id = v.id
WHERE oi.order_id = ?
");
$stmtItems->execute([$order_id]);
$items = $stmtItems->fetchAll(PDO::FETCH_ASSOC);
// Format items for JS cart
$cartItems = [];
foreach ($items as $item) {
$cartItems[] = [
'id' => $item['product_id'],
'name' => $item['product_name'],
'price' => floatval($item['unit_price']),
'base_price' => floatval($item['base_price']), // Note: this might be different from current DB price if changed, but for recall we usually want the ORIGINAL price or CURRENT?
// Ideally, if we edit an order, we might want to keep original prices OR update to current.
// For simplicity, let's use the price stored in order_items (unit_price) as the effective price.
'quantity' => intval($item['quantity']),
'variant_id' => $item['variant_id'],
'variant_name' => $item['variant_name'],
'hasVariants' => !empty($item['variant_id'])
];
}
// Fetch Customer
$customer = null;
if ($order['customer_id']) {
$cStmt = $pdo->prepare("SELECT * FROM customers WHERE id = ?");
$cStmt->execute([$order['customer_id']]);
$customer = $cStmt->fetch(PDO::FETCH_ASSOC);
}
echo json_encode([
'success' => true,
'order' => $order,
'items' => $cartItems,
'customer' => $customer
]);
exit;
}
} catch (Exception $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}