<?php

elgg_gatekeeper();
$identifier = elgg_extract('identifier', $vars, 'groups');
$segments = elgg_extract('segments', $vars);
$guid = elgg_extract('guid', $vars);
$group = get_entity($guid);
$vars['entity'] = $group;
if (!$group instanceof ElggGroup || !$group->canEdit()) {
    register_error(elgg_echo('groups:noaccess'));
    forward(REFERRER);
}
// pushing context to make it easier to user 'menu:filter' hook
elgg_push_context("{$identifier}/edit");
elgg_load_library('elgg:groups');
elgg_set_page_owner_guid($group->guid);
group_subtypes_configure_tools($group->getSubtype());
$tab = array_shift($segments);
if (!$tab || !elgg_view_exists("resources/groups/edit/{$tab}")) {
    $tab = 'index';
}
echo elgg_view_resource("groups/edit/{$tab}", $vars);
        register_error(elgg_echo("{$identifier}:no_allowed_subtypes"));
        forward(REFERRER);
    }
    if (count($allowed_subtypes) == 1) {
        $subtype = $allowed_subtypes[0];
    }
}
$vars['parent_guid'] = $parent->guid;
$vars['subtype'] = $subtype;
if ($subtype) {
    // can write to container ignores hierarchy logic
    $params = array('parent' => $parent, 'type' => 'group', 'subtype' => $subtype);
    $can_contain = elgg_trigger_plugin_hook('permissions_check:parent', 'group', $params, true);
    if (!$can_contain) {
        register_error(elgg_echo("{$identifier}:illegal_subtype", array(elgg_echo("item:group:{$subtype}"))));
        forward(REFERRER);
    }
    group_subtypes_configure_tools($subtype);
    $title = elgg_echo("{$identifier}:add:{$subtype}");
    $content = elgg_view('groups/edit/index', $vars);
} else {
    $title = elgg_echo("{$identifier}:add:select_subtype");
    $content = elgg_view_form('groups/add/select_subtype', array('action' => current_page_url(), 'method' => 'GET', 'disable_security' => true), $vars);
}
elgg_push_breadcrumb(elgg_echo($identifier), "{$identifier}/all");
if ($parent instanceof ElggGroup) {
    elgg_push_breadcrumb($parent->getDisplayName(), $parent->getURL());
}
elgg_push_breadcrumb($title);
$body = elgg_view_layout('content', $params = array('content' => $content, 'title' => $title, 'filter' => ''));
echo elgg_view_page($title, $body);