<?php
$numSelectionItems = 0;
$totalCost = 0;

$defaultRooms      = $db->run("SELECT * FROM selection_tag WHERE type = 'room' ORDER BY title ASC");
$defaultCategories = $db->run("SELECT * FROM selection_tag WHERE type = 'category' ORDER BY title ASC");

if ( $groups = $db->run("SELECT * FROM selection_group WHERE projectId = ? ORDER BY sort ASC", $pid) ) {
    for ( $i = 0; $i < count($groups); $i++ ) {
        $groups[$i]['selections'] = $db->run("SELECT * FROM selection_item WHERE groupId = ? ORDER BY sort ASC", $groups[$i]['id']);
        $groups[$i]['cost'] = $db->cell("SELECT SUM(cost * quantity) FROM selection_item WHERE groupId = ?", $groups[$i]['id']);

        $numSelectionItems += count($groups[$i]['selections']);
        $totalCost += $groups[$i]['cost'];

        for ( $k = 0; $k < count($groups[$i]['selections']); $k++ ) {
            $groups[$i]['selections'][$k]['tags'] = $db->run("SELECT title FROM selection_item_tag, selection_tag WHERE selection_item_tag.selectionItemId = ? AND selection_item_tag.tagId = selection_tag.id", $groups[$i]['selections'][$k]['id']);
        }
    }
}