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 with is_loyalty $stmtItems = $pdo->prepare(" SELECT oi.*, p.name as product_name, p.price as base_price, p.is_loyalty, 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']), 'quantity' => intval($item['quantity']), 'variant_id' => $item['variant_id'], 'variant_name' => $item['variant_name'], 'hasVariants' => !empty($item['variant_id']), 'is_loyalty' => intval($item['is_loyalty']) === 1 ]; } // 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); if ($customer) { // Fetch Loyalty Threshold for consistent frontend logic $settingsStmt = $pdo->query("SELECT points_for_free_meal FROM loyalty_settings WHERE id = 1"); $loyaltySettings = $settingsStmt->fetch(PDO::FETCH_ASSOC); $threshold = $loyaltySettings ? intval($loyaltySettings['points_for_free_meal']) : 70; $customer['points'] = intval($customer['points']); $customer['eligible_for_free_meal'] = $customer['points'] >= $threshold; $customer['eligible_count'] = floor($customer['points'] / $threshold); $customer['points_needed'] = max(0, $threshold - ($customer['points'] % $threshold)); } } echo json_encode([ 'success' => true, 'order' => $order, 'items' => $cartItems, 'customer' => $customer ]); exit; } } catch (Exception $e) { echo json_encode(['success' => false, 'error' => $e->getMessage()]); }