false, 'error' => 'No data provided']); exit; } try { $pdo = db(); $pdo->beginTransaction(); // Validate order_type against allowed ENUM values $allowed_types = ['dine-in', 'takeaway', 'delivery', 'drive-thru']; $order_type = isset($data['order_type']) && in_array($data['order_type'], $allowed_types) ? $data['order_type'] : 'dine-in'; $table_id = null; $table_number = null; if ($order_type === 'dine-in') { $tid = $data['table_number'] ?? null; // Front-end sends ID as table_number if ($tid) { $stmt = $pdo->prepare("SELECT id, name FROM tables WHERE id = ?"); $stmt->execute([$tid]); $table = $stmt->fetch(PDO::FETCH_ASSOC); if ($table) { $table_id = $table['id']; $table_number = $table['name']; } } // If not found or not provided, leave null (Walk-in/Counter) or default to 1 if it exists if (!$table_id) { // Optional: try to find table 1 $stmt = $pdo->query("SELECT id, name FROM tables LIMIT 1"); $table = $stmt->fetch(PDO::FETCH_ASSOC); if ($table) { $table_id = $table['id']; $table_number = $table['name']; } } } // Customer Handling $customer_id = $data['customer_id'] ?? null; $customer_name = $data['customer_name'] ?? null; // Fallback or manual entry $customer_phone = $data['customer_phone'] ?? null; if ($customer_id) { $stmt = $pdo->prepare("SELECT name, phone FROM customers WHERE id = ?"); $stmt->execute([$customer_id]); $cust = $stmt->fetch(PDO::FETCH_ASSOC); if ($cust) { $customer_name = $cust['name']; $customer_phone = $cust['phone']; } else { // Invalid customer ID, clear it but keep manual name if any (though unlikely combo) $customer_id = null; } } $stmt = $pdo->prepare("INSERT INTO orders (outlet_id, table_id, table_number, order_type, customer_id, customer_name, customer_phone, total_amount, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')"); $stmt->execute([1, $table_id, $table_number, $order_type, $customer_id, $customer_name, $customer_phone, $data['total_amount'] ?? 0]); $order_id = $pdo->lastInsertId(); $item_stmt = $pdo->prepare("INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, ?, ?)"); if (!empty($data['items']) && is_array($data['items'])) { foreach ($data['items'] as $item) { $pid = $item['product_id'] ?? ($item['id'] ?? null); $qty = $item['quantity'] ?? 1; $price = $item['unit_price'] ?? ($item['price'] ?? 0); if ($pid) { $item_stmt->execute([$order_id, $pid, $qty, $price]); } } } $pdo->commit(); echo json_encode(['success' => true, 'order_id' => $order_id]); } catch (Exception $e) { if ($pdo->inTransaction()) { $pdo->rollBack(); } error_log("Order Error: " . $e->getMessage()); echo json_encode(['success' => false, 'error' => $e->getMessage()]); }