/**
 *	This function is the start point for configuration of permissions within SimpleDesk.
 *
 *	@since 2.0
*/
function shd_admin_permissions()
{
    global $context, $scripturl, $sourcedir, $settings, $txt, $modSettings;
    shd_load_all_permission_sets();
    loadTemplate('sd_template/SimpleDesk-AdminPermissions');
    shd_load_language('sd_language/SimpleDeskPermissions');
    $subactions = array('main' => 'shd_admin_role_list', 'createrole' => 'shd_admin_create_role', 'editrole' => 'shd_admin_edit_role', 'saverole' => 'shd_admin_save_role', 'copyrole' => 'shd_admin_copy_role');
    $_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subactions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'main';
    $subactions[$_REQUEST['sa']]();
}
function shd_profile_permissions($memID)
{
    global $context, $txt, $scripturl, $sourcedir, $user_info, $smcFunc, $user_profile, $settings;
    shd_load_language('sd_language/SimpleDeskPermissions');
    $context['page_title'] = $txt['shd_profile_area'] . ' - ' . $txt['shd_profile_permissions'];
    $context['sub_template'] = 'shd_profile_permissions';
    // OK, start by figuring out what permissions are out there.
    shd_load_all_permission_sets();
    // 1. What groups is this user in? And we need all their groups, which in 'profile' mode, SMF helpfully puts into $user_profile[$memID] for us.
    $groups = empty($user_profile[$memID]['additional_groups']) ? array() : explode(',', $user_profile[$memID]['additional_groups']);
    $groups[] = $user_profile[$memID]['id_group'];
    // Sanitise this little lot
    foreach ($groups as $key => $value) {
        $groups[$key] = (int) $value;
    }
    // 1b. Hang on, is this user special? Are they, dare I suggest it, a full blown forum admin?
    $context['member']['has_all_permissions'] = in_array(1, $groups);
    if ($context['member']['has_all_permissions']) {
        return;
    }
    // 2. Do we have a department?
    $_REQUEST['permdept'] = isset($_REQUEST['permdept']) ? (int) $_REQUEST['permdept'] : 0;
    $depts = shd_allowed_to('access_helpdesk', false);
    if (!in_array($_REQUEST['permdept'], $depts)) {
        $_REQUEST['permdept'] = 0;
    }
    // this way we know that 0 = show list only, non-0 means to show a listing.
    // 2b. We still need to get the list of departments.
    $context['depts_list'] = array();
    $query = $smcFunc['db_query']('', '
		SELECT id_dept, dept_name
		FROM {db_prefix}helpdesk_depts
		WHERE id_dept IN ({array_int:depts})
		ORDER BY dept_order', array('depts' => $depts));
    while ($row = $smcFunc['db_fetch_assoc']($query)) {
        $context['depts_list'][$row['id_dept']] = $row['dept_name'];
    }
    if (empty($_REQUEST['permdept'])) {
        return $context['dept_list_only'] = true;
    }
    // 2. Get group colours and names.
    $context['membergroups'][0] = array('group_name' => $txt['membergroups_members'], 'color' => '', 'link' => $txt['membergroups_members']);
    $query = $smcFunc['db_query']('', '
		SELECT mg.id_group, mg.group_name, mg.online_color
		FROM {db_prefix}membergroups AS mg
		WHERE mg.id_group IN ({array_int:groups})
		ORDER BY id_group', array('groups' => $groups));
    while ($row = $smcFunc['db_fetch_assoc']($query)) {
        $context['membergroups'][$row['id_group']] = array('name' => $row['group_name'], 'color' => $row['online_color'], 'link' => '<a href="' . $scripturl . '?action=groups;sa=members;group=' . $row['id_group'] . '"' . (empty($row['online_color']) ? '' : ' style="color: ' . $row['online_color'] . ';"') . '>' . $row['group_name'] . '</a>');
    }
    $smcFunc['db_free_result']($query);
    // 3. Get roles that apply to this user, and figure out their groups as we go.
    $query = $smcFunc['db_query']('', '
		SELECT hdrg.id_role, hdrg.id_group, hdr.template, hdr.role_name, hddr.id_dept
		FROM {db_prefix}helpdesk_role_groups AS hdrg
			INNER JOIN {db_prefix}helpdesk_roles AS hdr ON (hdrg.id_role = hdr.id_role)
			INNER JOIN {db_prefix}helpdesk_dept_roles AS hddr ON (hdr.id_role = hddr.id_role)
		WHERE hdrg.id_group IN ({array_int:groups})
			AND hddr.id_dept = {int:dept}
		ORDER BY hdrg.id_role, hdrg.id_group', array('groups' => $groups, 'dept' => $_REQUEST['permdept']));
    $role_permissions = array();
    $roles = array();
    while ($row = $smcFunc['db_fetch_assoc']($query)) {
        if (empty($role_permissions[$row['id_role']])) {
            $role_permissions[$row['id_role']] = $context['shd_permissions']['roles'][$row['template']]['permissions'];
        }
        if (!empty($roles[$row['id_role']])) {
            $roles[$row['id_role']]['groups'][] = $row['id_group'];
        } else {
            $roles[$row['id_role']] = array('name' => $row['role_name'], 'template' => $row['template'], 'groups' => array($row['id_group']));
        }
    }
    $smcFunc['db_free_result']($query);
    $context['member_roles'] = $roles;
    // 4. Now the hard bit. Figure out what permissions they have.
    $context['member_permissions'] = array('allowed' => array(), 'denied' => array());
    if (!empty($roles)) {
        $query = $smcFunc['db_query']('', '
			SELECT id_role, permission, add_type
			FROM {db_prefix}helpdesk_role_permissions
			WHERE id_role IN ({array_int:roles})', array('roles' => array_keys($roles)));
        while ($row = $smcFunc['db_fetch_assoc']($query)) {
            $role_permissions[$row['id_role']][$row['permission']] = $row['add_type'];
        }
        // if it's defined in the DB it's somehow different to what the template so replace the template
    }
    foreach ($role_permissions as $role_id => $permission_set) {
        foreach ($permission_set as $permission => $state) {
            if ($state == ROLEPERM_ALLOW) {
                $context['member_permissions']['allowed'][$permission][] = $role_id;
            } elseif ($state == ROLEPERM_DENY) {
                $context['member_permissions']['denied'][$permission][] = $role_id;
            }
        }
    }
}