I see in your query that you are selecting several columns named "id"
When you use fetch_assoc() the column names must be unique otherwise $row["id"] will be overwritten by the last one (seller id) therefore you cannot reference the user id or catgory id etc. Use column aliases to differentiate.
Now you can reference $row['pid'], $row['cid'] etc
When producing output with various levels of headings and subheadings and subtotals, store your data in an array that reflects the output structure. For example...
$data = [
2 => [
'seller_name' => 'Sasha',
'orders' => [
10002 => [
'lines' => [
0 => [
'purchase_price' => 200.00,
'uid' => 4,
'user_fullname' => 'yeewen'
. . .
],
1 -> [
'purchase_price' => 200.00,
'uid' => 4,
'user_fullname' => 'yeewen'
. . .
]
]
'order_total' => 400.00
]
],
'seller_total' = 400.00
];
Then the processing becomes a set of nested loops...
foreach ($data as $seller_id => $seller_data) {
output seller heading
foreach ($seller_data['orders'] as $order_no => $order_data) {
output order heading
foreach ($order_data['lines']) {
output line data
}
output order subtotal
}
output seller subtotal
accumulate grand total
}
output grand total