User Group Orders

I have user groups set up with customer administrators for each group. I am now trying to set it up so the administrator of a user group can see all the orders placed for that specific user group. I have gotten fairly close but instead of showing only the orders placed for that group it is showing all orders from every group.

This is from my controllers/customers/orders.php (around line 340)

if (!empty($auth['user_id'])) {
$params['user_id'] = $auth['user_id'];

$ugadid = $auth['user_id'];
$yes = "Y";

$cntsql = "SELECT COUNT(*) FROM cscart_usergroup_links WHERE user_id='$ugadid' AND group_administrator='$yes' AND status='A'";
$cntresult = db_query($cntsql) or trigger_error("SQL", E_USER_ERROR);
$cntr = mysqli_fetch_row($cntresult);
$numrows = $cntr[0];
if($numrows !== "0") {
$query = db_query("SELECT usergroup_id FROM cscart_usergroup_links WHERE user_id='$ugadid' AND group_administrator='$yes' AND status='A'"); //query the db
while($row = mysqli_fetch_assoc($query)) {
$grpid = $row['usergroup_id']; //add row to array
$customers = db_get_array("SELECT user_id FROM cscart_usergroup_links WHERE usergroup_id='$grpid' ORDER BY user_id");

$usr_ids = is_array($customers) ? $customers : explode(',', $customers['user_id']);
$params['user_id'] = array_intersect($usr_ids, $customers);

else { $params['user_id'] = $auth['user_id']; }

} elseif (!empty($auth['order_ids'])) {
if (empty($params['order_id'])) {
$params['order_id'] = $auth['order_ids'];
} else {
$ord_ids = is_array($params['order_id']) ? $params['order_id'] : explode(',', $params['order_id']);
$params['order_id'] = array_intersect($ord_ids, $auth['order_ids']);
} else {
return array(CONTROLLER_STATUS_REDIRECT, "auth.login_form?return_url=" . urlencode(Registry::get('config.current_url')));
list($orders, $search) = fn_get_orders($params, Registry::get('settings.Appearance.orders_per_page'));
$view->assign('orders', $orders);
$view->assign('search', $search);

Any help is greatly appreciated.

Your code is unreadable and has serious problems. You should use the internal database functions correctly and not try to mix them with PHP functions. I.e. db_query() returns only true or false. It does not return a resource. Additionally, if you want to read from the db into a foreach, you should uses something like:

foreach(db_get_array("SELECT x,y,z,a,b,c FROM ?:usergroup_links") as $ar) {
if( $ar['link_id'] == 'xy' )

I would strongly suggest NOT mixing PHP mysqli_functions with the internal db functions.

And you probably want to use a 'get_orders_pre' hook to constrain your selection.