<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

class ShowAvailablePrivileges extends Content
{
  public function getContent()
  {
    $smarty = $this->getSmarty();

    $privilegesArray = $this->getPrivilegeTreetableArray();
    $sortedPrivileges = ShowPrivileges::sortPrivilegeTreetableArray($privilegesArray, true);
    $smarty->assign('template', GetOperations::getVarValue('template'));
    $smarty->assign('privileges', $sortedPrivileges);

    return $smarty->fetch('tools/rechte_hinzufuegen.html');
  }

  private function getWebPrivilegesTemplatesByPrivilegeId()
  {
    $dbwWpt = new DBWorkWebPrivilegesT(1, true);
    $templateId = GetOperations::getVarValue('template');
    $privilegesTemplates = $dbwWpt->getByTemplateId($templateId);

    return ArrayOperations::setAttributAsKey($privilegesTemplates, 'privileg_id');
  }

  private function getPrivilegeTreetableArray()
  {
    $dbwWebPriv = new DBWorkWebPrivileges(1, true);
    $dbwTools = new DBWorkTools(1, true);

    $tools = ArrayOperations::setAttributAsKey($dbwTools->getAllTools(), 'id');
    $privileges = ArrayOperations::setAttributAsKey($dbwWebPriv->getAll(), 'id');
    $privilegesTemplates = $this->getWebPrivilegesTemplatesByPrivilegeId();

    $resultArray = array();
    foreach ($privileges as $priv) {
      if (!isset($privilegesTemplates[$priv->id])) {
        $toolname = $tools[$priv->tool_id]->text;
        $obj = new stdClass();
        $obj->privilege_id = $priv->id;
        $obj->privilege_name = $priv->getName();
        $obj->privilege_group = $priv->getGroup();
        $obj->privilege_key = $priv->keynumber;
        $obj->privilege_tool_id = $priv->tool_id;
        $resultArray[$tools[$priv->tool_id]->marketingid . ' ' . $toolname][$priv->getGroup()][] = $obj;
      }
    }

    ksort($resultArray);

    return $resultArray;
  }
}