0) { $result = $order->getOrderById($id); if (!$result) { http_response_code(404); $answer['message'] = 'Order not found.'; exit(json_encode($answer)); } $answer['output'] = $result; // Check if an active invoice already exists for this order $sth = $pdo2->prepare( "SELECT COUNT(*) FROM td_invoice WHERE company_id = :company_id AND order_id = :order_id AND doc_type = 'invoice' AND status != 4" ); $sth->execute([':company_id' => $company_id, ':order_id' => $id]); $answer['has_active_invoice'] = (int)$sth->fetchColumn() > 0; // Calculate returnable items — order items minus already confirmed returns $order_items = $result['items'] ?? '[]'; // Aggregate returned qty per item_id from confirmed returns $sth = $pdo2->prepare( "SELECT items FROM td_return WHERE company_id = :company_id AND order_id = :order_id AND status = 1" ); $sth->execute([':company_id' => $company_id, ':order_id' => $id]); $returned_qty = []; foreach ($sth->fetchAll(PDO::FETCH_COLUMN) as $items_json) { $items = json_decode($items_json, true) ?: []; foreach ($items as $item) { $item_id = (int)($item['item_id'] ?? -1); if ($item_id < 0) continue; $returned_qty[$item_id] = ($returned_qty[$item_id] ?? 0) + (float)$item['quantity']; } } $returnable = []; foreach ($order_items as $i => $item) { $already_returned = $returned_qty[$i] ?? 0; $remaining = (float)$item['quantity'] - $already_returned; if ($remaining > 0) { $returnable[] = array_merge($item, [ 'item_id' => $i, 'original_qty' => (float)$item['quantity'], 'returned_qty' => $already_returned, 'returnable_qty' => $remaining, ]); } } $answer['returnable_items'] = $returnable; } else { $answer['output'] = $order->getOrderList(); } $answer['success'] = 1; exit(json_encode($answer)); ?>