<?php
/**
 * The public-facing functionality of the plugin.
 *
 * @link       -
 * @since      1.0.0
 *
 * @package    Accordion_Md_Plugin
 * @subpackage Accordion_Md_Plugin/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Accordion_Md_Plugin
 * @subpackage Accordion_Md_Plugin/public
 * @author     Markus Domin <markus.domin@fh-luebeck.de>
 */
class Trainingssystem_Plugin_Module_Company
{

	private static $toolesswarning = "Der Fragebogen wurde insgesamt von zu wenigen Teilnehmenden ausgefüllt.";
	private static $toolesswarningshort = "Zu wenig Teilnehmende";
	const MINTEILNEHMER = '8';

    public function __construct()
    {

    }

    public function user_grouper($atts)
    {

        $heading = isset($atts['titel']) ? $atts['titel'] : 'Unternehmen'; 
        
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgr")) {
            ob_start();
            $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
            $current_user = wp_get_current_user();
            if (0 == $current_user->ID) {
			    return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
            } else {

                $bosses = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getBosses();

                $allusers = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getAllNutzer(false, false, false);

                if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrall")) {
                    $companies = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getAllCompanies(true, true, false, true);
                } elseif(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrown")) {
                    $companies = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getMyCompanies($current_user->ID, true, true, false, true);
                } else {
                    return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
                }
                
                $kAdmins = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getKAdmins();

                $company_detail_links = array();
                foreach($companies as $c) {
                    $company_detail_links[$c->getId()] = add_query_arg("cid", $c->getId(), get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["company_details"]));
                }
                echo $twig->render('company-mgr/company-mgr.html',
                    [
                        'companies' => $companies,
                        'bosses' => $bosses,
                        'users' => $allusers,
                        'kAdmins' => $kAdmins,
                        'kAdminEditor' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("kAdminEditor"),
                        'bossEditor' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("bossEditor"),
                        'canSeeDetails' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrdetails"),
                        'company_detail_links' => $company_detail_links,
                        'heading' => $heading,
                        "settings" => $settings,
                        "canSeeUsername" => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("seeusername"),
                    ]
                );
            }


            return ob_get_clean();
        } else {
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
    }

    public function company_mgr_get_companies(){
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgr")) {
            $current_user = wp_get_current_user();
            $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
            if ( 0 == $current_user->ID ) {
				echo $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
				//exit;
			}else{
                if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrall")) {
                    $companies = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getAllCompanies(true, true, false, true);
                } elseif(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrown")) {
                    $companies = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getMyCompanies($current_user->ID, true, true, false, true);
                } else {
                    return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
                }

                echo $twig->render('company-mgr/company-mgr-companylist.html',
                    [
                        'companies'=>$companies,
                        'canSeeDetails' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrdetails"),
                        'settings' => $settings,
                        'kAdminEditor' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("kAdminEditor"),
                        'bossEditor' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("bossEditor")
                    ]
                );
            }

            
        }
        else{
            echo $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
        wp_die();
    }

    public function company_mgr_add_company()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgr")) {
            $companies = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getAllCompanies(true, false, false, false);
            $duplicate = false;
            if(isset($_POST['bossid']) && trim($_POST['bossid']) != "") {
                foreach($companies as $company) {
                    if($company->getBoss() != null && $company->getBoss()->getId() == $_POST['bossid']) {
                        $duplicate = true;
                    }
                } 
            }
            
            $company_name = json_decode(stripslashes(sanitize_text_field($_POST['company_name'])), true);
            if($_POST['kadminid'] == "0") {
                $kAdminId = get_current_user_id();
            } else {
                $kAdminId = sanitize_text_field($_POST['kadminid']);
            }
            
            if(!$duplicate) {
                Trainingssystem_Plugin_Database::getInstance()->CompanyDao->insertCompany(
                    $company_name,
                    sanitize_text_field($_POST['bossid']),
                    $kAdminId
                );
            }
            else
            {
                echo "0";
            }
        }
        wp_die();
    }

    public function company_mgr_update_company()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgr")) {
            $company_name = json_decode(stripslashes(sanitize_text_field($_POST['company_name'])), true);

            $companies = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getAllCompanies(true, false, false, false);
            $found = false;
            foreach($companies as $company) {
                if($company->getBoss() != null && $company->getBoss()->getId() == $_POST['bossid'] && $company->getId() != $_POST['company_id']) {
                    $found = true;
                }
            }

            if(!$found) {
                $bossId = null;
                if(!Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("bossEditor")) {
                    $bossId = false;
                } else {
                    $bossId = empty(sanitize_text_field($_POST['bossid'])) ? null : sanitize_text_field($_POST['bossid']);
                }
                $kAdminId = null;
                if(!Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("kAdminEditor")) {
                    $kAdminId = false;
                } else {
                    $kAdminId = empty(sanitize_text_field($_POST['kadminid']))  ? null : sanitize_text_field($_POST['kadminid']);
                }
                Trainingssystem_Plugin_Database::getInstance()->CompanyDao->updateCompany(
                    sanitize_text_field($_POST['company_id']),
                    $company_name,
                    $bossId,
                    $kAdminId
                );
            }
            else
            {
                echo "0";
            }
        }
        wp_die();
    }

    public function company_mgr_getgroups_company()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgr")) {
            $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
            if (isset($_POST['companyid'])) {
                $company_id = intval(sanitize_text_field($_POST['companyid']));
                $allgroups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroups($company_id);
                $tmp = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTeamleader();
                $allteamleader = array();
                foreach($tmp as $t) {
                    $allteamleader[$t->ID] = $t;
                }

                // Teamleader
                $allgroupsIds = array();
                $teamleader = array();
                foreach($allgroups as $group){
                    $allgroupsIds[] = $group->getId();
                }

                foreach($allgroupsIds as $groupId){
                    $args = array(
                        'meta_key' => 'team_leader',
                        'meta_value' => $groupId
                    );
                    $user_query = new WP_User_Query( $args );
                    $user_results = $user_query->get_results();

                    $teamleader[$groupId] = array();
                    if(!empty($user_results)){
                        foreach($user_results as $user_entry){
                            $teamleader[$groupId]['userid'] = $user_entry->ID;
                            $teamleader[$groupId]['name'] = $user_entry->user_login;
                        }
                    }
                    else{
                        $teamleader[$groupId]['userid'] = "";
                        $teamleader[$groupId]['name'] = "";
                    }

                    
                }

                echo $twig->render('company-mgr/company-mgr-groups.html', [
                    "groups" => $allgroups,
                    "teamleader" => $teamleader,
                    "allteamleader" => $allteamleader,
                    "canSeeUsername" => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("seeusername"),
                    "teamLeaderEditor" => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("teamLeaderEditor"),
                ]);
            }
        }
        wp_die();
    }

    public function company_mgr_delete_company()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgr")) {
            $companyId = intval(sanitize_text_field($_POST['companyId']));
            $companyGroups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroups($companyId);
            $groupIds = array();
            foreach($companyGroups as $companyGroup){
                $groupIds[] = $companyGroup->getId();
            }

            foreach($groupIds as $gId){
                $args = array(
                    'meta_key' => 'team_leader',
                    'meta_value' => $gId
                );
    
                $user_query = new WP_User_Query( $args );
                $user_results = $user_query->get_results();

                if(!empty($user_results)){
                    foreach($user_results as $user_entry){
                        delete_user_meta($user_entry->ID, 'team_leader', $gId);
                    }
                }
            }

            Trainingssystem_Plugin_Database::getInstance()->CompanyDao->deleteCompany($companyId);
        }
        wp_die();
    }

    public function company_mgr_create_group()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgr")) {
            $companyId = intval(sanitize_text_field($_POST['companyId']));
            $groupName = json_decode(stripslashes(sanitize_text_field($_POST['groupName'])), true);
            $members = json_decode(stripslashes(sanitize_text_field($_POST['members'])), true);

            Trainingssystem_Plugin_Database::getInstance()->CompanygroupDao->insertCompanygroupWithMembers($groupName, $companyId, $members);
        }
        wp_die();
    }

    public function company_mgr_update_group()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgr")) {

            if(isset($_POST['group_id']) && trim($_POST['group_id']) != "" && is_numeric($_POST['group_id']) && isset($_POST['group_name']) && trim($_POST['group_name']) != ""){
                $groupId = intval(sanitize_text_field($_POST['group_id']));
                $groupName = json_decode(stripslashes(sanitize_text_field($_POST['group_name'])), true);
    
                Trainingssystem_Plugin_Database::getInstance()->CompanygroupDao->updateCompanygroup($groupId, $groupName);
                echo "1";
            }
            else{
                echo "0";
            }
            
        }
        wp_die();
    }

    public function company_mgr_delete_group()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgr")) {
            $groupId = intval(sanitize_text_field($_POST['groupId']));
            $teamleaderId = intval(sanitize_text_field($_POST['teamleaderId']));

            Trainingssystem_Plugin_Database::getInstance()->CompanygroupDao->deleteCompanygroup($groupId);

            if($teamleaderId != ""){
                delete_user_meta($teamleaderId, 'team_leader', $groupId);
            }
        }
        wp_die();
    }

    public function company_mgr_remove_groupmember()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgr")) {
            $groupId = intval(sanitize_text_field($_POST['groupId']));
            $userId = intval(sanitize_text_field($_POST['userId']));
            $teamleaderId = intval(sanitize_text_field($_POST['teamleaderId']));

            Trainingssystem_Plugin_Database::getInstance()->CompanygroupUserDao->deleteUserFromGroup($userId, $groupId);

            if($userId == $teamleaderId){
                delete_user_meta($userId, 'team_leader', $groupId);
            }
        }
        wp_die();
    }

    public function company_mgr_add_groupmember()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgr")) {
            $groupId = intval(sanitize_text_field($_POST['groupId']));
            // $userId = intval(sanitize_text_field($_POST['userId']));
            $members = json_decode(stripslashes(sanitize_text_field($_POST['members'])), true);
            $currentMembers = Trainingssystem_Plugin_Database::getInstance()->CompanygroupUserDao->getUserIdsByGroupId($groupId);
            foreach ($members as $userId) {
                if(!in_array($userId, $currentMembers)){
                    Trainingssystem_Plugin_Database::getInstance()->CompanygroupUserDao->addUserToGroup($userId, $groupId);
                }
            }
        }
        wp_die();
    }

    public function company_mgr_add_teamleader(){
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgr") && Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("kAdminEditor")) {

            $groupId = intval(sanitize_text_field($_POST['groupId']));
            $userId = intval(sanitize_text_field($_POST['userId']));

            if(is_numeric($_POST['groupId']) && $groupId !== 0) {

                $tmp = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTeamleader();
                $allteamleader = array();
                foreach($tmp as $t) {
                    $allteamleader[$t->ID] = $t;
                }
                
                $args = array(
                    'meta_key' => 'team_leader',
                    'meta_value' => $groupId
                );

                $user_query = new WP_User_Query( $args );
                $user_results = $user_query->get_results();

                if(empty($user_results)){
                    add_user_meta($userId, 'team_leader', $groupId);
                }
                else{
                    foreach($user_results as $user_entry){
                        delete_user_meta($user_entry->ID, 'team_leader', $groupId);
                    }
                    if($userId != "" && in_array($userId, array_keys($allteamleader))){
                        add_user_meta($userId, 'team_leader', $groupId);
                    }
                }
                echo "1";
            } else {
                echo "0";
            }
            wp_die();
        }
    }

    /****************************************************
        SHORTCODES
     ***************************************************/

    /**
     * Main GBU Shortcode - seperates functions by mode attribute in atts array
     * 
     * @param atts Array with mode and ID
     * @return HTML Code
     */
    public function output_gbu($atts) {

        if(0 !== get_current_user_id()) {
        
            if(isset($atts['mode']) && trim($atts['mode']) != "" && isset($atts['id']) && trim($atts['id']) != "" && is_numeric($atts['id'])) {

                $text = true;
                if(isset($atts['notext'])) {
                    $text = false;
                }

                $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

                switch($atts['mode']) {
                    case "einzel_pos_zu_neg":
                        if($this->isTsForm($atts['id'])) {
                            return $this->einzel($atts['id'], $text, true);
                        } else {
                            return $twig->render("forms/form-error-notsform.html");
                        }
                        break;
                    case "einzel_neg_zu_pos":
                        if($this->isTsForm($atts['id'])) {
                            return $this->einzel($atts['id'], $text, false);
                        } else {
                            return $twig->render("forms/form-error-notsform.html");
                        }
                        break;
                    case "ts1_ga_pos_zu_neg":
                        if($this->isTsForm($atts['id'])) {
                            return $this->ts1_ga($atts['id'], $text, true);
                        } else {
                            return $twig->render("forms/form-error-notsform.html");
                        }
                        break;
                    case "ts1_ga_neg_zu_pos":
                        if($this->isTsForm($atts['id'])) {
                            return $this->ts1_ga($atts['id'], $text, false);
                        } else {
                            return $twig->render("forms/form-error-notsform.html");
                        }
                        break;
                    case "ts2_gs_pos_zu_neg":
                        if($this->isTsForm($atts['id'])) {
                            return $this->ts2_gs($atts['id'], $text, true);
                        } else {
                            return $twig->render("forms/form-error-notsform.html");
                        }
                        break;
                    case "ts2_gs_neg_zu_pos":
                        if($this->isTsForm($atts['id'])) {
                            return $this->ts2_gs($atts['id'], $text, false);
                        } else {
                            return $twig->render("forms/form-error-notsform.html");
                        }
                        break;
                    case "ts3_gv_pos_zu_neg":
                        if($this->isTsForm($atts['id'])) {
                            return $this->ts3_gv($atts['id'], $text, true);
                        } else {
                            return $twig->render("forms/form-error-notsform.html");
                        }
                        break;
                    case "ts3_gv_neg_zu_pos":
                        if($this->isTsForm($atts['id'])) {
                            return $this->ts3_gv($atts['id'], $text, false);
                        } else {
                            return $twig->render("forms/form-error-notsform.html");
                        }
                        break;
                    case "text":
                        if($this->isTsForm($atts['id'])) {
                            return $this->ts_forms_output_text($atts['id']);
                        } else {
                            return $twig->render("forms/form-error-notsform.html");
                        }
                        break;
                }
            }
        } else {
            $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
    }

    public function output_gbu_mittelwerte($atts){

        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if(0 !== get_current_user_id()){
            if(isset($atts['ids']) && trim($atts['ids']) != "" && isset($atts['scales']) && trim($atts['scales']) != ""){

                $ids = explode(",", $atts['ids']);
                $formIds = array();
                foreach($ids as $id){
                    if($this->isTsForm(trim($id))){
                        $formIds[] = trim($id);
                    }
                }

                $gbuScales = explode("|", $atts['scales']);
                $scales = array();
                foreach($gbuScales as $gbuScale){
                    $scales[] = $gbuScale;
                }
                
                $showTables = array();
                if(isset($atts['show_tables'])){
                    $showTablesString = explode(",", $atts['show_tables']);
                    foreach($showTablesString as $showTable){
                        $showTables[] = trim($showTable);
                    }
                }
                else{
                    $showTables[] = "all";
                }

                $mode = array();
                if(isset($atts['mode'])){
                    if(trim($atts['mode'] != "")){
                        $modeString = trim($atts['mode']);
                        $modeArray = explode(",", $modeString);
                        foreach($formIds as $fIndex => $fId){
                            $mode[$fId] = trim($modeArray[$fIndex]);
                        }
                    }
                    else{
                        foreach($formIds as $fId){
                            $mode[$fId] = "";
                        }
                    }
                }
                else{
                    foreach($formIds as $fId){
                        $mode[$fId] = "";
                    }
                }

                $showPDFDownload = false;
                if(isset($atts['showpdfdownload'])){
                    if(trim($atts['showpdfdownload']) == "1"){
                        $showPDFDownload = true;
                    }
                }

                $pdfDownloadTitle = "Auswertung als PDF herunterladen";
                if(isset($atts['pdfdownloadtitle'])){
                    if(trim($atts['pdfdownloadtitle']) != ""){
                        $pdfDownloadTitle = trim($atts['pdfdownloadtitle']);
                    }
                }

                if(sizeof($formIds) > 0){
                    return $this->ts_forms_gbu_mittelwerte($formIds, $scales, $showTables, $mode, $showPDFDownload, $pdfDownloadTitle);
                }
                else{
                    return $twig->render("company/company-gbu-mittelwerte-error.html");
                }
            }
            else{
                return $twig->render("company/company-gbu-mittelwerte-error.html");
            }
        }
        else{
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
    }
    
    /**
     * Shortcode for the output of an average of a block
     * 
     * @param atts Array
     * @return HTML Code
     */
    public function output_mittelwert_gesamt($atts)
    {
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if(0 !== get_current_user_id()) {
            if(isset($atts['ids']) && trim($atts['ids']) != "") {

                $groupbygroups = false;
                if(isset($atts['groupbygroups']) && $atts['groupbygroups'] == "true") {
                    $groupbygroups = true;
                }

                $poszuneg = false;
                if(isset($atts['poszuneg']) && $atts['poszuneg'] == "true") {
                    $poszuneg = true;
                }
                $ids = explode(";", $atts['ids']);

                $ts = 0;
                $nf = 0;

                foreach($ids as $id) {
                    if($this->isTsForm($id)) {
                        $ts++;
                    } else {
                        $nf++;
                    }
                }

                if(sizeof($ids) == $ts) {
                    return $this->ts_forms_mittelwert_gesamt($ids, $groupbygroups, $poszuneg);
                } else if(sizeof($ids) == $nf) {
                    return $twig->render("forms/form-error-notsform.html");
                } else {
                    trigger_error("The shortcode [coach_output_mittelwert_gesamt ids='x'] cannot be used with NinjaForms and TS Forms mixed.", E_USER_ERROR);
                }
            } else {
                trigger_error("The shortcode [coach_output_mittelwert_gesamt] needs the attribute ids.", E_USER_ERROR);
            }
        } else {
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
    }

    /**
     * Shortcode to create a csv link to be displayed to the user
     * 
     * @param atts Array
     * @return HTML Code
     */
    public function csv_link($atts)
    {
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
        if(0 !== get_current_user_id()) {
        
            return $twig->render('company/csv-download-link.html', ["atts" => $atts]);

        } else {
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
    }

    /**
     * Shortcode - is being queried via an AJAX Request
     * Creates and echos the csv file to the browser
     * 
     * @param atts Array
     */
    public function download_csv($atts) 
    {
        if(0 !== get_current_user_id()) {
            if(isset($_POST['data']) && trim($_POST['data']) != "" && trim($_POST['data']) != "{}") 
            {
                    
                $data = json_decode(wp_unslash($_POST['data']));

                $singleuser = false;
                if(isset($_POST['singleuser']) && $_POST['singleuser'] == "true") {
                    $singleuser = true;
                }
        
                $groupbygroups = false;
                if(isset($_POST['groupbygroups']) && $_POST['groupbygroups'] == "true") {
                    $groupbygroups = true;
                }

                $ts = 0;
                $nf = 0;
                $total = 0;

                foreach($data as $topic => $subtopicarray) {
                    foreach($subtopicarray as $subtopic => $formid) {
                        $total++;
                        if($this->isTsForm($formid)) {
                            $ts++;
                        } else {
                            $nf++;
                        }
                    }
                }

                if($total == $ts) {
                    header("Content-type: text/csv, charset=utf-8");
                    header("Content-disposition: attachment; filename=Export-" . current_time("d-m-Y-H-i-s") . ".csv");
                    echo $this->ts_forms_csv_download($data, $singleuser, $groupbygroups);
                } else if($total == $nf) {
                    return $twig->render("forms/form-error-notsform.html");
                } else {
                    trigger_error("The function diwnload_csv cannot be used with NinjaForms and TS Forms mixed.", E_USER_ERROR);
                }
            } else {
                echo "0";
            }
        }
        wp_die();
    }

    /****************************************************
        DEPRECATED SHORTCODES
     ***************************************************/
    
    public function output_einzel_beurteilung1($atts)
    {
        if(!isset($atts['mode'])) {
            $atts['mode'] = "einzel_pos_zu_neg";
        }

        trigger_error("The shortcode [coach_output_einzel_beurteilung1 id='x'] should not be used any more. Use [coach_output_gbu mode='einzel_pos_zu_neg' id='x'] instead.", E_USER_DEPRECATED);

        return $this->output_gbu($atts);
    }

    public function output_einzel_beurteilung2($atts)
    {
        if(!isset($atts['mode'])) {
            $atts['mode'] = "einzel_neg_zu_pos";
        }

        trigger_error("The shortcode [coach_output_einzel_beurteilung2 id='x'] should not be used any more. Use [coach_output_gbu mode='einzel_neg_zu_pos' id='x'] instead.", E_USER_DEPRECATED);

        return $this->output_gbu($atts);
    }

    public function output_gesamt_haeufigkeit($atts)
    {
        if(!isset($atts['mode'])) {
            $atts['mode'] = "ts1_ga_pos_zu_neg";
        }

        trigger_error("The shortcode [coach_output_gesamt_haeufigkeit id='x'] should not be used any more. Use [coach_output_gbu mode='ts1_ga_pos_zu_neg' id='x'] instead.", E_USER_DEPRECATED);

        return $this->output_gbu($atts);
    }

    public function output_gesamt_haeufigkeit2($atts)
    {
        if(!isset($atts['mode'])) {
            $atts['mode'] = "ts1_ga_neg_zu_pos";
        }

        trigger_error("The shortcode [coach_output_gesamt_haeufigkeit2 id='x'] should not be used any more. Use [coach_output_gbu mode='ts1_ga_neg_zu_pos' id='x'] instead.", E_USER_DEPRECATED);

        return $this->output_gbu($atts);
    }

    public function output_gesamt_haeufigkeit_gruppen($atts)
    {
        if(!isset($atts['mode'])) {
            $atts['mode'] = "ts2_gs_pos_zu_neg";
        }

        trigger_error("The shortcode [coach_output_gesamt_haeufigkeit_gruppen id='x'] should not be used any more. Use [coach_output_gbu mode='ts2_gs_pos_zu_neg' id='x'] instead.", E_USER_DEPRECATED);

        return $this->output_gbu($atts);
    }

    public function output_gesamt_haeufigkeit_gruppen2($atts)
    {
        if(!isset($atts['mode'])) {
            $atts['mode'] = "ts2_gs_neg_zu_pos";
        }

        trigger_error("The shortcode [coach_output_gesamt_haeufigkeit_gruppen2 id='x'] should not be used any more. Use [coach_output_gbu mode='ts2_gs_neg_zu_pos' id='x'] instead.", E_USER_DEPRECATED);

        return $this->output_gbu($atts);
    }

    public function output_tabellenset3($atts)
    {
        if(!isset($atts['mode'])) {
            $atts['mode'] = "ts3_gv_pos_zu_neg";
        }

        trigger_error("The shortcode [coach_output_tabellenset3 id='x'] should not be used any more. Use [coach_output_gbu mode='ts3_gv_pos_zu_neg' id='x'] instead.", E_USER_DEPRECATED);

        return $this->output_gbu($atts);
    }

    public function output_tabellenset3b($atts)
    {
        if(!isset($atts['mode'])) {
            $atts['mode'] = "ts3_gv_neg_zu_pos";
        }

        trigger_error("The shortcode [coach_output_tabellenset3b id='x'] should not be used any more. Use [coach_output_gbu mode='ts3_gv_neg_zu_pos' id='x'] instead.", E_USER_DEPRECATED);

        return $this->output_gbu($atts);
    }

    public function output_gefaerdungsbeurteilung_text($atts)
    {
        if(!isset($atts['mode'])) {
            $atts['mode'] = "text";
        }

        trigger_error("The shortcode [coach_output_gefaerdungsbeurteilung_text id='x'] should not be used any more. Use [coach_output_gbu mode='text' id='x'] instead.", E_USER_DEPRECATED);

        return $this->output_gbu($atts);
	}

    /****************************************************
        TS FORMS FUNCTIONS
     ***************************************************/

    // ANFANG: Beschäftigte: Arbeitsumgebung, Arbeitszeit
    public function einzel($id, $text, $poszuneg) {
        $uid = $this::getUserId();

		$table = array();
		
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
        
		$fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getUserFormfieldsByForm($id, $uid);

        foreach ($fields as $formgroup) {

            foreach($formgroup as $field) {
                $field_id = $field->getFieldId();

                if($field->getType() == "matrix") { // Matrix
                    
                    foreach($field->getAttributesJsonDecoded()['questions'] as $q_key => $q) {
                        
                        $table['rows'][$field_id . $q_key]['label'] = $q['question'];

                        if($field->getFormdata() != null && $field->getFormdata()->dataIsArray()) {
                            $dataArray = $field->getFormdata()->getDataJsonDecoded();
                            
                            if(isset($dataArray[$q_key]) && is_numeric($dataArray[$q_key])) {

                                if($poszuneg) {
                                    if ($dataArray[$q_key] == 0) {
                                        $table['rows'][$field_id . $q_key]['bgcolor'] = "ffffff";
                                        $table['rows'][$field_id . $q_key]['value'] = $text ? "Keine Angabe" : '';
                                    } else if ($dataArray[$q_key] < 3) {
                                        $table['rows'][$field_id . $q_key]['bgcolor'] = "bfe2ca";
                                        $table['rows'][$field_id . $q_key]['value'] = $text ? "sehr gut bis gut" :  '';
                                    } else if ($dataArray[$q_key] > 3) {
                                        $table['rows'][$field_id . $q_key]['bgcolor'] = "f4858e";
                                        $table['rows'][$field_id . $q_key]['value'] = $text? "kritisch" : '';
                                    } else {
                                        $table['rows'][$field_id . $q_key]['bgcolor'] = "fed88f";
                                        $table['rows'][$field_id . $q_key]['value'] = $text ? "mittelmäßig" : '';
                                    }
                                } else {
                                    if ($dataArray[$q_key] == 0) {
                                        $table['rows'][$field_id . $q_key]['bgcolor'] = "ffffff";
                                        $table['rows'][$field_id . $q_key]['value'] = $text ? "Keine Angabe" : '';
                                    } else if ($dataArray[$q_key] > 3) {
                                        $table['rows'][$field_id . $q_key]['bgcolor'] = "bfe2ca";
                                        $table['rows'][$field_id . $q_key]['value'] = $text ? "sehr gut bis gut" :  '';
                                    } else if ($dataArray[$q_key] < 3) {
                                        $table['rows'][$field_id . $q_key]['bgcolor'] = "f4858e";
                                        $table['rows'][$field_id . $q_key]['value'] = $text? "kritisch" : '';
                                    } else {
                                        $table['rows'][$field_id . $q_key]['bgcolor'] = "fed88f";
                                        $table['rows'][$field_id . $q_key]['value'] = $text ? "mittelmäßig" : '';
                                    }
                                }

                            } else {
                                $table['rows'][$field_id . $q_key]['bgcolor'] = "FFFFFF";
                                $table['rows'][$field_id . $q_key]['value'] = $text ? "Keine Angabe" : '';
                            }

                        } else {
                            $table['rows'][$field_id . $q_key]['bgcolor'] = "FFFFFF";
                            $table['rows'][$field_id . $q_key]['value'] = $text ? "Keine Angabe" : '';
                        }
                    }

                } else { // Normal Input
                
                    // Bewertung erstellen
                    if(isset($field->getAttributesJsonDecoded()['title'])) {
                        $table['rows'][$field_id]['label'] = $field->getAttributesJsonDecoded()['title'];
                    } else {
                        $table['rows'][$field_id]['label'] = "";
                    }
                    if ($field->getFormdata() != null && is_numeric($field->getFormdata()->getData())) {
                        if($poszuneg) {
                            if ($field->getFormdata()->getData() == 0) {
                                $table['rows'][$field_id]['bgcolor'] = "ffffff";
                                $table['rows'][$field_id]['value'] = $text ? "Keine Angabe" : '';
                            } else if ($field->getFormdata()->getData() < 3) {
                                $table['rows'][$field_id]['bgcolor'] = "bfe2ca";
                                $table['rows'][$field_id]['value'] = $text ? "sehr gut bis gut" : '';
                            } else if ($field->getFormdata()->getData() > 3) {
                                $table['rows'][$field_id]['bgcolor'] = "f4858e";
                                $table['rows'][$field_id]['value'] = $text ? "kritisch" : '';
                            } else {
                                $table['rows'][$field_id]['bgcolor'] = "fed88f";
                                $table['rows'][$field_id]['value'] = $text ? "mittelmäßig" : '';
                            }
                        } else {
                            if ($field->getFormdata()->getData() == 0) {
                                $table['rows'][$field_id]['bgcolor'] = "ffffff";
                                $table['rows'][$field_id]['value'] = $text ? "Keine Angabe" : '';
                            } else if ($field->getFormdata()->getData() > 3) {
                                $table['rows'][$field_id]['bgcolor'] = "bfe2ca";
                                $table['rows'][$field_id]['value'] = $text ? "sehr gut bis gut" : '';
                            } else if ($field->getFormdata()->getData() < 3) {
                                $table['rows'][$field_id]['bgcolor'] = "f4858e";
                                $table['rows'][$field_id]['value'] = $text ? "kritisch" : '';
                            } else {
                                $table['rows'][$field_id]['bgcolor'] = "fed88f";
                                $table['rows'][$field_id]['value'] = $text ? "mittelmäßig" : '';
                            }
                        }
                        
                    } else {
                        $table['rows'][$field_id]['bgcolor'] = "FFFFFF";
                        $table['rows'][$field_id]['value'] = $text ? "Keine Angabe" : '';
                    }
                }
            }
        }
        return $twig->render("company/company-table-einzel.html", ["table" => $table, "id" => $id]);
    }
    // ENDE: Beschäftigte: Arbeitsumgebung, Arbeitszeit

    // ANFANG: Tabellenset 1A  Häufigkeiten und Mittelwerte (Gesamtauswertung)
    public function ts1_ga($id, $text, $poszuneg) {
        $uid = $this::getUserId();
        $users = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getUsersByBossId($uid);

        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if(sizeof($users) > 0) 
        {
            $table = array();

            $count_haeufigkeit1 = 0;
            $count_haeufigkeit2 = 0;
            $count_haeufigkeit3 = 0;
            $count_haeufigkeit4 = 0;
            $count_haeufigkeit5 = 0;
            $counter = 0;
            $fragebogen_fail = false;
            $haeufigkeiten_gesamt = 0;

            $fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($id);

            foreach ($fields as $field) {

                if($field->getType() == "matrix") { // Matrix

                    $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);

                    foreach($field->getAttributesJsonDecoded()['questions'] as $q_key => $q) {
                        $field_id = $field->getFieldId() . $q_key;

                        foreach ($data as $eingabe) {

                            if($eingabe != null && $eingabe->dataIsArray() && isset($eingabe->getDataJsonDecoded()[$q_key]) && is_numeric($eingabe->getDataJsonDecoded()[$q_key])) {
                        
                                if ($eingabe->getDataJsonDecoded()[$q_key] == 1) {
                                    $count_haeufigkeit1++;
                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 2) {
                                    $count_haeufigkeit2++;
                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 3) {
                                    $count_haeufigkeit3++;
                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 4) {
                                    $count_haeufigkeit4++;
                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 5) {
                                    $count_haeufigkeit5++;
                                }
                            }

                        }

                        // Ausgabe
                        $table['rows'][$field_id]['label'] = $q['question'];

                        $anzahl_zeile = $count_haeufigkeit1 + $count_haeufigkeit2 + $count_haeufigkeit3 + $count_haeufigkeit4 + $count_haeufigkeit5;
                        // Mindestanzahl erreicht
                        if ($anzahl_zeile >= self::MINTEILNEHMER) {
                            $table['rows'][$field_id]['tooless'] = false;
                            $table['rows'][$field_id]['a1'] = $count_haeufigkeit1;
                            $table['rows'][$field_id]['a2'] = $count_haeufigkeit2;
                            $table['rows'][$field_id]['a3'] = $count_haeufigkeit3;
                            $table['rows'][$field_id]['a4'] = $count_haeufigkeit4;
                            $table['rows'][$field_id]['a5'] = $count_haeufigkeit5;
                            $table['rows'][$field_id]['summe'] = $anzahl_zeile;

                            $counter++;
                            $häufigkeit_zeile = ($count_haeufigkeit1 * 1) + ($count_haeufigkeit2 * 2) + ($count_haeufigkeit3 * 3) + ($count_haeufigkeit4 * 4) + ($count_haeufigkeit5 * 5);
                            $haeufigkeiten_gesamt = $haeufigkeiten_gesamt + ($häufigkeit_zeile / $anzahl_zeile);
                        } else {
                            $table['rows'][$field_id]['tooless'] = true;
                            $table['rows'][$field_id]['value'] = $text ? $this::$toolesswarningshort . " (" . $anzahl_zeile . ")" : '';

                            $fragebogen_fail = true;
                        }

                        $count_haeufigkeit1 = 0;
                        $count_haeufigkeit2 = 0;
                        $count_haeufigkeit3 = 0;
                        $count_haeufigkeit4 = 0;
                        $count_haeufigkeit5 = 0;
                        $anzahl_zeile = 0;
                    
                    }

                } else {

                    $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);
                    $field_id = $field->getFieldId();
                    
                    foreach ($data as $eingabe) {
                        
                        if ($eingabe->getData() == 1) {
                            $count_haeufigkeit1++;
                        } else if ($eingabe->getData() == 2) {
                            $count_haeufigkeit2++;
                        } else if ($eingabe->getData() == 3) {
                            $count_haeufigkeit3++;
                        } else if ($eingabe->getData() == 4) {
                            $count_haeufigkeit4++;
                        } else if ($eingabe->getData() == 5) {
                            $count_haeufigkeit5++;
                        }
                    }

                    // Ausgabe
                    if(isset($field->getAttributesJsonDecoded()['title'])) {
                        $table['rows'][$field_id]['label'] = $field->getAttributesJsonDecoded()['title'];
                    } else {
                        $table['rows'][$field_id]['label'] = "";
                    }

                    $anzahl_zeile = $count_haeufigkeit1 + $count_haeufigkeit2 + $count_haeufigkeit3 + $count_haeufigkeit4 + $count_haeufigkeit5;
                    // Mindestanzahl erreicht
                    if ($anzahl_zeile >= self::MINTEILNEHMER) {
                        $table['rows'][$field_id]['tooless'] = false;
                        $table['rows'][$field_id]['a1'] = $count_haeufigkeit1;
                        $table['rows'][$field_id]['a2'] = $count_haeufigkeit2;
                        $table['rows'][$field_id]['a3'] = $count_haeufigkeit3;
                        $table['rows'][$field_id]['a4'] = $count_haeufigkeit4;
                        $table['rows'][$field_id]['a5'] = $count_haeufigkeit5;
                        $table['rows'][$field_id]['summe'] = $anzahl_zeile;

                        $counter++;
                        $häufigkeit_zeile = ($count_haeufigkeit1 * 1) + ($count_haeufigkeit2 * 2) + ($count_haeufigkeit3 * 3) + ($count_haeufigkeit4 * 4) + ($count_haeufigkeit5 * 5);
                        $haeufigkeiten_gesamt = $haeufigkeiten_gesamt + ($häufigkeit_zeile / $anzahl_zeile);
                    } else {
                        $table['rows'][$field_id]['tooless'] = true;
                        $table['rows'][$field_id]['value'] = $text ? $this::$toolesswarningshort . " (" . $anzahl_zeile . ")" : '';

                        $fragebogen_fail = true;
                    }
                    
                    $count_haeufigkeit1 = 0;
                    $count_haeufigkeit2 = 0;
                    $count_haeufigkeit3 = 0;
                    $count_haeufigkeit4 = 0;
                    $count_haeufigkeit5 = 0;
                    $anzahl_zeile = 0;
                }
            }

            // Mittelwert ausgeben
            if ($fragebogen_fail == true) {
                $table['bgcolor'] = "ffffff";
                $table['value'] = $text ? $this::$toolesswarning : '';
            } else {
                $mittelwert = ($counter != 0) ? round($haeufigkeiten_gesamt / $counter, 1) : 0;
                if($poszuneg) {
                    if ($mittelwert == 0) {
                        $table['bgcolor'] = "ffffff";
                        $table['value'] = $text ? $this::$toolesswarning : '';
                    } else if ($mittelwert <= 2.3) {
                        $table['bgcolor'] = "bfe2ca";
                        $table['value'] = $text ? number_format($mittelwert, 1, ',', '') : '';
                    } else if ($mittelwert >= 3.7) {
                        $table['bgcolor'] = "f4858e";
                        $table['value'] = $text ? number_format($mittelwert, 1, ',', '') : '';
                    } else {
                        $table['bgcolor'] = "fed88f";
                        $table['value'] = $text ? number_format($mittelwert, 1, ',', '') : '';
                    }
                } else {
                    if ($mittelwert == 0) {
                        $table['bgcolor'] = "ffffff";
                        $table['value'] = $text ? $this::$toolesswarning : '';
                    } else if ($mittelwert <= 2.3) {
                        $table['bgcolor'] = "f4858e";
                        $table['value'] = $text ? number_format($mittelwert, 1, ',', '') : '';
                    } else if ($mittelwert >= 3.7) {
                        $table['bgcolor'] = "bfe2ca";
                        $table['value'] = $text ? number_format($mittelwert, 1, ',', '') : '';
                    } else {
                        $table['bgcolor'] = "fed88f";
                        $table['value'] = $text ? number_format($mittelwert, 1, ',', '') : '';
                    }
                }
            }
            return $twig->render("company/company-table-gesamt-mittelwert.html", ["table" => $table, "id" => $id]);
        }
        else
        {
            return $twig->render("company/company-noboss.html", ["id" => $id]);
        }
    }
    // ENDE: Tabellenset 1A  Häufigkeiten und Mittelwerte (Gesamtauswertung)

    // ANFANG: Tabellenset 2A (pos. zu neg.)
    public function ts2_gs($id, $text, $poszuneg) {
        $uid = $this::getUserId();
        $groups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroupsByBossId($uid);

        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if(sizeof($groups) > 0)
        {
            $table = array();
            
            foreach ($groups as $groupid => $group) {

                $count_haeufigkeit1 = 0;
                $count_haeufigkeit2 = 0;
                $count_haeufigkeit3 = 0;
                $count_haeufigkeit4 = 0;
                $count_haeufigkeit5 = 0;
                $anzahl_zeile = 0;
                $counter = 0;
                $häufigkeit_zeile = 0;
                $haeufigkeiten_gesamt = 0;
                $fragebogen_fail = false;
                $mittelwert = 0;

                $table[$groupid]['groupname'] = $group['name'];
                $users = $group['users'];

                $fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($id);
                
                foreach ($fields as $field) {

                    if($field->getType() == "matrix") { // Matrix

                        $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);

                        foreach($field->getAttributesJsonDecoded()['questions'] as $q_key => $q) {
                            $field_id = $field->getFieldId() . $q_key;

                            foreach ($data as $eingabe) {

                                if($eingabe != null && $eingabe->dataIsArray() && isset($eingabe->getDataJsonDecoded()[$q_key]) && is_numeric($eingabe->getDataJsonDecoded()[$q_key])) {
                            
                                    if ($eingabe->getDataJsonDecoded()[$q_key] == 1) {
                                        $count_haeufigkeit1++;
                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 2) {
                                        $count_haeufigkeit2++;
                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 3) {
                                        $count_haeufigkeit3++;
                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 4) {
                                        $count_haeufigkeit4++;
                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 5) {
                                        $count_haeufigkeit5++;
                                    }
                                }

                            }

                            // Ausgabe
                            $table[$groupid]['row'][$field_id]['label'] = $q['question'];

                            $anzahl_zeile = $count_haeufigkeit1 + $count_haeufigkeit2 + $count_haeufigkeit3 + $count_haeufigkeit4 + $count_haeufigkeit5;
                            // Mindestanzahl erreicht
                            if ($anzahl_zeile >= self::MINTEILNEHMER) {
                                $table[$groupid]['row'][$field_id]['tooless'] = false;
                                $table[$groupid]['row'][$field_id]['h1'] = $count_haeufigkeit1;
                                $table[$groupid]['row'][$field_id]['h2'] = $count_haeufigkeit2;
                                $table[$groupid]['row'][$field_id]['h3'] = $count_haeufigkeit3;
                                $table[$groupid]['row'][$field_id]['h4'] = $count_haeufigkeit4;
                                $table[$groupid]['row'][$field_id]['h5'] = $count_haeufigkeit5;
                                $table[$groupid]['row'][$field_id]['summe'] = $anzahl_zeile;

                                $counter++;

                                $häufigkeit_zeile = ($count_haeufigkeit1 * 1) + ($count_haeufigkeit2 * 2) + ($count_haeufigkeit3 * 3) + ($count_haeufigkeit4 * 4) + ($count_haeufigkeit5 * 5);
                                $haeufigkeiten_gesamt = $haeufigkeiten_gesamt + ($häufigkeit_zeile / $anzahl_zeile);
                            } else {
                                $fragebogen_fail = true;
                                
                                $table[$groupid]['row'][$field_id]['tooless'] = true;
                                $table[$groupid]['row'][$field_id]['value'] = $this::$toolesswarningshort . " (" . $anzahl_zeile . ")";
                            }

                            $count_haeufigkeit1 = 0;
                            $count_haeufigkeit2 = 0;
                            $count_haeufigkeit3 = 0;
                            $count_haeufigkeit4 = 0;
                            $count_haeufigkeit5 = 0;
                            $anzahl_zeile = 0;
                        
                        }

                    } else {
                   
                        $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);
                        $field_id = $field->getFieldId();
                        
                        foreach ($data as $eingabe) {
                            
                            if ($eingabe->getData() == 1) {
                                $count_haeufigkeit1++;
                            } else if ($eingabe->getData() == 2) {
                                $count_haeufigkeit2++;
                            } else if ($eingabe->getData() == 3) {
                                $count_haeufigkeit3++;
                            } else if ($eingabe->getData() == 4) {
                                $count_haeufigkeit4++;
                            } else if ($eingabe->getData() == 5) {
                                $count_haeufigkeit5++;
                            }
                        }
        
                        // Ausgabe
                        if(isset($field->getAttributesJsonDecoded()['title'])) {
                            $table[$groupid]['row'][$field_id]['label'] = $field->getAttributesJsonDecoded()['title'];
                        } else {
                            $table[$groupid]['row'][$field_id]['label'] = "";
                        }
                        $anzahl_zeile = $count_haeufigkeit1 + $count_haeufigkeit2 + $count_haeufigkeit3 + $count_haeufigkeit4 + $count_haeufigkeit5;
                        // Mindestanzahl erreicht
                        if ($anzahl_zeile >= self::MINTEILNEHMER) {
                            $table[$groupid]['row'][$field_id]['tooless'] = false;
                            $table[$groupid]['row'][$field_id]['h1'] = $count_haeufigkeit1;
                            $table[$groupid]['row'][$field_id]['h2'] = $count_haeufigkeit2;
                            $table[$groupid]['row'][$field_id]['h3'] = $count_haeufigkeit3;
                            $table[$groupid]['row'][$field_id]['h4'] = $count_haeufigkeit4;
                            $table[$groupid]['row'][$field_id]['h5'] = $count_haeufigkeit5;
                            $table[$groupid]['row'][$field_id]['summe'] = $anzahl_zeile;

                            $counter++;

                            $häufigkeit_zeile = ($count_haeufigkeit1 * 1) + ($count_haeufigkeit2 * 2) + ($count_haeufigkeit3 * 3) + ($count_haeufigkeit4 * 4) + ($count_haeufigkeit5 * 5);
                            $haeufigkeiten_gesamt = $haeufigkeiten_gesamt + ($häufigkeit_zeile / $anzahl_zeile);
                        } else {
                            $fragebogen_fail = true;
                            
                            $table[$groupid]['row'][$field_id]['tooless'] = true;
                            $table[$groupid]['row'][$field_id]['value'] = $this::$toolesswarningshort . " (" . $anzahl_zeile . ")";
                        }
                        $count_haeufigkeit1 = 0;
                        $count_haeufigkeit2 = 0;
                        $count_haeufigkeit3 = 0;
                        $count_haeufigkeit4 = 0;
                        $count_haeufigkeit5 = 0;
                        $anzahl_zeile = 0;
                    }
                }

                // Mittelwert ausgeben
                if ($fragebogen_fail == true) {
                    $table[$groupid]['bgcolor'] = "ffffff";
                    $table[$groupid]['value'] = $this::$toolesswarning;
                } else {
                    $mittelwert = ($counter != 0) ? round($haeufigkeiten_gesamt / $counter, 1) : 0;
                    if($poszuneg) {
                        if ($mittelwert == 0) {
                            $table[$groupid]['bgcolor'] = "ffffff";
                            $table[$groupid]['value'] = $this::$toolesswarning;
                        } else if ($mittelwert <= 2.3) {
                            $table[$groupid]['bgcolor'] = "bfe2ca";
                            $table[$groupid]['value'] = number_format($mittelwert, 1, ',', '');
                        } else if ($mittelwert >= 3.7) {
                            $table[$groupid]['bgcolor'] = "f4858e";
                            $table[$groupid]['value'] = number_format($mittelwert, 1, ',', '');
                        } else {	
                            $table[$groupid]['bgcolor'] = "fed88f";
                            $table[$groupid]['value'] = number_format($mittelwert, 1, ',', '');
                        }
                    } else {
                        if ($mittelwert == 0) {
                            $table[$groupid]['bgcolor'] = "ffffff";
                            $table[$groupid]['value'] = $this::$toolesswarning;
                        } else if ($mittelwert <= 2.3) {
                            $table[$groupid]['bgcolor'] = "f4858e";
                            $table[$groupid]['value'] = number_format($mittelwert, 1, ',', '');
                        } else if ($mittelwert >= 3.7) {
                            $table[$groupid]['bgcolor'] = "bfe2ca";
                            $table[$groupid]['value'] = number_format($mittelwert, 1, ',', '');
                        } else {
                            $table[$groupid]['bgcolor'] = "fed88f";
                            $table[$groupid]['value'] = number_format($mittelwert, 1, ',', '');
                        }
                    }
                }
            }
            return $twig->render("company/company-table-gruppen-details.html", ["table" => $table, "id" => $id]);
        }
        else
        {
            return $twig->render("company/company-noboss.html", ["id" => $id]);
        }
    }
    // ENDE: Tabellenset 2A (pos. zu neg.)

    // ANFANG: Tabellenset 3A (pos. zu neg.)
    public function ts3_gv($id, $text, $poszuneg) {
        $uid = $this::getUserId();
		$groups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroupsByBossId($uid);
		
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if(sizeof($groups) > 0)
        {
            $table = array();
            
            foreach ($groups as $groupid => $group) {
                $count_haeufigkeit1 = 0;
                $count_haeufigkeit2 = 0;
                $count_haeufigkeit3 = 0;
                $count_haeufigkeit4 = 0;
                $count_haeufigkeit5 = 0;
                $anzahl_zeile = 0;
                $counter = 0;
                $häufigkeit_zeile = 0;
                $haeufigkeiten_gesamt = 0;
                $fragebogen_fail = false;
                $mittelwert = 0;

                $table[$groupid]['groupname'] = $group['name'];
                $users = $group['users'];

                $fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($id);

                foreach ($fields as $field) {

                    if($field->getType() == "matrix") { // Matrix
    
                        $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);
    
                        foreach($field->getAttributesJsonDecoded()['questions'] as $q_key => $q) {
                            $field_id = $field->getFieldId() . $q_key;
    
                            foreach ($data as $eingabe) {
    
                                if($eingabe != null && $eingabe->dataIsArray() && isset($eingabe->getDataJsonDecoded()[$q_key]) && is_numeric($eingabe->getDataJsonDecoded()[$q_key])) {
                            
                                    if ($eingabe->getDataJsonDecoded()[$q_key] == 1) {
                                        $count_haeufigkeit1++;
                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 2) {
                                        $count_haeufigkeit2++;
                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 3) {
                                        $count_haeufigkeit3++;
                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 4) {
                                        $count_haeufigkeit4++;
                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 5) {
                                        $count_haeufigkeit5++;
                                    }
                                }
    
                            }
    
                            // Ausgabe
                            $table[$groupid]['rows'][$field_id]['label'] = $q['question'];
    
                            // Ausgabe
                            $anzahl_zeile = $count_haeufigkeit1 + $count_haeufigkeit2 + $count_haeufigkeit3 + $count_haeufigkeit4 + $count_haeufigkeit5;
                            // Mindestanzahl erreicht
                            if ($anzahl_zeile >= self::MINTEILNEHMER) {
                                $counter++;
                                
                                $häufigkeit_zeile = ($count_haeufigkeit1 * 1) + ($count_haeufigkeit2 * 2) + ($count_haeufigkeit3 * 3) + ($count_haeufigkeit4 * 4) + ($count_haeufigkeit5 * 5);
                                $haeufigkeiten_gesamt = $haeufigkeiten_gesamt + ($häufigkeit_zeile / $anzahl_zeile);
                            } else {
                                $fragebogen_fail = true;
                                
                            }
                            $count_haeufigkeit1 = 0;
                            $count_haeufigkeit2 = 0;
                            $count_haeufigkeit3 = 0;
                            $count_haeufigkeit4 = 0;
                            $count_haeufigkeit5 = 0;
                            $anzahl_zeile = 0;
                        
                        }
    
                    } else {

                        $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);
                        $field_id = $field->getFieldId();
                        
                        foreach ($data as $eingabe) {
                            
                            if ($eingabe->getData() == 1) {
                                $count_haeufigkeit1++;
                            } else if ($eingabe->getData() == 2) {
                                $count_haeufigkeit2++;
                            } else if ($eingabe->getData() == 3) {
                                $count_haeufigkeit3++;
                            } else if ($eingabe->getData() == 4) {
                                $count_haeufigkeit4++;
                            } else if ($eingabe->getData() == 5) {
                                $count_haeufigkeit5++;
                            }
                        }
                        
                        // Ausgabe
                        if(isset($field->getAttributesJsonDecoded()['title'])) {
                            $table[$groupid]['rows'][$field_id]['label'] = $field->getAttributesJsonDecoded()['title'];
                        } else {
                            $table[$groupid]['rows'][$field_id]['label'] = "";
                        }
                        
                        // Ausgabe
                        $anzahl_zeile = $count_haeufigkeit1 + $count_haeufigkeit2 + $count_haeufigkeit3 + $count_haeufigkeit4 + $count_haeufigkeit5;
                        // Mindestanzahl erreicht
                        if ($anzahl_zeile >= self::MINTEILNEHMER) {
                            $counter++;
                            
                            $häufigkeit_zeile = ($count_haeufigkeit1 * 1) + ($count_haeufigkeit2 * 2) + ($count_haeufigkeit3 * 3) + ($count_haeufigkeit4 * 4) + ($count_haeufigkeit5 * 5);
                            $haeufigkeiten_gesamt = $haeufigkeiten_gesamt + ($häufigkeit_zeile / $anzahl_zeile);
                        } else {
                            $fragebogen_fail = true;
                            
                        }
                        $count_haeufigkeit1 = 0;
                        $count_haeufigkeit2 = 0;
                        $count_haeufigkeit3 = 0;
                        $count_haeufigkeit4 = 0;
                        $count_haeufigkeit5 = 0;
                        $anzahl_zeile = 0;
                    }
                }

                // Mittelwert ausgeben
                if ($fragebogen_fail == true) {
                    $table[$groupid]['bgcolor'] = "ffffff";
                    $table[$groupid]['value'] = $text ? $this::$toolesswarning : '';
                } else {
                    $mittelwert = round($haeufigkeiten_gesamt / $counter, 1);
                    if($poszuneg) {
                        if ($mittelwert == 0) {
                            $table[$groupid]['bgcolor'] = "ffffff";
                            $table[$groupid]['value'] = $text ? $this::$toolesswarning : '';
                        } else if ($mittelwert <= 2.3) {
                            $table[$groupid]['bgcolor'] = "bfe2ca";
                            $table[$groupid]['value'] = $text ? number_format($mittelwert, 1, ',', '') : '';
                        } else if ($mittelwert >= 3.7) {
                            $table[$groupid]['bgcolor'] = "f4858e";
                            $table[$groupid]['value'] = $text ? number_format($mittelwert, 1, ',', '') : '';
                        } else {
                            $table[$groupid]['bgcolor'] = "fed88f";
                            $table[$groupid]['value'] = $text ? number_format($mittelwert, 1, ',', '') : '';
                        }
                    } else {
                        if ($mittelwert == 0) {
                            $table[$groupid]['bgcolor'] = "ffffff";
                            $table[$groupid]['value'] = $text ? $this::$toolesswarning : '';
                        } else if ($mittelwert <= 2.3) {
                            $table[$groupid]['bgcolor'] = "f4858e";
                            $table[$groupid]['value'] = $text ? number_format($mittelwert, 1, ',', '') : '';
                        } else if ($mittelwert >= 3.7) {
                            $table[$groupid]['bgcolor'] = "bfe2ca";
                            $table[$groupid]['value'] = $text ? number_format($mittelwert, 1, ',', '') : '';
                        } else {
                            $table[$groupid]['bgcolor'] = "fed88f";
                            $table[$groupid]['value'] = $text ? number_format($mittelwert, 1, ',', '') : '';
                        }
                    }
                }
            }
            return $twig->render("company/company-table-gruppen-mittelwert.html", ["table" => $table, "id" => $id]);
        }
        else
        {
            return $twig->render("company/company-noboss.html", ["id" => $id]);
        }
    }
    // ENDE: Tabellenset 3A (pos. zu neg.)

    // ANFANG: Textausgabe
    public function ts_forms_output_text($id) {
        $uid = $this::getUserId();
        $users = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getUsersByBossId($uid);

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if(sizeof($users) > 0) 
        {
            $list = array();

            $fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($id);

            foreach ($fields as $field) {
                $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);
                foreach ($data as $thisData) {
                    $eingabe = $thisData->getData();
                    if(trim($eingabe) != "") {
                        $list[] = $eingabe;
                    }
                }
            }
            
            return $twig->render("company/json-to-list.html", ["list" => $list, "id" => $id]);
        }
        else
        {
            return $twig->render("company/company-noboss.html", ["id" => $id]);
        }
    }
    // ENDE: Textausgabe

    // ANFANG: Mittelwerte Skalen, Subskalen, Items
    public function ts_forms_gbu_mittelwerte($ids, $scales, $showTables, $mode, $showPDFDownload, $pdfDownloadTitle){
        $uid = $this::getUserId(); // User-ID
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
        if(is_array($ids) && is_array($scales)){
            if($ids != null && sizeof($ids) > 0 && $scales != null && sizeof($scales) > 0 && sizeof($ids) == sizeof($scales)) {
                
                $isKAdmin = false;
                $isBoss = false;
                $isTeamleader = false;
                $tableKAdmin = array();
                $tableBoss = array();
                $tableTeamleader = array();
                if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("gbumittelwertekadmin")){
                    $companiesThisKAdmin = $this::getCompaniesByKAdmin($uid);
                    if(sizeof($companiesThisKAdmin) > 0){
                        $isKAdmin = true;
                        
                        if(!isset($tableKAdmin['companies'])){
                            $tableKAdmin['companies'] = array();
                        }

                        foreach($companiesThisKAdmin as $company){

                            $companyInformation = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getCompanyById($company);
                            $companyname = $companyInformation->getName();
                            $companyGroups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroups($company);
                            $companymember = 0;
                            $groups = array();
                            foreach($companyGroups as $companyGroup){
        
                                if(!isset($groups[$companyGroup->getId()])){
                                    $groups[$companyGroup->getId()] = array();
                                }
                                $groups[$companyGroup->getId()]['name'] = $companyGroup->getName();
                                $groups[$companyGroup->getId()]['users'] = Trainingssystem_Plugin_Database::getInstance()->CompanygroupUserDao->getUserIdsByGroupId($companyGroup->getId());

                                $companymember += sizeof($groups[$companyGroup->getId()]['users']);
                            }

                            if(!isset($tableKAdmin['companies'][$company])){
                                $tableKAdmin['companies'][$company] = array();
                            }

                            $tableKAdmin['companies'][$company]['companyname'] = $companyname;

                            if(!isset($tableKAdmin['companies'][$company]['scale_table'])){
                                $tableKAdmin['companies'][$company]['scale_table'] = array();
                            }

                            if(!isset($tableKAdmin['companies'][$company]['scale_table']['scales'])){
                                $tableKAdmin['companies'][$company]['scale_table']['scales'] = array();
                            }

                            if(!isset($tableKAdmin['companies'][$company]['scale_table']['gesamt_information'])){
                                $tableKAdmin['companies'][$company]['scale_table']['gesamt_information'] = array();
                            }

                            if(!isset($tableKAdmin['companies'][$company]['subscale_table'])){
                                $tableKAdmin['companies'][$company]['subscale_table'] = array();
                            }

                            if(!isset($tableKAdmin['companies'][$company]['subscale_table']['scales'])){
                                $tableKAdmin['companies'][$company]['subscale_table']['scales'] = array();
                            }

                            if(!isset($tableKAdmin['companies'][$company]['subscale_table']['gesamt_information'])){
                                $tableKAdmin['companies'][$company]['subscale_table']['gesamt_information'] = array();
                            }

                            if(!isset($tableKAdmin['companies'][$company]['item_table'])){
                                $tableKAdmin['companies'][$company]['item_table'] = array();
                            }

                            if(!isset($tableKAdmin['companies'][$company]['item_table']['scales'])){
                                $tableKAdmin['companies'][$company]['item_table']['scales'] = array();
                            }

                            if(!isset($tableKAdmin['companies'][$company]['item_table']['gesamt_information'])){
                                $tableKAdmin['companies'][$company]['item_table']['gesamt_information'] = array();
                            }

                            $tableKAdmin['companies'][$company]['scale_table']['gesamt_information']['countPersons'] = $companymember;
                            $tableKAdmin['companies'][$company]['subscale_table']['gesamt_information']['countPersons'] = $companymember;
                            $tableKAdmin['companies'][$company]['item_table']['gesamt_information']['countPersons'] = $companymember;

                            if(!isset($tableKAdmin['companies'][$company]['scale_table']['group_information'])){
                                $tableKAdmin['companies'][$company]['scale_table']['group_information'] = array();
                            }

                            if(!isset($tableKAdmin['companies'][$company]['subscale_table']['group_information'])){
                                $tableKAdmin['companies'][$company]['subscale_table']['group_information'] = array();
                            }

                            if(!isset($tableKAdmin['companies'][$company]['item_table']['group_information'])){
                                $tableKAdmin['companies'][$company]['item_table']['group_information'] = array();
                            }

                            foreach($scales as $scale){

                                if(!isset($tableKAdmin['companies'][$company]['scale_table']['scales'][$scale])){
                                    $tableKAdmin['companies'][$company]['scale_table']['scales'][$scale] = array();
                                }

                                if(!isset($tableKAdmin['companies'][$company]['scale_table']['scales'][$scale]['gesamt'])){
                                    $tableKAdmin['companies'][$company]['scale_table']['scales'][$scale]['gesamt'] = array();
                                }

                                if(!isset($tableKAdmin['companies'][$company]['scale_table']['scales'][$scale]['groups'])){
                                    $tableKAdmin['companies'][$company]['scale_table']['scales'][$scale]['groups'] = array();
                                }

                                if(!isset($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scale])){
                                    $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scale] = array();
                                }

                                if(!isset($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scale]['subscales'])){
                                    $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scale]['subscales'] = array();
                                }

                                if(!isset($tableKAdmin['companies'][$company]['item_table']['scales'][$scale])){
                                    $tableKAdmin['companies'][$company]['item_table']['scales'][$scale] = array();
                                }

                                if(!isset($tableKAdmin['companies'][$company]['item_table']['scales'][$scale]['subscales'])){
                                    $tableKAdmin['companies'][$company]['item_table']['scales'][$scale]['subscales'] = array();
                                }
                            }
    
                            foreach($ids as $formkey => $formid){
                                $scaleThisForm = $scales[$formkey];
                                $fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($formid);
                                
                                foreach($fields as $field){
            
                                    if($field->getType() == "matrix"){
                                        // Überschriften der Matrix
                                        $fieldHeadings = $field->getAttributesJsonDecoded()['headings'];
                                        $labelsThisField = array();
                                        $valuesThisField = array();
                                        foreach($fieldHeadings as $fHead){
                                            $labelsThisField[] = $fHead['text'];
                                            $valuesThisField[] = $fHead['value'];
                                        }
                                        // Informationen über Fragen der Matrix
                                        $fieldQuestions = $field->getAttributesJsonDecoded()['questions'];
                                        $fQuestions = array();
                                        $fQuestionsMeta = array();
                                        foreach($fieldQuestions as $fieldQuestionIndex => $fieldQuestion){
                                            $fQuestions[$fieldQuestionIndex] = $fieldQuestion["question"];
                                            $fQuestionsMeta[$fieldQuestionIndex] = $fieldQuestion["meta"];
                                        }
            
                                        // Sammlung für die Subskalen
                                        $subscales = array();
                                        $subscalesItemsCount = array();
            
                                        foreach($fQuestionsMeta as $qMeta){
            
                                            if(!in_array($qMeta, $subscales)){
                                                $subscales[] = $qMeta;
                                            }
        
                                            if(!isset($subscalesItemsCount[$qMeta])){
                                                $subscalesItemsCount[$qMeta] = 0;
                                            }
            
                                            $subscalesItemsCount[$qMeta]++;
                                        }
            
                                        // Null-Matrix der Größe Elemente Headings x Anzahl Questions
                                        $fieldData = array();
                                        // Null-Vektor der Größe 1 x Anzahl Questions
                                        $fieldTN =  array();
                                        foreach($fQuestions as $fQIndex => $fQ){
                                            $fieldData[$fQIndex] = array();
                                            foreach($valuesThisField as $valF){
                                                $fieldData[$fQIndex][$valF] = 0;
                                            }
            
                                            $fieldTN[$fQIndex] = 0;
                                        }
            
                                        // Speicherung der Häufigkeitsverteilungen für jede Gruppe
                                        $groupFieldData = array();
                                        // Speicherung der Anzahl an Teilnehmenden für jede Gruppe für jede Frage
                                        $groupFieldTN = array();
                                        // Speicherung der Häufigkeitsverteilungen gesamt
                                        $fieldDataTotal = $fieldData;
                                        // Speicherung der Anzahl an Teilnehmenden gesamt für jede Frage
                                        $fieldTNTotal = $fieldTN;
            
                                        foreach($groups as $groupID => $group){
                                            $groupFieldData[$groupID] = $fieldData;
                                            $groupFieldTN[$groupID] = $fieldTN;
                                            $usersThisGroup = $group['users'];

                                            if(!isset($tableKAdmin['companies'][$company]['scale_table']['group_information'][$groupID])){
                                                $tableKAdmin['companies'][$company]['scale_table']['group_information'][$groupID] = array();
                                            }

                                            $tableKAdmin['companies'][$company]['scale_table']['group_information'][$groupID]['groupname'] = $group['name'];
                                            $tableKAdmin['companies'][$company]['scale_table']['group_information'][$groupID]['countPersons'] = sizeof($group['users']);
                
                                            if(!isset($tableKAdmin['companies'][$company]['subscale_table']['group_information'][$groupID])){
                                                $tableKAdmin['companies'][$company]['subscale_table']['group_information'][$groupID] = array();
                                            }

                                            $tableKAdmin['companies'][$company]['subscale_table']['group_information'][$groupID]['groupname'] = $group['name'];
                                            $tableKAdmin['companies'][$company]['subscale_table']['group_information'][$groupID]['countPersons'] = sizeof($group['users']);
                
                                            if(!isset($tableKAdmin['companies'][$company]['item_table']['group_information'][$groupID])){
                                                $tableKAdmin['companies'][$company]['item_table']['group_information'][$groupID] = array();
                                            }

                                            $tableKAdmin['companies'][$company]['item_table']['group_information'][$groupID]['groupname'] = $group['name'];
                                            $tableKAdmin['companies'][$company]['item_table']['group_information'][$groupID]['countPersons'] = sizeof($group['users']);
        
                                            foreach($scales as $scale){
                                                
                                                if(!isset($tableKAdmin['companies'][$company]['scale_table']['scales'][$scale]['groups'][$groupID])){
                                                    $tableKAdmin['companies'][$company]['scale_table']['scales'][$scale]['groups'][$groupID] = array();
                                                }
                                            }
    
                                            $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $usersThisGroup);
                                            
                                            $queryArgs = array(
                                                'meta_key' => 'team_leader',
                                                'meta_value' => $groupID
                                            );
                                            $user_query = new WP_User_Query( $queryArgs );
                                            $thisGroupTeamleader = $user_query->get_results();
        
                                            $thisGroupTeamleaderId = "";
                                            if(!empty($thisGroupTeamleader)){
                                                foreach($thisGroupTeamleader as $gLeader){
                                                    $thisGroupTeamleaderId = $gLeader->ID;
                                                }
                                            }
        
                                            foreach($data as $eingabe){
                                                if($eingabe->getUserId() != $thisGroupTeamleaderId){
                                                    $thisUserData = json_decode($eingabe->getData(), true);
                                                    foreach($fieldQuestions as $qI => $qData){  
                
                                                        if(isset($thisUserData[$qI])){
                                                            if(trim($thisUserData[$qI]) != ""){
                                                                $groupFieldData[$groupID][$qI][$thisUserData[$qI]]++;
                                                                $groupFieldTN[$groupID][$qI]++;
                                                                $fieldDataTotal[$qI][$thisUserData[$qI]]++;
                                                                $fieldTNTotal[$qI]++;
                                                            }
                                                        }
                                                    }
                                                }
        
                                            }
                                        }
            
                                        $subscalesTNReached = array();
            
                                        foreach($groups as $grID => $gr){
                                            foreach($subscales as $subscale){
                                                $subscalesTNReached[$grID][$subscale] = true;

                                                if(!isset($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale])){
                                                    $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale] = array();
                                                }

                                                if(!isset($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'])){
                                                    $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'] = array();
                                                }

                                                if(!isset($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$grID])){
                                                    $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$grID] = array();
                                                }
                
                                                if(!isset($tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$subscale])){
                                                    $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$subscale] = array();
                                                }

                                                if(!isset($tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$subscale]['items'])){
                                                    $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$subscale]['items'] = array();
                                                }
                                                
                                            }
                                        }
            
            
                                        $meanQuestionsTotal = array();
                                        $sumMeansTotal = array();
                                        $sumMeansGroup = array();
    
                                        $subscalesTNTotalReached = array();
                                        foreach($subscales as $subscaleTotal){
                                            $subscalesTNTotalReached[$subscaleTotal] = true;
                                        }
            
                                        
                                        foreach($fQuestions as $fQKey => $fQValue){
                                            $metaThisQuestion = $fQuestionsMeta[$fQKey];
                                            $sumThisQuestionTotal = 0;
                                            foreach($fieldDataTotal[$fQKey] as $vKeyTotal => $vValTotal){
                                                $sumThisQuestionTotal += $vKeyTotal*$vValTotal;
                                            }
                                            
                                            if(!isset($sumMeansTotal[$metaThisQuestion])){
                                                $sumMeansTotal[$metaThisQuestion] = 0;
                                            }
            
                                            if($fieldTNTotal[$fQKey] == 0){
                                                $meanQuestionsTotal[$fQKey] = "-";
                                            }
                                            else{
                                                $meanQuestionsTotal[$fQKey] = $sumThisQuestionTotal/$fieldTNTotal[$fQKey];
                                                $sumMeansTotal[$metaThisQuestion] += $meanQuestionsTotal[$fQKey];
                                            }
            
                                            foreach($groups as $groupID => $group){

                                                if(!isset($tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue])){
                                                    $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue] = array();
                                                }

                                                if(!isset($tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'])){
                                                    $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'] = array();
                                                }

                                                if(!isset($tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID])){
                                                    $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID] = array();
                                                }
                                                
                                                $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['item_mean'] = "-";
                                                $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "ffffff";

                                                // get input count for the current group - item level
                                                $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['item_input_count'] = $groupFieldTN[$groupID][$fQKey];
            
                                                $sumValuesThisGroup = 0;
                                                foreach($groupFieldData[$groupID][$fQKey] as $vKey => $vVal){
                                                    $sumValuesThisGroup += $vKey*$vVal;
                                                }
                            
                                                $meanThisGroup = 0;
                                                if($groupFieldTN[$groupID][$fQKey] == 0){
                                                    $meanThisGroup = "-";
                                                }
                                                else{
                                                    $meanThisGroup = $sumValuesThisGroup/$groupFieldTN[$groupID][$fQKey];
            
                                                    if(!isset($sumMeansGroup[$groupID])){
                                                        $sumMeansGroup[$groupID] = array();
                                                    }
        
                                                    if(!isset($sumMeansGroup[$groupID][$metaThisQuestion])){
                                                        $sumMeansGroup[$groupID][$metaThisQuestion] = 0;
                                                    }
            
                                                    $sumMeansGroup[$groupID][$metaThisQuestion] += $meanThisGroup;
                                                }
    
                                                if($groupFieldTN[$groupID][$fQKey] >= self::MINTEILNEHMER){

                                                    $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['item_mean'] = round($meanThisGroup,1);

                                                    if($mode[$formid] == "+-"){
                                                        if(round($meanThisGroup,1)<= 2.3){
                                                            $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "bfe2ca";
                                                        }
                                                        else if(round($meanThisGroup,1)>= 3.7){
                                                            $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "f4858e";
                                                        }
                                                        else{
                                                            $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "fed88f";
                                                        }
                                                    }
                                                    else if($mode[$formid] == "-+"){
                                                        if(round($meanThisGroup,1)<= 2.3){
                                                            $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "f4858e";
                                                        }
                                                        else if(round($meanThisGroup,1)>= 3.7){
                                                            $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "bfe2ca";
                                                        }
                                                        else{
                                                            $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "fed88f";
                                                        }
                                                    }


                                                }
                                                else{
                                                    $subscalesTNReached[$groupID][$metaThisQuestion] = false;
                                                }
                    
                                            }

                                            if(!isset($tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt'])){
                                                $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt'] = array();
                                            }

                                            $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['item_mean'] = "-";
                                            $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "ffffff";

                                            // get input count for the company - item level
                                            $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['item_input_count'] = $fieldTNTotal[$fQKey];
                                            
                                            if($fieldTNTotal[$fQKey] >= self::MINTEILNEHMER){
                                                $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['item_mean'] = round($meanQuestionsTotal[$fQKey],1);

                                                if($mode[$formid] == "+-"){
                                                    if(round($meanQuestionsTotal[$fQKey],1)<= 2.3){
                                                        $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "bfe2ca";
                                                    }
                                                    else if(round($meanQuestionsTotal[$fQKey],1)>= 3.7){
                                                        $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "f4858e";
                                                    }
                                                    else{
                                                        $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "fed88f";
                                                    }
                                                }
                                                else if($mode[$formid] == "-+"){
                                                    if(round($meanQuestionsTotal[$fQKey],1)<= 2.3){
                                                        $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "f4858e";
                                                    }
                                                    else if(round($meanQuestionsTotal[$fQKey],1)>= 3.7){
                                                        $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "bfe2ca";
                                                    }
                                                    else{
                                                        $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "fed88f";
                                                    }
                                                }
                                            }
                                            else{
                                                $subscalesTNTotalReached[$metaThisQuestion] = false;
                                            }
                                        }
    
                                        foreach($groups as $gID => $group){
                                            $scaleTNReached = true;
                                            $sumSubscalesGroup = 0;
    
                                            foreach($subscales as $subscale){
                                                
                                                $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_mean'] = "-";
                                                $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "ffffff";

                                                // get the max/min input count for the current group - subscale level
                                                $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_min'] = null;
                                                $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_max'] = null;
                                                $subscaleItems = $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$subscale]['items'];
                                                foreach($subscaleItems as $subscaleItem){
                                                    if(isset($subscaleItem['groups'][$gID]['item_input_count'])){
                                                        if(is_null($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_min'])){
                                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_min'] = $subscaleItem['groups'][$gID]['item_input_count'];
                                                        }
                                                        else{
                                                            if($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_min'] > $subscaleItem['groups'][$gID]['item_input_count']){
                                                                $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_min'] = $subscaleItem['groups'][$gID]['item_input_count'];
                                                            }
                                                        }

                                                        if(is_null($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_max'])){
                                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_max'] = $subscaleItem['groups'][$gID]['item_input_count'];
                                                        }
                                                        else{
                                                            if($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_max'] < $subscaleItem['groups'][$gID]['item_input_count']){
                                                                $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_max'] = $subscaleItem['groups'][$gID]['item_input_count'];
                                                            }
                                                        }
                                                    }
                                                }

                                                if($subscalesTNReached[$gID][$subscale] == true){

                                                    $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_mean'] = round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale],1);
                                                    
                                                    if($mode[$formid] == "+-"){
                                                        if(round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale],1)<= 2.3){
                                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "bfe2ca";
                                                        }
                                                        else if(round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale],1)>= 3.7){
                                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "f4858e";
                                                        }
                                                        else{
                                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "fed88f";
                                                        }
                                                    }
                                                    else if($mode[$formid] == "-+"){
                                                        if(round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale],1)<= 2.3){
                                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "f4858e";
                                                        }
                                                        else if(round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale],1)>= 3.7){
                                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "bfe2ca";
                                                        }
                                                        else{
                                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "fed88f";
                                                        }
                                                    }

                                                    $sumSubscalesGroup += round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale],1);
                                                }
                                                else{
                                                    $scaleTNReached = false;
                                                }
                                            }
                                            
                                            $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_mean'] = "-";
                                            $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "ffffff";

                                            // get the max/min input count for the current group - scale level
                                            $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_min'] = null;
                                            $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_max'] = null;
                                            $scaleSubscales = $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'];
                                            foreach($scaleSubscales as $scaleSubscale){
                                                if(isset($scaleSubscale['groups'][$gID]['subscale_input_count_min'])){
                                                    if(is_null($tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_min'])){
                                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_min'] = $scaleSubscale['groups'][$gID]['subscale_input_count_min'];
                                                    }
                                                    else{
                                                        if($tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_min'] > $scaleSubscale['groups'][$gID]['subscale_input_count_min']){
                                                            $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_min'] = $scaleSubscale['groups'][$gID]['subscale_input_count_min'];
                                                        }
                                                    }
                                                }

                                                if(isset($scaleSubscale['groups'][$gID]['subscale_input_count_max'])){
                                                    if(is_null($tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_max'])){
                                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_max'] = $scaleSubscale['groups'][$gID]['subscale_input_count_max'];
                                                    }
                                                    else{
                                                        if($tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_max'] < $scaleSubscale['groups'][$gID]['subscale_input_count_max']){
                                                            $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_max'] = $scaleSubscale['groups'][$gID]['subscale_input_count_max'];
                                                        }
                                                    }
                                                }
                                            }

                                            if($scaleTNReached){

                                                $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_mean'] = round($sumSubscalesGroup/sizeof($subscales),1);
                                                if($mode[$formid] == "+-"){
                                                    if(round($sumSubscalesGroup/sizeof($subscales),1)<= 2.3){
                                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "bfe2ca";
                                                    }
                                                    else if(round($sumSubscalesGroup/sizeof($subscales),1)>= 3.7){
                                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "f4858e";
                                                    }
                                                    else{
                                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "fed88f";
                                                    }
                                                }
                                                else if($mode[$formid] == "-+"){
                                                    if(round($sumSubscalesGroup/sizeof($subscales),1)<= 2.3){
                                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "f4858e";
                                                    }
                                                    else if(round($sumSubscalesGroup/sizeof($subscales),1)>= 3.7){
                                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "bfe2ca";
                                                    }
                                                    else{
                                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "fed88f";
                                                    }
                                                }
                                            }
                                        }
    
                                        $scaleTNTotalReached = true;
                                        $sumScalesTotal = 0;
    
                                        foreach($subscales as $subscale){
                                            if(!isset($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt'])){
                                                $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt'] = array();
                                            }
                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_mean'] = "-";
                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "ffffff";

                                            // get the max/min input count for the company - subscale level
                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_min'] = null;
                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_max'] = null;
                                            $subscaleItemsTotal = $tableKAdmin['companies'][$company]['item_table']['scales'][$scaleThisForm]['subscales'][$subscale]['items'];

                                            foreach($subscaleItemsTotal as $subscaleItemTotal){
                                                if(isset($subscaleItemTotal['gesamt']['item_input_count'])){
                                                    if(is_null($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_min'])){
                                                        $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_min'] = $subscaleItemTotal['gesamt']['item_input_count'];
                                                    }
                                                    else{
                                                        if($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_min'] > $subscaleItemTotal['gesamt']['item_input_count']){
                                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_min'] = $subscaleItemTotal['gesamt']['item_input_count'];
                                                        }
                                                    }

                                                    if(is_null($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_max'])){
                                                        $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_max'] = $subscaleItemTotal['gesamt']['item_input_count'];
                                                    }
                                                    else{
                                                        if($tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_max'] < $subscaleItemTotal['gesamt']['item_input_count']){
                                                            $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_max'] = $subscaleItemTotal['gesamt']['item_input_count'];
                                                        }
                                                    }
                                                }
                                            }

                                            if($subscalesTNTotalReached[$subscale]){

                                                $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_mean'] = round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale],1);
                                                if($mode[$formid] == "+-"){
                                                    if(round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale],1)<= 2.3){
                                                        $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "bfe2ca";
                                                    }
                                                    else if(round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale],1)>= 3.7){
                                                        $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "f4858e";
                                                    }
                                                    else{
                                                        $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "fed88f";
                                                    }
                                                }
                                                else if($mode[$formid] == "-+"){
                                                    if(round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale],1)<= 2.3){
                                                        $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "f4858e";
                                                    }
                                                    else if(round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale],1)>= 3.7){
                                                        $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "bfe2ca";
                                                    }
                                                    else{
                                                        $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "fed88f";
                                                    }
                                                }

                                                
                                                $sumScalesTotal += round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale],1);
                                            }
                                            else{
                                                $scaleTNTotalReached = false;
                                            }
                                        }
                                        
                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_mean'] = "-";
                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "ffffff";

                                        // get the max/min input count for the company - scale level
                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_min'] = null;
                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_max'] = null;
                                        $scaleSubscalesTotal = $tableKAdmin['companies'][$company]['subscale_table']['scales'][$scaleThisForm]['subscales'];
                                        foreach($scaleSubscalesTotal as $scaleSubscaleTotal){
                                            if(isset($scaleSubscaleTotal['gesamt']['subscale_input_count_min'])){
                                                if(is_null($tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_min'])){
                                                    $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_min'] = $scaleSubscaleTotal['gesamt']['subscale_input_count_min'];
                                                }
                                                else{
                                                    if($tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_min'] > $scaleSubscaleTotal['gesamt']['subscale_input_count_min']){
                                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_min'] = $scaleSubscaleTotal['gesamt']['subscale_input_count_min'];
                                                    }
                                                }
                                            }

                                            if(isset($scaleSubscaleTotal['gesamt']['subscale_input_count_max'])){
                                                if(is_null($tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_max'])){
                                                    $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_max'] = $scaleSubscaleTotal['gesamt']['subscale_input_count_max'];
                                                }
                                                else{
                                                    if($tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_max'] < $scaleSubscaleTotal['gesamt']['subscale_input_count_max']){
                                                        $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_max'] = $scaleSubscaleTotal['gesamt']['subscale_input_count_max'];
                                                    }
                                                }
                                            }
                                        }

                                        if($scaleTNTotalReached){

                                            $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_mean'] = round($sumScalesTotal/sizeof($subscales),1);

                                            if($mode[$formid] == "+-"){
                                                if(round($sumScalesTotal/sizeof($subscales),1)<= 2.3){
                                                    $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "bfe2ca";
                                                }
                                                else if(round($sumScalesTotal/sizeof($subscales),1)>= 3.7){
                                                    $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "f4858e";
                                                }
                                                else{
                                                    $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "fed88f";
                                                }
                                            }
                                            else if($mode[$formid] == "-+"){
                                                if(round($sumScalesTotal/sizeof($subscales),1)<= 2.3){
                                                    $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "f4858e";
                                                }
                                                else if(round($sumScalesTotal/sizeof($subscales),1)>= 3.7){
                                                    $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "bfe2ca";
                                                }
                                                else{
                                                    $tableKAdmin['companies'][$company]['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "fed88f";
                                                }
                                            }
                                        }
                                                                            
                                    }
                                }
                            }
                        }
                    }
                }
                else if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("gbumittelwerteboss")){
                    $company_users = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getUsersByBossId($uid);
                    if(sizeof($company_users) > 0){
                        $isBoss = true;


                        if(!isset($tableBoss['scale_table'])){
                            $tableBoss['scale_table'] = array();
                        }

                        if(!isset($tableBoss['scale_table']['scales'])){
                            $tableBoss['scale_table']['scales'] = array();
                        }

                        if(!isset($tableBoss['scale_table']['gesamt_information'])){
                            $tableBoss['scale_table']['gesamt_information'] = array();
                        }

                        if(!isset($tableBoss['subscale_table'])){
                            $tableBoss['subscale_table'] = array();
                        }

                        if(!isset($tableBoss['subscale_table']['scales'])){
                            $tableBoss['subscale_table']['scales'] = array();
                        }

                        if(!isset($tableBoss['subscale_table']['gesamt_information'])){
                            $tableBoss['subscale_table']['gesamt_information'] = array();
                        }

                        if(!isset($tableBoss['item_table'])){
                            $tableBoss['item_table'] = array();
                        }

                        if(!isset($tableBoss['item_table']['scales'])){
                            $tableBoss['item_table']['scales'] = array();
                        }

                        if(!isset($tableBoss['item_table']['gesamt_information'])){
                            $tableBoss['item_table']['gesamt_information'] = array();
                        }

                        $tableBoss['scale_table']['gesamt_information']['countPersons'] = sizeof($company_users);
                        $tableBoss['subscale_table']['gesamt_information']['countPersons'] = sizeof($company_users);
                        $tableBoss['item_table']['gesamt_information']['countPersons'] = sizeof($company_users);

                        if(!isset($tableBoss['scale_table']['group_information'])){
                            $tableBoss['scale_table']['group_information'] = array();
                        }

                        if(!isset($tableBoss['subscale_table']['group_information'])){
                            $tableBoss['subscale_table']['group_information'] = array();
                        }

                        if(!isset($tableBoss['item_table']['group_information'])){
                            $tableBoss['item_table']['group_information'] = array();
                        }

                        $groups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroupsByBossId($uid);
                        foreach($groups as $groupID => $group){
                            if(!isset($tableBoss['scale_table']['group_information'][$groupID])){
                                $tableBoss['scale_table']['group_information'][$groupID] = array();
                            }
                            $tableBoss['scale_table']['group_information'][$groupID]['countPersons'] = sizeof($group['users']);
                            $tableBoss['scale_table']['group_information'][$groupID]['groupname'] = $group['name'];

                            if(!isset($tableBoss['subscale_table']['group_information'][$groupID])){
                                $tableBoss['subscale_table']['group_information'][$groupID] = array();
                            }
                            $tableBoss['subscale_table']['group_information'][$groupID]['countPersons'] = sizeof($group['users']);
                            $tableBoss['subscale_table']['group_information'][$groupID]['groupname'] = $group['name'];

                            if(!isset($tableBoss['item_table']['group_information'][$groupID])){
                                $tableBoss['item_table']['group_information'][$groupID] = array();
                            }
                            $tableBoss['item_table']['group_information'][$groupID]['countPersons'] = sizeof($group['users']);
                            $tableBoss['item_table']['group_information'][$groupID]['groupname'] = $group['name'];
                        }



                        foreach($scales as $scale){

                            if(!isset($tableBoss['scale_table']['scales'][$scale])){
                                $tableBoss['scale_table']['scales'][$scale] = array();
                            }

                            if(!isset($tableBoss['scale_table']['scales'][$scale]['gesamt'])){
                                $tableBoss['scale_table']['scales'][$scale]['gesamt'] = array();
                            }

                            if(!isset($tableBoss['scale_table']['scales'][$scale]['groups'])){
                                $tableBoss['scale_table']['scales'][$scale]['groups'] = array();
                            }

                            if(!isset($tableBoss['subscale_table']['scales'][$scale])){
                                $tableBoss['subscale_table']['scales'][$scale] = array();
                            }

                            if(!isset($tableBoss['subscale_table']['scales'][$scale]['subscales'])){
                                $tableBoss['subscale_table']['scales'][$scale]['subscales'] = array();
                            }

                            if(!isset($tableBoss['item_table']['scales'][$scale])){
                                $tableBoss['item_table']['scales'][$scale] = array();
                            }

                            if(!isset($tableBoss['item_table']['scales'][$scale]['subscales'])){
                                $tableBoss['item_table']['scales'][$scale]['subscales'] = array();
                            }
                               
                        }

                        foreach($ids as $formkey => $formid){
                            $scaleThisForm = $scales[$formkey];
                            $fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($formid);
                            
                            foreach($fields as $field){
        
                                if($field->getType() == "matrix"){
                                    // Überschriften der Matrix
                                    $fieldHeadings = $field->getAttributesJsonDecoded()['headings'];
                                    $labelsThisField = array();
                                    $valuesThisField = array();
                                    foreach($fieldHeadings as $fHead){
                                        $labelsThisField[] = $fHead['text'];
                                        $valuesThisField[] = $fHead['value'];
                                    }
                                    // Informationen über Fragen der Matrix
                                    $fieldQuestions = $field->getAttributesJsonDecoded()['questions'];
                                    $fQuestions = array();
                                    $fQuestionsMeta = array();
                                    foreach($fieldQuestions as $fieldQuestionIndex => $fieldQuestion){
                                        $fQuestions[$fieldQuestionIndex] = $fieldQuestion["question"];
                                        $fQuestionsMeta[$fieldQuestionIndex] = $fieldQuestion["meta"];
                                    }
        
                                    // Sammlung für die Subskalen
                                    $subscales = array();
                                    $subscalesItemsCount = array();
        
                                    foreach($fQuestionsMeta as $qMeta){
        
                                        if(!in_array($qMeta, $subscales)){
                                            $subscales[] = $qMeta;
                                        }
    
                                        if(!isset($subscalesItemsCount[$qMeta])){
                                            $subscalesItemsCount[$qMeta] = 0;
                                        }
        
                                        $subscalesItemsCount[$qMeta]++;
                                    }
        
                                    // Null-Matrix der Größe Elemente Headings x Anzahl Questions
                                    $fieldData = array();
                                    // Null-Vektor der Größe 1 x Anzahl Questions
                                    $fieldTN =  array();
                                    foreach($fQuestions as $fQIndex => $fQ){
                                        $fieldData[$fQIndex] = array();
                                        foreach($valuesThisField as $valF){
                                            $fieldData[$fQIndex][$valF] = 0;
                                        }
        
                                        $fieldTN[$fQIndex] = 0;
                                    }
        
                                    // Speicherung der Häufigkeitsverteilungen für jede Gruppe
                                    $groupFieldData = array();
                                    // Speicherung der Anzahl an Teilnehmenden für jede Gruppe für jede Frage
                                    $groupFieldTN = array();
                                    // Speicherung der Häufigkeitsverteilungen gesamt
                                    $fieldDataTotal = $fieldData;
                                    // Speicherung der Anzahl an Teilnehmenden gesamt für jede Frage
                                    $fieldTNTotal = $fieldTN;
        
                                    foreach($groups as $groupID => $group){
                                        $groupFieldData[$groupID] = $fieldData;
                                        $groupFieldTN[$groupID] = $fieldTN;
                                        $usersThisGroup = $group['users'];

                                        foreach($scales as $scale){

                                            if(!isset($tableBoss['scale_table']['scales'][$scale]['groups'][$groupID])){
                                                $tableBoss['scale_table']['scales'][$scale]['groups'][$groupID] = array();
                                            }
                
                                        }

                                        $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $usersThisGroup);
                                        
                                        $queryArgs = array(
                                            'meta_key' => 'team_leader',
                                            'meta_value' => $groupID
                                        );
                                        $user_query = new WP_User_Query( $queryArgs );
                                        $thisGroupTeamleader = $user_query->get_results();
    
                                        $thisGroupTeamleaderId = "";
                                        if(!empty($thisGroupTeamleader)){
                                            foreach($thisGroupTeamleader as $gLeader){
                                                $thisGroupTeamleaderId = $gLeader->ID;
                                            }
                                        }
    
                                        foreach($data as $eingabe){
                                            if($eingabe->getUserId() != $thisGroupTeamleaderId){
                                                $thisUserData = json_decode($eingabe->getData(), true);
                                                foreach($fieldQuestions as $qI => $qData){ 
            
                                                    if(isset($thisUserData[$qI])){
                                                        if(trim($thisUserData[$qI]) != ""){
                                                            $groupFieldData[$groupID][$qI][$thisUserData[$qI]]++;
                                                            $groupFieldTN[$groupID][$qI]++;
                                                            $fieldDataTotal[$qI][$thisUserData[$qI]]++;
                                                            $fieldTNTotal[$qI]++;
                                                        }
                                                    }
                                                }
                                            }
    
                                        }
                                    }
        
                                    $subscalesTNReached = array();
        
                                    foreach($groups as $grID => $gr){
                                        foreach($subscales as $subscale){
                                            $subscalesTNReached[$grID][$subscale] = true;



                                            if(!isset($tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale])){
                                                $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale] = array();
                                            }

                                            if(!isset($tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'])){
                                                $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'] = array();
                                            }
                                            
                                            if(!isset($tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$grID])){
                                                $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$grID] = array();
                                            }

                                            if(!isset($tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$subscale])){
                                                $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$subscale] = array();
                                            }

                                            if(!isset($tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$subscale]['items'])){
                                                $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$subscale]['items'] = array();
                                            }

                                        }
                                    }
                
                                    $meanQuestionsTotal = array();
                                    $sumMeansTotal = array();
                                    $sumMeansGroup = array();

                                    $subscalesTNTotalReached = array();
                                    foreach($subscales as $subscaleTotal){
                                        $subscalesTNTotalReached[$subscaleTotal] = true;
                                    }
        
                                    
                                    foreach($fQuestions as $fQKey => $fQValue){
                                        $metaThisQuestion = $fQuestionsMeta[$fQKey];
                                        $sumThisQuestionTotal = 0;
                                        foreach($fieldDataTotal[$fQKey] as $vKeyTotal => $vValTotal){
                                            $sumThisQuestionTotal += $vKeyTotal*$vValTotal;
                                        }
                                        
                                        if(!isset($sumMeansTotal[$metaThisQuestion])){
                                            $sumMeansTotal[$metaThisQuestion] = 0;
                                        }
        
                                        if($fieldTNTotal[$fQKey] == 0){
                                            $meanQuestionsTotal[$fQKey] = "-";
                                        }
                                        else{
                                            $meanQuestionsTotal[$fQKey] = $sumThisQuestionTotal/$fieldTNTotal[$fQKey];
                                            $sumMeansTotal[$metaThisQuestion] += $meanQuestionsTotal[$fQKey];
                                        }
        
                                        foreach($groups as $groupID => $group){

                                            if(!isset($tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue])){
                                                $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue] = array();
                                            }

                                            if(!isset($tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'])){
                                                $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'] = array();
                                            }

                                            if(!isset($tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID])){
                                                $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID] = array();
                                            }

                                            $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['item_mean'] = "-";
                                            $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "ffffff";
                                            
                                            // get input count for the current group - item level
                                            $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['item_input_count'] = $groupFieldTN[$groupID][$fQKey];

                                            $sumValuesThisGroup = 0;
                                            foreach($groupFieldData[$groupID][$fQKey] as $vKey => $vVal){
                                                $sumValuesThisGroup += $vKey*$vVal;
                                            }
                        
                                            $meanThisGroup = 0;
                                            if($groupFieldTN[$groupID][$fQKey] == 0){
                                                $meanThisGroup = "-";
                                            }
                                            else{
                                                $meanThisGroup = $sumValuesThisGroup/$groupFieldTN[$groupID][$fQKey];
        
                                                if(!isset($sumMeansGroup[$groupID])){
                                                    $sumMeansGroup[$groupID] = array();
                                                }
    
                                                if(!isset($sumMeansGroup[$groupID][$metaThisQuestion])){
                                                    $sumMeansGroup[$groupID][$metaThisQuestion] = 0;
                                                }
        
                                                $sumMeansGroup[$groupID][$metaThisQuestion] += $meanThisGroup;
                                            }

                                            if($groupFieldTN[$groupID][$fQKey] >= self::MINTEILNEHMER){

                                                $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['item_mean'] = round($meanThisGroup,1);
                                                if($mode[$formid] == "+-"){
                                                    if(round($meanThisGroup,1)<= 2.3){
                                                        $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "bfe2ca";
                                                    }
                                                    else if(round($meanThisGroup,1)>= 3.7){
                                                        $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "f4858e";
                                                    }
                                                    else{
                                                        $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "fed88f";
                                                    }
                                                }
                                                else if($mode[$formid] == "-+"){
                                                    if(round($meanThisGroup,1)<= 2.3){
                                                        $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "f4858e";
                                                    }
                                                    else if(round($meanThisGroup,1)>= 3.7){
                                                        $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "bfe2ca";
                                                    }
                                                    else{
                                                        $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['groups'][$groupID]['val_color'] = "fed88f";
                                                    }
                                                }
                                            }
                                            else{
                                                $subscalesTNReached[$groupID][$metaThisQuestion] = false;
                                            }
                
                                        }

                                        if(!isset($tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt'])){
                                            $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt'] = array();
                                        }
                                        $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['item_mean'] = "-";
                                        $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "ffffff";
                                        
                                        // get input count for the company - item level
                                        $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['item_input_count'] = $fieldTNTotal[$fQKey];

                                        if($fieldTNTotal[$fQKey] >= self::MINTEILNEHMER){

                                            $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['item_mean'] = round($meanQuestionsTotal[$fQKey],1);
                                            if($mode[$formid] == "+-"){
                                                if(round($meanQuestionsTotal[$fQKey],1)<= 2.3){
                                                    $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "bfe2ca";
                                                }
                                                else if(round($meanQuestionsTotal[$fQKey],1)>= 3.7){
                                                    $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "f4858e";
                                                }
                                                else{
                                                    $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "fed88f";
                                                }
                                            }
                                            else if($mode[$formid] == "-+"){
                                                if(round($meanQuestionsTotal[$fQKey],1)<= 2.3){
                                                    $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "f4858e";
                                                }
                                                else if(round($meanQuestionsTotal[$fQKey],1)>= 3.7){
                                                    $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "bfe2ca";
                                                }
                                                else{
                                                    $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['gesamt']['val_color'] = "fed88f";
                                                }
                                            }
                                        }
                                        else{
                                            $subscalesTNTotalReached[$metaThisQuestion] = false;
                                        }
                                    }

                                    foreach($groups as $gID => $group){
                                        $scaleTNReached = true;
                                        $sumSubscalesGroup = 0;

                                        foreach($subscales as $subscale){
                                            $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_mean'] = "-";
                                            $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "ffffff";

                                            // get the max/min input count for the current group - subscale level
                                            $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_min'] = null;
                                            $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_max'] = null;
                                            $subscaleItems = $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$subscale]['items'];
                                            foreach($subscaleItems as $subscaleItem){
                                                if(isset($subscaleItem['groups'][$gID]['item_input_count'])){
                                                    if(is_null($tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_min'])){
                                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_min'] = $subscaleItem['groups'][$gID]['item_input_count'];
                                                    }
                                                    else{
                                                        if($tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_min'] > $subscaleItem['groups'][$gID]['item_input_count']){
                                                            $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_min'] = $subscaleItem['groups'][$gID]['item_input_count'];
                                                        }
                                                    }

                                                    if(is_null($tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_max'])){
                                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_max'] = $subscaleItem['groups'][$gID]['item_input_count'];
                                                    }
                                                    else{
                                                        if($tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_max'] < $subscaleItem['groups'][$gID]['item_input_count']){
                                                            $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_input_count_max'] = $subscaleItem['groups'][$gID]['item_input_count'];
                                                        }
                                                    }
                                                }
                                            }

                                            if($subscalesTNReached[$gID][$subscale] == true){


                                                $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['subscale_mean'] = round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale],1);
                                                if($mode[$formid] == "+-"){
                                                    if(round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale],1)<= 2.3){
                                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "bfe2ca";
                                                    }
                                                    else if(round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale],1)>= 3.7){
                                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "f4858e";
                                                    }
                                                    else{
                                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "fed88f";
                                                    }
                                                }
                                                else if($mode[$formid] == "-+"){
                                                    if(round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale],1)<= 2.3){
                                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "f4858e";
                                                    }
                                                    else if(round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale],1)>= 3.7){
                                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "bfe2ca";
                                                    }
                                                    else{
                                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['groups'][$gID]['val_color'] = "fed88f";
                                                    }
                                                }
                                                $sumSubscalesGroup += round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale],1);
                                            }
                                            else{
                                                $scaleTNReached = false;
                                            }
                                        }
                                        $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_mean'] = "-";
                                        $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "ffffff";

                                        // get the max/min input count for the current group - scale level
                                        $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_min'] = null;
                                        $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_max'] = null;
                                        $scaleSubscales = $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'];
                                        foreach($scaleSubscales as $scaleSubscale){
                                            if(isset($scaleSubscale['groups'][$gID]['subscale_input_count_min'])){
                                                if(is_null($tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_min'])){
                                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_min'] = $scaleSubscale['groups'][$gID]['subscale_input_count_min'];
                                                }
                                                else{
                                                    if($tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_min'] > $scaleSubscale['groups'][$gID]['subscale_input_count_min']){
                                                        $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_min'] = $scaleSubscale['groups'][$gID]['subscale_input_count_min'];
                                                    }
                                                }
                                            }

                                            if(isset($scaleSubscale['groups'][$gID]['subscale_input_count_max'])){
                                                if(is_null($tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_max'])){
                                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_max'] = $scaleSubscale['groups'][$gID]['subscale_input_count_max'];
                                                }
                                                else{
                                                    if($tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_max'] < $scaleSubscale['groups'][$gID]['subscale_input_count_max']){
                                                        $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_input_count_max'] = $scaleSubscale['groups'][$gID]['subscale_input_count_max'];
                                                    }
                                                }
                                            }
                                        }

                                        if($scaleTNReached){

                                            $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['scale_mean'] = round($sumSubscalesGroup/sizeof($subscales),1);
                                            if($mode[$formid] == "+-"){
                                                if(round($sumSubscalesGroup/sizeof($subscales),1)<= 2.3){
                                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "bfe2ca";
                                                }
                                                else if(round($sumSubscalesGroup/sizeof($subscales),1)>= 3.7){
                                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "f4858e";
                                                }
                                                else{
                                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "fed88f";
                                                }
                                            }
                                            else if($mode[$formid] == "-+"){
                                                if(round($sumSubscalesGroup/sizeof($subscales),1)<= 2.3){
                                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "f4858e";
                                                }
                                                else if(round($sumSubscalesGroup/sizeof($subscales),1)>= 3.7){
                                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "bfe2ca";
                                                }
                                                else{
                                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['groups'][$gID]['val_color'] = "fed88f";
                                                }
                                            }
                                        }
                                    }

                                    $scaleTNTotalReached = true;
                                    $sumScalesTotal = 0;

                                    foreach($subscales as $subscale){
                                        if(!isset($tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt'])){
                                            $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt'] = array();
                                        }
                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_mean'] = "-";
                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "ffffff";

                                        // get the max/min input count for the company - subscale level
                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_min'] = null;
                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_max'] = null;
                                        $subscaleItemsTotal = $tableBoss['item_table']['scales'][$scaleThisForm]['subscales'][$subscale]['items'];

                                        foreach($subscaleItemsTotal as $subscaleItemTotal){
                                            if(isset($subscaleItemTotal['gesamt']['item_input_count'])){
                                                if(is_null($tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_min'])){
                                                    $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_min'] = $subscaleItemTotal['gesamt']['item_input_count'];
                                                }
                                                else{
                                                    if($tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_min'] > $subscaleItemTotal['gesamt']['item_input_count']){
                                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_min'] = $subscaleItemTotal['gesamt']['item_input_count'];
                                                    }
                                                }

                                                if(is_null($tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_max'])){
                                                    $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_max'] = $subscaleItemTotal['gesamt']['item_input_count'];
                                                }
                                                else{
                                                    if($tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_max'] < $subscaleItemTotal['gesamt']['item_input_count']){
                                                        $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_input_count_max'] = $subscaleItemTotal['gesamt']['item_input_count'];
                                                    }
                                                }
                                            }
                                        }

                                        if($subscalesTNTotalReached[$subscale]){

                                            $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['subscale_mean'] = round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale],1);
                                            if($mode[$formid] == "+-"){
                                                if(round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale],1)<= 2.3){
                                                    $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "bfe2ca";
                                                }
                                                else if(round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale],1)>= 3.7){
                                                    $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "f4858e";
                                                }
                                                else{
                                                    $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "fed88f";
                                                }
                                            }
                                            else if($mode[$formid] == "-+"){
                                                if(round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale],1)<= 2.3){
                                                    $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "f4858e";
                                                }
                                                else if(round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale],1)>= 3.7){
                                                    $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "bfe2ca";
                                                }
                                                else{
                                                    $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['gesamt']['val_color'] = "fed88f";
                                                }
                                            }

                                            $sumScalesTotal += round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale],1);
                                        }
                                        else{
                                            $scaleTNTotalReached = false;
                                        }
                                    }

                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_mean'] = "-";
                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "ffffff";

                                    // get the max/min input count for the company - scale level
                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_min'] = null;
                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_max'] = null;
                                    $scaleSubscalesTotal = $tableBoss['subscale_table']['scales'][$scaleThisForm]['subscales'];
                                    foreach($scaleSubscalesTotal as $scaleSubscaleTotal){
                                        if(isset($scaleSubscaleTotal['gesamt']['subscale_input_count_min'])){
                                            if(is_null($tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_min'])){
                                                $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_min'] = $scaleSubscaleTotal['gesamt']['subscale_input_count_min'];
                                            }
                                            else{
                                                if($tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_min'] > $scaleSubscaleTotal['gesamt']['subscale_input_count_min']){
                                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_min'] = $scaleSubscaleTotal['gesamt']['subscale_input_count_min'];
                                                }
                                            }
                                        }

                                        if(isset($scaleSubscaleTotal['gesamt']['subscale_input_count_max'])){
                                            if(is_null($tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_max'])){
                                                $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_max'] = $scaleSubscaleTotal['gesamt']['subscale_input_count_max'];
                                            }
                                            else{
                                                if($tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_max'] < $scaleSubscaleTotal['gesamt']['subscale_input_count_max']){
                                                    $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_input_count_max'] = $scaleSubscaleTotal['gesamt']['subscale_input_count_max'];
                                                }
                                            }
                                        }
                                    }

                                    if($scaleTNTotalReached){

                                        $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['scale_mean'] = round($sumScalesTotal/sizeof($subscales),1);

                                        if($mode[$formid] == "+-"){
                                            if(round($sumScalesTotal/sizeof($subscales),1)<= 2.3){
                                                $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "bfe2ca";
                                            }
                                            else if(round($sumScalesTotal/sizeof($subscales),1)>= 3.7){
                                                $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "f4858e";
                                            }
                                            else{
                                                $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "fed88f";
                                            }
                                        }
                                        else if($mode[$formid] == "-+"){
                                            if(round($sumScalesTotal/sizeof($subscales),1)<= 2.3){
                                                $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "f4858e";
                                            }
                                            else if(round($sumScalesTotal/sizeof($subscales),1)>= 3.7){
                                                $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "bfe2ca";
                                            }
                                            else{
                                                $tableBoss['scale_table']['scales'][$scaleThisForm]['gesamt']['val_color'] = "fed88f";
                                            }
                                        }
                                    }
                                                                        
                                }
                            }
                        }
                    }
                }
                else if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("gbumittelwerteteamleader")){
                    $teamleaderGroupId = get_user_meta($uid, "team_leader", true);
                    if($teamleaderGroupId != ""){
                        $isTeamleader = true;
                        $teamleaderGroup = Trainingssystem_Plugin_Database::getInstance()->CompanygroupDao->getCompanygroupById($teamleaderGroupId);
                        $teamleaderGroupMembers = $teamleaderGroup->getMembers();
                        $teamleaderGroupIds = array();
                        foreach($teamleaderGroupMembers as $teamleaderGroupMember){
                            $groupMemberId = $teamleaderGroupMember->getId();
                            if($groupMemberId != $uid){
                                $teamleaderGroupIds[] = $groupMemberId;
                            }
                            
                        }
                        $teamleadergroupName = $teamleaderGroup->getName();

                        if(!isset($tableTeamleader['scale_table'])){
                            $tableTeamleader['scale_table'] = array();
                        }

                        if(!isset($tableTeamleader['scale_table']['scales'])){
                            $tableTeamleader['scale_table']['scales'] = array();
                        }

                        if(!isset($tableTeamleader['subscale_table'])){
                            $tableTeamleader['subscale_table'] = array();
                        }

                        if(!isset($tableTeamleader['subscale_table']['scales'])){
                            $tableTeamleader['subscale_table']['scales'] = array();
                        }

                        if(!isset($tableTeamleader['item_table'])){
                            $tableTeamleader['item_table'] = array();
                        }

                        if(!isset($tableTeamleader['item_table']['scales'])){
                            $tableTeamleader['item_table']['scales'] = array();
                        }

                        if(!isset($tableTeamleader['scale_table']['group_information'])){
                            $tableTeamleader['scale_table']['group_information'] = array();
                        }

                        if(!isset($tableTeamleader['subscale_table']['group_information'])){
                            $tableTeamleader['subscale_table']['group_information'] = array();
                        }

                        if(!isset($tableTeamleader['item_table']['group_information'])){
                            $tableTeamleader['item_table']['group_information'] = array();
                        }

                        $tableTeamleader['scale_table']['group_information']['groupname'] = $teamleadergroupName;
                        $tableTeamleader['scale_table']['group_information']['countPersons'] = sizeof($teamleaderGroupMembers);
                        $tableTeamleader['subscale_table']['group_information']['groupname'] = $teamleadergroupName;
                        $tableTeamleader['subscale_table']['group_information']['countPersons'] = sizeof($teamleaderGroupMembers);
                        $tableTeamleader['item_table']['group_information']['groupname'] = $teamleadergroupName;
                        $tableTeamleader['item_table']['group_information']['countPersons'] = sizeof($teamleaderGroupMembers);

                        foreach($scales as $scale){

                            if(!isset($tableTeamleader['scale_table']['scales'][$scale])){
                                $tableTeamleader['scale_table']['scales'][$scale] = array();
                            }

                            if(!isset($tableTeamleader['subscale_table']['scales'][$scale])){
                                $tableTeamleader['subscale_table']['scales'][$scale] = array();
                            }

                            if(!isset($tableTeamleader['item_table']['scales'][$scale])){
                                $tableTeamleader['item_table']['scales'][$scale] = array();
                            }

                        }

                        foreach($ids as $formkey => $formid){
                            $scaleThisForm = $scales[$formkey];
                            $fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($formid);

                            foreach($fields as $field){

                                if($field->getType() == "matrix"){
                                    // Überschriften der Matrix
                                    $fieldHeadings = $field->getAttributesJsonDecoded()['headings'];
                                    $labelsThisField = array();
                                    $valuesThisField = array();
                                    foreach($fieldHeadings as $fHead){
                                        $labelsThisField[] = $fHead['text'];
                                        $valuesThisField[] = $fHead['value'];
                                    }
                                    // Informationen über Fragen der Matrix
                                    $fieldQuestions = $field->getAttributesJsonDecoded()['questions'];
                                    $fQuestions = array();
                                    $fQuestionsMeta = array();
                                    foreach($fieldQuestions as $fieldQuestionIndex => $fieldQuestion){
                                        $fQuestions[$fieldQuestionIndex] = $fieldQuestion["question"];
                                        $fQuestionsMeta[$fieldQuestionIndex] = $fieldQuestion["meta"];
                                    }
    
                                    // Sammlung für die Subskalen
                                    $subscales = array();
                                    $subscalesItemsCount = array();

                                    foreach($fQuestionsMeta as $qMeta){
    
                                        if(!in_array($qMeta, $subscales)){
                                            $subscales[] = $qMeta;

                                            if(!isset($tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'])){
                                                $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'] = array();
                                            }

                                            if(!isset($tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$qMeta])){
                                                $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$qMeta] = array();
                                            }

                                            if(!isset($tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'])){
                                                $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'] = array();
                                            }

                                            if(!isset($tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$qMeta])){
                                                $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$qMeta] = array();
                                            }

                                        }
    
                                        if(!isset($subscalesItemsCount[$qMeta])){
                                            $subscalesItemsCount[$qMeta] = 0;
                                        }
        
                                        $subscalesItemsCount[$qMeta]++;
                                    }

                                    // Null-Matrix der Größe Elemente Headings x Anzahl Questions
                                    $fieldData = array();
                                    // Null-Vektor der Größe 1 x Anzahl Questions
                                    $fieldTN =  array();
                                    foreach($fQuestions as $fQIndex => $fQ){
                                        $fieldData[$fQIndex] = array();
                                        foreach($valuesThisField as $valF){
                                            $fieldData[$fQIndex][$valF] = 0;
                                        }
    
                                        $fieldTN[$fQIndex] = 0;
                                    }

                                    // Speicherung der Häufigkeitsverteilungen für jede Gruppe
                                    $groupFieldData = array();
                                    // Speicherung der Anzahl an Teilnehmenden für jede Gruppe für jede Frage
                                    $groupFieldTN = array();
    
                                    $groupFieldData[$teamleaderGroupId] = $fieldData;
                                    $groupFieldTN[$teamleaderGroupId] = $fieldTN;
                                    $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $teamleaderGroupIds);
                                    foreach($data as $eingabe){
                                        $thisUserData = json_decode($eingabe->getData(), true);
                                        foreach($fieldQuestions as $qI => $qData){  
                                            if(isset($thisUserData[$qI])){
                                                if(trim($thisUserData[$qI]) != ""){
                                                    $groupFieldData[$teamleaderGroupId][$qI][$thisUserData[$qI]]++;
                                                    $groupFieldTN[$teamleaderGroupId][$qI]++;
                                                }

                                            }
                                        }
                                    }
                                    $subscalesTNReached = array();
                                    foreach($subscales as $subscale){
                                        $subscalesTNReached[$teamleaderGroupId][$subscale] = true;
                                    }
        
                                    $sumMeansGroup = array();

                                    foreach($fQuestions as $fQKey => $fQValue){
                                        $metaThisQuestion = $fQuestionsMeta[$fQKey];
                                        
                                        if(!isset($tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'])){
                                            $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'] = array();
                                        }

                                        if(!isset($tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue])){
                                            $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue] = array();
                                        }

                                        
                                        $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['item_mean'] = "-";
                                        $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['val_color'] = "ffffff";

                                        // get input count for the current group - item level
                                        $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['item_input_count'] = $groupFieldTN[$teamleaderGroupId][$fQKey];
                                            
                                        $sumValuesThisGroup = 0;
                                        foreach($groupFieldData[$teamleaderGroupId][$fQKey] as $vKey => $vVal){
                                            $sumValuesThisGroup += $vKey*$vVal;
                                        }
                        
                                        $meanThisGroup = 0;
                                        if($groupFieldTN[$teamleaderGroupId][$fQKey] == 0){
                                            $meanThisGroup = "-";
                                            $subscalesTNReached[$teamleaderGroupId][$metaThisQuestion] = false;
                                        }
                                        else{
                                            $meanThisGroup = $sumValuesThisGroup/$groupFieldTN[$teamleaderGroupId][$fQKey];
        
                                            if(!isset($sumMeansGroup[$teamleaderGroupId])){
                                                $sumMeansGroup[$teamleaderGroupId] = array();
                                            }
    
                                            if(!isset($sumMeansGroup[$teamleaderGroupId][$metaThisQuestion])){
                                                $sumMeansGroup[$teamleaderGroupId][$metaThisQuestion] = 0;
                                            }
        
                                            $sumMeansGroup[$teamleaderGroupId][$metaThisQuestion] += $meanThisGroup;
                                            
                                            if($groupFieldTN[$teamleaderGroupId][$fQKey] >= self::MINTEILNEHMER){
                                                $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['item_mean'] = round($meanThisGroup,1);
                                                
                                                if($mode[$formid] == "+-"){
                                                    if(round($meanThisGroup,1)<= 2.3){
                                                        $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['val_color'] = "bfe2ca";
                                                    }
                                                    else if(round($meanThisGroup,1)>= 3.7){
                                                        $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['val_color'] = "f4858e";
                                                    }
                                                    else{
                                                        $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['val_color'] = "fed88f";
                                                    }
                                                }
                                                else if($mode[$formid] == "-+"){
                                                    if(round($meanThisGroup,1)<= 2.3){
                                                        $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['val_color'] = "f4858e";
                                                    }
                                                    else if(round($meanThisGroup,1)>= 3.7){
                                                        $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['val_color'] = "bfe2ca";
                                                    }
                                                    else{
                                                        $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$metaThisQuestion]['items'][$fQValue]['val_color'] = "fed88f";
                                                    }
                                                }

                                            }
                                            else{
                                                $subscalesTNReached[$teamleaderGroupId][$metaThisQuestion] = false;
                                            }
                                        }

                                    }

                                    $scaleTNReached = true;
                                    $sumSubscalesGroup = 0;

                                    foreach($subscales as $subscale){
                                        $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['subscale_mean'] = "-";
                                        $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['val_color'] = "ffffff";

                                        // get the max/min input count for the current group - subscale level
                                        $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['subscale_input_count_min'] = null;
                                        $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['subscale_input_count_max'] = null;
                                        $subscaleItems = $tableTeamleader['item_table']['scales'][$scaleThisForm]['subscales'][$subscale]['items'];
                                        foreach($subscaleItems as $subscaleItem){
                                            if(isset($subscaleItem['item_input_count'])){
                                                if(is_null($tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['subscale_input_count_min'])){
                                                    $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['subscale_input_count_min'] = $subscaleItem['item_input_count'];
                                                }
                                                else{
                                                    if($tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['subscale_input_count_min'] > $subscaleItem['item_input_count']){
                                                        $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['subscale_input_count_min'] = $subscaleItem['item_input_count'];
                                                    }
                                                }

                                                if(is_null($tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['subscale_input_count_max'])){
                                                    $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['subscale_input_count_max'] = $subscaleItem['item_input_count'];
                                                }
                                                else{
                                                    if($tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['subscale_input_count_max'] < $subscaleItem['item_input_count']){
                                                        $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['subscale_input_count_max'] = $subscaleItem['item_input_count'];
                                                    }
                                                }
                                            }
                                        }

                                        if($subscalesTNReached[$teamleaderGroupId][$subscale] == true){
                                            $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['subscale_mean'] = round($sumMeansGroup[$teamleaderGroupId][$subscale]/$subscalesItemsCount[$subscale], 1);
                                            
                                            if($mode[$formid] == "+-"){
                                                if(round($sumMeansGroup[$teamleaderGroupId][$subscale]/$subscalesItemsCount[$subscale], 1)<= 2.3){
                                                    $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['val_color'] = "bfe2ca";
                                                }
                                                else if(round($sumMeansGroup[$teamleaderGroupId][$subscale]/$subscalesItemsCount[$subscale], 1)>= 3.7){
                                                    $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['val_color'] = "f4858e";
                                                }
                                                else{
                                                    $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['val_color'] = "fed88f";
                                                }
                                            }
                                            else if($mode[$formid] == "-+"){
                                                if(round($sumMeansGroup[$teamleaderGroupId][$subscale]/$subscalesItemsCount[$subscale], 1)<= 2.3){
                                                    $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['val_color'] = "f4858e";
                                                }
                                                else if(round($sumMeansGroup[$teamleaderGroupId][$subscale]/$subscalesItemsCount[$subscale], 1)>= 3.7){
                                                    $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['val_color'] = "bfe2ca";
                                                }
                                                else{
                                                    $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'][$subscale]['val_color'] = "fed88f";
                                                }
                                            }

                                            $sumSubscalesGroup += round($sumMeansGroup[$teamleaderGroupId][$subscale]/$subscalesItemsCount[$subscale], 1);
                                        }
                                        else{
                                            $scaleTNReached = false;
                                        }
                                    }

                                    $tableTeamleader['scale_table']['scales'][$scaleThisForm]['scale_mean'] = "-";
                                    $tableTeamleader['scale_table']['scales'][$scaleThisForm]['val_color'] = "ffffff";

                                    // get the max/min input count for the current group - scale level
                                    $tableTeamleader['scale_table']['scales'][$scaleThisForm]['scale_input_count_min'] = null;
                                    $tableTeamleader['scale_table']['scales'][$scaleThisForm]['scale_input_count_max'] = null;
                                    $scaleSubscales = $tableTeamleader['subscale_table']['scales'][$scaleThisForm]['subscales'];
                                    foreach($scaleSubscales as $scaleSubscale){
                                        if(isset($scaleSubscale['subscale_input_count_min'])){
                                            if(is_null($tableTeamleader['scale_table']['scales'][$scaleThisForm]['scale_input_count_min'])){
                                                $tableTeamleader['scale_table']['scales'][$scaleThisForm]['scale_input_count_min'] = $scaleSubscale['subscale_input_count_min'];
                                            }
                                            else{
                                                if($tableTeamleader['scale_table']['scales'][$scaleThisForm]['scale_input_count_min'] > $scaleSubscale['subscale_input_count_min']){
                                                    $tableTeamleader['scale_table']['scales'][$scaleThisForm]['scale_input_count_min'] = $scaleSubscale['subscale_input_count_min'];
                                                }
                                            }
                                        }

                                        if(isset($scaleSubscale['subscale_input_count_max'])){
                                            if(is_null($tableTeamleader['scale_table']['scales'][$scaleThisForm]['scale_input_count_max'])){
                                                $tableTeamleader['scale_table']['scales'][$scaleThisForm]['scale_input_count_max'] = $scaleSubscale['subscale_input_count_max'];
                                            }
                                            else{
                                                if($tableTeamleader['scale_table']['scales'][$scaleThisForm]['scale_input_count_max'] < $scaleSubscale['subscale_input_count_max']){
                                                    $tableTeamleader['scale_table']['scales'][$scaleThisForm]['scale_input_count_max'] = $scaleSubscale['subscale_input_count_max'];
                                                }
                                            }
                                        }
                                    }

                                    if($scaleTNReached){
                                        $tableTeamleader['scale_table']['scales'][$scaleThisForm]['scale_mean'] = round($sumSubscalesGroup/sizeof($subscales),1);

                                        if($mode[$formid] == "+-"){
                                            if(round($sumSubscalesGroup/sizeof($subscales),1)<= 2.3){
                                                $tableTeamleader['scale_table']['scales'][$scaleThisForm]['val_color'] = "bfe2ca";
                                            }
                                            else if(round($sumSubscalesGroup/sizeof($subscales),1)>= 3.7){
                                                $tableTeamleader['scale_table']['scales'][$scaleThisForm]['val_color'] = "f4858e";
                                            }
                                            else{
                                                $tableTeamleader['scale_table']['scales'][$scaleThisForm]['val_color'] = "fed88f";
                                            }
                                        }
                                        else if($mode[$formid] == "-+"){
                                            if(round($sumSubscalesGroup/sizeof($subscales),1)<= 2.3){
                                                $tableTeamleader['scale_table']['scales'][$scaleThisForm]['val_color'] = "f4858e";
                                            }
                                            else if(round($sumSubscalesGroup/sizeof($subscales),1)>= 3.7){
                                                $tableTeamleader['scale_table']['scales'][$scaleThisForm]['val_color'] = "bfe2ca";
                                            }
                                            else{
                                                $tableTeamleader['scale_table']['scales'][$scaleThisForm]['val_color'] = "fed88f";
                                            }
                                        }
                                    }

                                }
                            }
                        }
                    }
                }

                $outputId = "";
                for($i=0; $i < count($ids); $i++){
                    if($i != 0){
                        $outputId = $outputId."_";
                    }
                    $outputId = $outputId.$ids[$i];
                }

                $showScales = false;
                $showSubscales = false;
                $showItems = false;

                foreach($showTables as $showTable){

                    if($showTable == "all"){
                        $showScales = true;
                        $showSubscales = true;
                        $showItems = true;
                    }
                    else if($showTable == "scales"){
                        $showScales = true;
                    }
                    else if($showTable == "subscales"){
                        $showSubscales = true;
                    }
                    else if($showTable == "items"){
                        $showItems = true;
                    }
                }

                if($showScales || $showSubscales || $showItems){
                    return $twig->render("company/company-gbu-mittelwerte.html", [
                        "isKAdmin" => $isKAdmin,
                        "isBoss" => $isBoss,
                        "isTeamleader" => $isTeamleader,
                        "tableKAdmin" => $tableKAdmin,
                        "tableBoss" => $tableBoss,
                        "tableTeamleader" => $tableTeamleader,
                        "showScales" => $showScales,
                        "showSubscales" => $showSubscales,
                        "showItems" => $showItems,
                        "outputId" => $outputId,
                        "MINTEILNEHMER" => self::MINTEILNEHMER,
                        "showPDFDownload" => $showPDFDownload,
                        "pdfDownloadTitle" => $pdfDownloadTitle
                    ]);
                }
                else{
                    return $twig->render("company/company-gbu-mittelwerte-error.html");
                }
                
            }
            else{
                return $twig->render("company/company-gbu-mittelwerte-error.html");
            }
        }
        else{
            return $twig->render("company/company-gbu-mittelwerte-error.html");
        }
    }
    // ENDE: Mittelwerte Skalen, Subskalen, Items

    // ANFANG: Mittelwert Gesamt
    public function ts_forms_mittelwert_gesamt($ids, $groupbygroups, $poszuneg) {
        $uid = $this::getUserid(); // User-ID
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if(is_array($ids))
        {
            if($ids != null && sizeof($ids) > 0)
            {
                // Id für Ausgabe-Element für PDF
                $printId = "";
                for($pId = 0; $pId < sizeof($ids); $pId++){

                    if($pId != 0){
                        $printId = $printId."_";
                    }
                    $printId = $printId.$ids[$pId];
                }

                if(!$groupbygroups) 
                {
                    $users = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getUsersByBossId($uid);
                    $table = array();

                    $anzahl['trifft_nicht_zu'] = 0;
                    $anzahl['trifft_wenig_zu'] = 0;
                    $anzahl['trifft_teilweise_zu'] = 0;
                    $anzahl['trifft_überwiegend_zu'] = 0;
                    $anzahl['trifft_völlig_zu'] = 0;
                    $counter = 0;
                    
                    if(sizeof($users) > 0) 
                    {
                        foreach($ids as $formid) 
                        {
                            $fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($formid);

                            foreach ($fields as $field) {

                                if($field->getType() == "matrix") { // Matrix

                                    $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);
    
                                    foreach($field->getAttributesJsonDecoded()['questions'] as $q_key => $q) {
                                        $field_id = $field->getFieldId() . $q_key;
                                        $counter++;

                                        foreach ($data as $eingabe) {
                
                                            if($eingabe != null && $eingabe->dataIsArray() && isset($eingabe->getDataJsonDecoded()[$q_key]) && is_numeric($eingabe->getDataJsonDecoded()[$q_key])) {
                                        
                                                if ($eingabe->getDataJsonDecoded()[$q_key] == 1) {
                                                    $anzahl['trifft_nicht_zu']++;
                                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 2) {
                                                    $anzahl['trifft_wenig_zu']++;
                                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 3) {
                                                    $anzahl['trifft_teilweise_zu']++;
                                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 4) {
                                                    $anzahl['trifft_überwiegend_zu']++;
                                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 5) {
                                                    $anzahl['trifft_völlig_zu']++;
                                                }
                                            }
                
                                        }
                                    }

                                } else {
                                    $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);
                                    $field_id = $field->getFieldId();
                                    
                                    $counter++;

                                    foreach ($data as $eingabe) {
                                        if ($eingabe->getData() == 1) {
                                            $anzahl['trifft_nicht_zu']++;
                                        } else if ($eingabe->getData() == 2) {
                                            $anzahl['trifft_wenig_zu']++;
                                        } else if ($eingabe->getData() == 3) {
                                            $anzahl['trifft_teilweise_zu']++;
                                        } else if ($eingabe->getData() == 4) {
                                            $anzahl['trifft_überwiegend_zu']++;
                                        } else if ($eingabe->getData() == 5) {
                                            $anzahl['trifft_völlig_zu']++;
                                        }
                                    }
                                }
                            }
                        }
                        
                        $anzahl_gesamt = $anzahl['trifft_nicht_zu'] + $anzahl['trifft_wenig_zu'] + $anzahl['trifft_teilweise_zu'] + $anzahl['trifft_überwiegend_zu'] + $anzahl['trifft_völlig_zu'];
                        $mittelwert = 0;
                        if($anzahl_gesamt > self::MINTEILNEHMER*$counter && $anzahl_gesamt != 0)
                        {
                            $haeufigkeiten = $anzahl['trifft_nicht_zu']*1 + $anzahl['trifft_wenig_zu']*2 + $anzahl['trifft_teilweise_zu']*3 + $anzahl['trifft_überwiegend_zu']*4 + $anzahl['trifft_völlig_zu']*5;
                            $mittelwert = round($haeufigkeiten/$anzahl_gesamt, 1);
                        }

                        if($poszuneg) {
                            if ($mittelwert == 0) {
                                $table[0]['bgcolor'] = "ffffff";
                                $table[0]['value'] = $this::$toolesswarning;
                            } else if ($mittelwert <= 2.3) {
                                $table[0]['bgcolor'] = "bfe2ca";
                                $table[0]['value'] = number_format($mittelwert, 1, ',', '');
                            } else if ($mittelwert >= 3.7) {
                                $table[0]['bgcolor'] = "f4858e";
                                $table[0]['value'] = number_format($mittelwert, 1, ',', '');
                            } else {
                                $table[0]['bgcolor'] = "fed88f";
                                $table[0]['value'] = number_format($mittelwert, 1, ',', '');
                            }
                        }
                        else
                        {
                            if ($mittelwert == 0) {
                                $table[0]['bgcolor'] = "ffffff";
                                $table[0]['value'] = $this::$toolesswarning;
                            } else if ($mittelwert <= 2.3) {
                                $table[0]['bgcolor'] = "f4858e";
                                $table[0]['value'] = number_format($mittelwert, 1, ',', '');
                            } else if ($mittelwert >= 3.7) {
                                $table[0]['bgcolor'] = "bfe2ca";
                                $table[0]['value'] = number_format($mittelwert, 1, ',', '');
                            } else {
                                $table[0]['bgcolor'] = "fed88f";
                                $table[0]['value'] = number_format($mittelwert, 1, ',', '');
                            }
                        }

                        return $twig->render("company/company-table-gesamt.html", ["table" => $table, "id" => $printId]);
                    }
                    else 
                    {
                        return $twig->render("company/company-noboss.html", ["id" => $printId]);
                    }
                }
                else
                {
                    $groups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroupsByBossId($uid);
                    
                    if(sizeof($groups) > 0) 
                    {
                        foreach($groups as $groupid => $group) 
                        {
                            $users = $group['users'];
                            $table = array();

                            $anzahl[$groupid]['trifft_nicht_zu'] = 0;
                            $anzahl[$groupid]['trifft_wenig_zu'] = 0;
                            $anzahl[$groupid]['trifft_teilweise_zu'] = 0;
                            $anzahl[$groupid]['trifft_überwiegend_zu'] = 0;
                            $anzahl[$groupid]['trifft_völlig_zu'] = 0;
                            $counter[$groupid] = 0;

                            foreach($ids as $formid)
                            {
                                $fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($formid);

                                foreach ($fields as $field) {

                                    if($field->getType() == "matrix") { // Matrix

                                        $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);
        
                                        foreach($field->getAttributesJsonDecoded()['questions'] as $q_key => $q) {
                                            $field_id = $field->getFieldId() . $q_key;
                                            $counter[$groupid]++;
                                            
                                            foreach ($data as $eingabe) {
                    
                                                if($eingabe != null && $eingabe->dataIsArray() && isset($eingabe->getDataJsonDecoded()[$q_key]) && is_numeric($eingabe->getDataJsonDecoded()[$q_key])) {
                                            
                                                    if ($eingabe->getDataJsonDecoded()[$q_key] == 1) {
                                                        $anzahl[$groupid]['trifft_nicht_zu']++;
                                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 2) {
                                                        $anzahl[$groupid]['trifft_wenig_zu']++;
                                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 3) {
                                                        $anzahl[$groupid]['trifft_teilweise_zu']++;
                                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 4) {
                                                        $anzahl[$groupid]['trifft_überwiegend_zu']++;
                                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 5) {
                                                        $anzahl[$groupid]['trifft_völlig_zu']++;
                                                    }
                                                }
                    
                                            }
                                        }

                                    } else {
                                        
                                        $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);
                                        $field_id = $field->getFieldId();
                                        
                                        $counter[$groupid]++;

                                        foreach ($data as $eingabe) {
                                            if ($eingabe->getData() == 1) {
                                                $anzahl[$groupid]['trifft_nicht_zu']++;
                                            } else if ($eingabe->getData() == 2) {
                                                $anzahl[$groupid]['trifft_wenig_zu']++;
                                            } else if ($eingabe->getData() == 3) {
                                                $anzahl[$groupid]['trifft_teilweise_zu']++;
                                            } else if ($eingabe->getData() == 4) {
                                                $anzahl[$groupid]['trifft_überwiegend_zu']++;
                                            } else if ($eingabe->getData() == 5) {
                                                $anzahl[$groupid]['trifft_völlig_zu']++;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        foreach($groups as $groupid => $group)
                        {
                            $anzahl_gesamt = $anzahl[$groupid]['trifft_nicht_zu'] + $anzahl[$groupid]['trifft_wenig_zu'] + $anzahl[$groupid]['trifft_teilweise_zu'] + $anzahl[$groupid]['trifft_überwiegend_zu'] + $anzahl[$groupid]['trifft_völlig_zu'];
                            $mittelwert = 0;
                            if($anzahl_gesamt > self::MINTEILNEHMER*$counter[$groupid] && $anzahl_gesamt != 0)
                            {
                                $haeufigkeiten = $anzahl[$groupid]['trifft_nicht_zu']*1 + $anzahl[$groupid]['trifft_wenig_zu']*2 + $anzahl[$groupid]['trifft_teilweise_zu']*3 + $anzahl[$groupid]['trifft_überwiegend_zu']*4 + $anzahl[$groupid]['trifft_völlig_zu']*5;
                                $mittelwert = round($haeufigkeiten/$anzahl_gesamt, 1);
                            }

                            $table[$groupid]['groupname'] = $group['name'];

                            if($poszuneg) {
                                if ($mittelwert == 0) {
                                    $table[$groupid]['bgcolor'] = "ffffff";
                                    $table[$groupid]['value'] = $this::$toolesswarning;
                                } else if ($mittelwert <= 2.3) {
                                    $table[$groupid]['bgcolor'] = "bfe2ca";
                                    $table[$groupid]['value'] = number_format($mittelwert, 1, ',', '');
                                } else if ($mittelwert >= 3.7) {
                                    $table[$groupid]['bgcolor'] = "f4858e";
                                    $table[$groupid]['value'] = number_format($mittelwert, 1, ',', '');
                                } else {
                                    $table[$groupid]['bgcolor'] = "fed88f";
                                    $table[$groupid]['value'] = number_format($mittelwert, 1, ',', '');
                                }
                            }
                            else
                            {
                                if ($mittelwert == 0) {
                                    $table[$groupid]['bgcolor'] = "ffffff";
                                    $table[$groupid]['value'] = $this::$toolesswarning;
                                } else if ($mittelwert <= 2.3) {
                                    $table[$groupid]['bgcolor'] = "f4858e";
                                    $table[$groupid]['value'] = number_format($mittelwert, 1, ',', '');
                                } else if ($mittelwert >= 3.7) {
                                    $table[$groupid]['bgcolor'] = "bfe2ca";
                                    $table[$groupid]['value'] = number_format($mittelwert, 1, ',', '');
                                } else {
                                    $table[$groupid]['bgcolor'] = "fed88f";
                                    $table[$groupid]['value'] = number_format($mittelwert, 1, ',', '');
                                }
                            }
                        }
                        return $twig->render("company/company-table-gesamt.html", ["table" => $table, "id" => $printId]);
                    }
                    else 
                    {
                        return $twig->render("company/company-noboss.html", ["id" => $printId]);
                    }
                }
            }
        }
    }
    // ENDE: Mittelwert Gesamt

    // ANFANG: CSV Download
    public function ts_forms_csv_download($data, $singleuser, $groupbygroups) {
        $uid = $this::getUserid(); // User-ID
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
        
        if($data != null) {
            $table = array();
            $mode = "";
            
            if($singleuser) 
            {
                $groupbygroups = false;
                $mode = "singleuser";

                foreach($data as $topic => $subtopicarray) 
                {
                    foreach($subtopicarray as $subtopic => $formid)
                    {
                        $fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getUserFormfieldsByForm($formid, $uid);

                        foreach ($fields as $formgroup) {

                            foreach($formgroup as $field) {

                                if($field->getType() == "matrix") { // Matrix

                                    $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);
        
                                    foreach($field->getAttributesJsonDecoded()['questions'] as $q_key => $q) {
                                        $field_id = $field->getFieldId() . $q_key;
                                        $table[$field_id]['topic'] = $topic;
                                        $table[$field_id]['subtopic'] = $subtopic;
                                        $table[$field_id]['label'] = $q['question'];

                                        $table[$field_id]['trifft_nicht_zu'] = 0;
                                        $table[$field_id]['trifft_wenig_zu'] = 0;
                                        $table[$field_id]['trifft_teilweise_zu'] = 0;
                                        $table[$field_id]['trifft_überwiegend_zu'] = 0;
                                        $table[$field_id]['trifft_völlig_zu'] = 0;
                                        
                                        foreach ($data as $eingabe) {
                
                                            if($eingabe != null && $eingabe->dataIsArray() && isset($eingabe->getDataJsonDecoded()[$q_key]) && is_numeric($eingabe->getDataJsonDecoded()[$q_key])) {
                                        
                                                if ($eingabe->getDataJsonDecoded()[$q_key] == 1) {
                                                    $table[$field_id]['trifft_nicht_zu']++;
                                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 2) {
                                                    $table[$field_id]['trifft_wenig_zu']++;
                                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 3) {
                                                    $table[$field_id]['trifft_teilweise_zu']++;
                                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 4) {
                                                    $table[$field_id]['trifft_überwiegend_zu']++;
                                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 5) {
                                                    $table[$field_id]['trifft_völlig_zu']++;
                                                }
                                            }
                
                                        }
                                    }

                                } else {

                                    $field_id = $field->getFieldId();
                                    $table[$field_id]['topic'] = $topic;
                                    $table[$field_id]['subtopic'] = $subtopic;
                                    if(isset($field->getAttributesJsonDecoded()['title'])) {
                                        $table[$field_id]['label'] = $field->getAttributesJsonDecoded()['title'];
                                    } else {
                                        $table[$field_id]['label'] = "";
                                    }
                                    $table[$field_id]['trifft_nicht_zu'] = 0;
                                    $table[$field_id]['trifft_wenig_zu'] = 0;
                                    $table[$field_id]['trifft_teilweise_zu'] = 0;
                                    $table[$field_id]['trifft_überwiegend_zu'] = 0;
                                    $table[$field_id]['trifft_völlig_zu'] = 0;
                                    
                                    
                                    if ($field->getFormdata() != null && is_numeric($field->getFormdata()->getData())) {
                                        if ($field->getFormdata()->getData() == 1) {
                                            $table[$field_id]['trifft_nicht_zu'] = 1;
                                        } else if ($field->getFormdata()->getData() == 2) {
                                            $table[$field_id]['trifft_wenig_zu'] = 1;
                                        } else if ($field->getFormdata()->getData() == 3) {
                                            $table[$field_id]['trifft_teilweise_zu'] = 1;
                                        } else if ($field->getFormdata()->getData() == 4) {
                                            $table[$field_id]['trifft_überwiegend_zu'] = 1;
                                        } else if ($field->getFormdata()->getData() == 5) {
                                            $table[$field_id]['trifft_völlig_zu'] = 1;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } 
            else if($groupbygroups)
            {
                $groups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroupsByBossId($uid);
                $mode = "groupbygroups";
                
                if(sizeof($groups) > 0)
                {
                    $topicid = 0;
                    foreach($data as $topic => $subtopicarray) 
                    {
                        $subtopicid=0;
                        foreach($subtopicarray as $subtopic => $formid)
                        {
                            foreach($groups as $groupid => $group) 
                            {
                                $users = $group['users'];

                                $fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($formid);
                                $fieldindex = 0;

                                foreach ($fields as $field) {
                                    $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);
                                    $field_id = $field->getFieldId();

                                    if($field->getType() == "matrix") { // Matrix

                                        foreach($field->getAttributesJsonDecoded()['questions'] as $q_key => $q) {

                                            $arrayindex = $topicid . '-' . $subtopicid . '-' . $fieldindex . '-' . $groupid . '-' . $field_id . '-' . $q_key;

                                            $table[$arrayindex]['topic'] = $topic;
                                            $table[$arrayindex]['subtopic'] = $subtopic;
                                            $table[$arrayindex]['label'] = $q['question'];
                                            $table[$arrayindex]['group'] = $group['name'];

                                            $table[$arrayindex]['trifft_nicht_zu'] = 0;
                                            $table[$arrayindex]['trifft_wenig_zu'] = 0;
                                            $table[$arrayindex]['trifft_teilweise_zu'] = 0;
                                            $table[$arrayindex]['trifft_überwiegend_zu'] = 0;
                                            $table[$arrayindex]['trifft_völlig_zu'] = 0;
                                            $table[$arrayindex]['gesamt'] = 0;
                                            $table[$arrayindex]['mittelwert'] = '0,0';
                                            $table[$arrayindex]['mittelwert_subtopic'] = '0,0';
                                            $table[$arrayindex]['mittelwert_topic'] = '0,0';
    
                                            foreach ($data as $eingabe) {

                                                if($eingabe != null && $eingabe->dataIsArray() && isset($eingabe->getDataJsonDecoded()[$q_key]) && is_numeric($eingabe->getDataJsonDecoded()[$q_key])) {
                                        
                                                    if ($eingabe->getDataJsonDecoded()[$q_key] == 1) {
                                                        $table[$arrayindex]['trifft_nicht_zu']++;
                                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 2) {
                                                        $table[$arrayindex]['trifft_wenig_zu']++;
                                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 3) {
                                                        $table[$arrayindex]['trifft_teilweise_zu']++;
                                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 4) {
                                                        $table[$arrayindex]['trifft_überwiegend_zu']++;
                                                    } else if ($eingabe->getDataJsonDecoded()[$q_key] == 5) {
                                                        $table[$arrayindex]['trifft_völlig_zu']++;
                                                    }
                                                }
                                            }

                                            // Ausgabe
                                            $anzahl_zeile = $table[$arrayindex]['trifft_nicht_zu']+$table[$arrayindex]['trifft_wenig_zu']+$table[$arrayindex]['trifft_teilweise_zu']+$table[$arrayindex]['trifft_überwiegend_zu']+$table[$arrayindex]['trifft_völlig_zu'];
                                            $table[$arrayindex]['gesamt'] = $anzahl_zeile;
                                            // Mindestanzahl erreicht
                                            if ($anzahl_zeile < self::MINTEILNEHMER) {
                                                $table[$arrayindex]['trifft_nicht_zu'] = 0;
                                                $table[$arrayindex]['trifft_wenig_zu'] = 0;
                                                $table[$arrayindex]['trifft_teilweise_zu'] = 0;
                                                $table[$arrayindex]['trifft_überwiegend_zu'] = 0;
                                                $table[$arrayindex]['trifft_völlig_zu'] = 0;
                                                $table[$arrayindex]['gesamt'] = 0;
                                            }
                                            else
                                            {
                                                $table[$arrayindex]['mittelwert'] = number_format((($table[$arrayindex]['trifft_nicht_zu']*1 + $table[$arrayindex]['trifft_wenig_zu']*2 + $table[$arrayindex]['trifft_teilweise_zu']*3 + $table[$arrayindex]['trifft_überwiegend_zu']*4 + $table[$arrayindex]['trifft_völlig_zu']*5)/$table[$arrayindex]['gesamt']), 5, ',', '');
                                            }
                                        }

                                    } else {

                                        $arrayindex = $topicid . '-' . $subtopicid . '-' . $fieldindex . '-' . $groupid . '-' . $field_id;

                                        $table[$arrayindex]['topic'] = $topic;
                                        $table[$arrayindex]['subtopic'] = $subtopic;
                                        if(isset($field->getAttributesJsonDecoded()['title'])) {
                                            $table[$arrayindex]['label'] = $field->getAttributesJsonDecoded()['title'];
                                        } else {
                                            $table[$arrayindex]['label'] = "";
                                        }
                                        $table[$arrayindex]['group'] = $group['name'];
                                        $table[$arrayindex]['trifft_nicht_zu'] = 0;
                                        $table[$arrayindex]['trifft_wenig_zu'] = 0;
                                        $table[$arrayindex]['trifft_teilweise_zu'] = 0;
                                        $table[$arrayindex]['trifft_überwiegend_zu'] = 0;
                                        $table[$arrayindex]['trifft_völlig_zu'] = 0;
                                        $table[$arrayindex]['gesamt'] = 0;
                                        $table[$arrayindex]['mittelwert'] = '0,0';
                                        $table[$arrayindex]['mittelwert_subtopic'] = '0,0';
                                        $table[$arrayindex]['mittelwert_topic'] = '0,0';

                                        foreach ($data as $eingabe) {
                                            if ($eingabe->getData() == 1) {
                                                $table[$arrayindex]['trifft_nicht_zu']++;
                                            } else if ($eingabe->getData() == 2) {
                                                $table[$arrayindex]['trifft_wenig_zu']++;
                                            } else if ($eingabe->getData() == 3) {
                                                $table[$arrayindex]['trifft_teilweise_zu']++;
                                            } else if ($eingabe->getData() == 4) {
                                                $table[$arrayindex]['trifft_überwiegend_zu']++;
                                            } else if ($eingabe->getData() == 5) {
                                                $table[$arrayindex]['trifft_völlig_zu']++;
                                            }
                                        }
                                    

                                        // Ausgabe
                                        $anzahl_zeile = $table[$arrayindex]['trifft_nicht_zu']+$table[$arrayindex]['trifft_wenig_zu']+$table[$arrayindex]['trifft_teilweise_zu']+$table[$arrayindex]['trifft_überwiegend_zu']+$table[$arrayindex]['trifft_völlig_zu'];
                                        $table[$arrayindex]['gesamt'] = $anzahl_zeile;
                                        // Mindestanzahl erreicht
                                        if ($anzahl_zeile < self::MINTEILNEHMER) {
                                            $table[$arrayindex]['trifft_nicht_zu'] = 0;
                                            $table[$arrayindex]['trifft_wenig_zu'] = 0;
                                            $table[$arrayindex]['trifft_teilweise_zu'] = 0;
                                            $table[$arrayindex]['trifft_überwiegend_zu'] = 0;
                                            $table[$arrayindex]['trifft_völlig_zu'] = 0;
                                            $table[$arrayindex]['gesamt'] = 0;
                                        }
                                        else
                                        {
                                            $table[$arrayindex]['mittelwert'] = number_format((($table[$arrayindex]['trifft_nicht_zu']*1 + $table[$arrayindex]['trifft_wenig_zu']*2 + $table[$arrayindex]['trifft_teilweise_zu']*3 + $table[$arrayindex]['trifft_überwiegend_zu']*4 + $table[$arrayindex]['trifft_völlig_zu']*5)/$table[$arrayindex]['gesamt']), 5, ',', '');
                                        }
                                    }
                                    $fieldindex++;
                                }
                            }
                            $subtopicid++;
                        }
                        $topicid++;
                    }
                    ksort($table);

                    // Mittelwerte berechnen
                    $mittelwerte_raw = array();
                    foreach($table as $row)
                    {
                        if($row['gesamt'] > 0) 
                        {
                            $mittelwerte_raw[$row['topic']][$row['subtopic']][$row['group']][] = (($row['trifft_nicht_zu']*1+$row['trifft_wenig_zu']*2+$row['trifft_teilweise_zu']*3+$row['trifft_überwiegend_zu']*4+$row['trifft_völlig_zu']*5)/$row['gesamt']);
                        }
                    }
                    
                    $mittelwerte = array();
                    foreach($mittelwerte_raw as $topic => $subtopicarray)
                    {
                        foreach($subtopicarray as $subtopic => $groups)
                        {
                            foreach($groups as $groupname => $values)
                            {
                                $summe = 0;
                                foreach($values as $value) {
                                    $summe += $value;
                                }
                                $mittelwerte[$subtopic][$groupname] = number_format(round($summe/sizeof($values), 5), 5, ',', '');
                            }
                        }
                    }

                    $mittelwerte_topic_raw = array();
                    foreach($table as $row)
                    {
                        $mittelwerte_topic_raw[$row['topic']]['trifft_nicht_zu'] = 0;
                        $mittelwerte_topic_raw[$row['topic']]['trifft_wenig_zu'] = 0;
                        $mittelwerte_topic_raw[$row['topic']]['trifft_teilweise_zu'] = 0;
                        $mittelwerte_topic_raw[$row['topic']]['trifft_überwiegend_zu'] = 0;
                        $mittelwerte_topic_raw[$row['topic']]['trifft_völlig_zu'] = 0;
                        $mittelwerte_topic_raw[$row['topic']]['gesamt'] = 0;
                    }
                    foreach($table as $row)
                    {
                        $mittelwerte_topic_raw[$row['topic']][$row['group']]['trifft_nicht_zu'] += $row['trifft_nicht_zu'];
                        $mittelwerte_topic_raw[$row['topic']][$row['group']]['trifft_wenig_zu'] += $row['trifft_wenig_zu'];
                        $mittelwerte_topic_raw[$row['topic']][$row['group']]['trifft_teilweise_zu'] += $row['trifft_teilweise_zu'];
                        $mittelwerte_topic_raw[$row['topic']][$row['group']]['trifft_überwiegend_zu'] += $row['trifft_überwiegend_zu'];
                        $mittelwerte_topic_raw[$row['topic']][$row['group']]['trifft_völlig_zu'] += $row['trifft_völlig_zu'];
                        $mittelwerte_topic_raw[$row['topic']][$row['group']]['gesamt'] += $row['gesamt'];
                    }

                    $mittelwerte_topic = array();
                    foreach($mittelwerte_topic_raw as $topic => $grouparray)
                    {
                        foreach($grouparray as $groupname => $values)
                        {
                            if($values['gesamt'] > 0) 
                                $mittelwerte_topic[$topic][$groupname] = number_format((($values['trifft_nicht_zu']*1 + $values['trifft_wenig_zu']*2 + $values['trifft_teilweise_zu']*3 + $values['trifft_überwiegend_zu']*4 + $values['trifft_völlig_zu']*5)/$values['gesamt']), 5, ',', '');
                        }
                    }

                    foreach($table as $arrayindex => $row)
                    {
                        if(isset($mittelwerte[$row['subtopic']][$row['group']]) && $row['gesamt'] > 0) {
                            $table[$arrayindex]['mittelwert_subtopic'] = $mittelwerte[$row['subtopic']][$row['group']];
                        }
                        if(isset($mittelwerte_topic[$row['topic']][$row['group']]) && $row['gesamt'] > 0) {
                            $table[$arrayindex]['mittelwert_topic'] = $mittelwerte_topic[$row['topic']][$row['group']];
                        }
                    }
                }
            }
            else
            {
                $users = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getUsersByBossId($uid);
                $mode = "default";
                
                if(sizeof($users) > 0)
                {
                    $topicid = 0;
                    foreach($data as $topic => $subtopicarray) 
                    {
                        $subtopicid=0;
                        foreach($subtopicarray as $subtopic => $formid)
                        {        
                            $fields = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($formid);
                            $fieldindex = 0;

                            foreach ($fields as $field) {

                                $data = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormfieldDataMultiUser($field->getFieldId(), $users);

                                if($field->getType() == "matrix") { // Matrix

                                    foreach($field->getAttributesJsonDecoded()['questions'] as $q_key => $q) {

                                        $arrayindex = $topicid . '-' . $subtopicid . '-' . $fieldindex . '-' . $field_id . '-' . $q_key;

                                        $table[$arrayindex]['topic'] = $topic;
                                        $table[$arrayindex]['subtopic'] = $subtopic;
                                        $table[$arrayindex]['label'] = $q['question'];
                                        $table[$arrayindex]['group'] = $group['name'];

                                        $table[$arrayindex]['trifft_nicht_zu'] = 0;
                                        $table[$arrayindex]['trifft_wenig_zu'] = 0;
                                        $table[$arrayindex]['trifft_teilweise_zu'] = 0;
                                        $table[$arrayindex]['trifft_überwiegend_zu'] = 0;
                                        $table[$arrayindex]['trifft_völlig_zu'] = 0;
                                        $table[$arrayindex]['gesamt'] = 0;
                                        $table[$arrayindex]['mittelwert'] = '0,0';
                                        $table[$arrayindex]['mittelwert_subtopic'] = '0,0';
                                        $table[$arrayindex]['mittelwert_topic'] = '0,0';

                                        foreach ($data as $eingabe) {

                                            if($eingabe != null && $eingabe->dataIsArray() && isset($eingabe->getDataJsonDecoded()[$q_key]) && is_numeric($eingabe->getDataJsonDecoded()[$q_key])) {
                                    
                                                if ($eingabe->getDataJsonDecoded()[$q_key] == 1) {
                                                    $table[$arrayindex]['trifft_nicht_zu']++;
                                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 2) {
                                                    $table[$arrayindex]['trifft_wenig_zu']++;
                                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 3) {
                                                    $table[$arrayindex]['trifft_teilweise_zu']++;
                                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 4) {
                                                    $table[$arrayindex]['trifft_überwiegend_zu']++;
                                                } else if ($eingabe->getDataJsonDecoded()[$q_key] == 5) {
                                                    $table[$arrayindex]['trifft_völlig_zu']++;
                                                }
                                            }
                                        }

                                        // Ausgabe
                                        $anzahl_zeile = $table[$arrayindex]['trifft_nicht_zu']+$table[$arrayindex]['trifft_wenig_zu']+$table[$arrayindex]['trifft_teilweise_zu']+$table[$arrayindex]['trifft_überwiegend_zu']+$table[$arrayindex]['trifft_völlig_zu'];
                                        $table[$arrayindex]['gesamt'] = $anzahl_zeile;
                                        // Mindestanzahl erreicht
                                        if ($anzahl_zeile < self::MINTEILNEHMER) {
                                            $table[$arrayindex]['trifft_nicht_zu'] = 0;
                                            $table[$arrayindex]['trifft_wenig_zu'] = 0;
                                            $table[$arrayindex]['trifft_teilweise_zu'] = 0;
                                            $table[$arrayindex]['trifft_überwiegend_zu'] = 0;
                                            $table[$arrayindex]['trifft_völlig_zu'] = 0;
                                            $table[$arrayindex]['gesamt'] = 0;
                                        }
                                        else
                                        {
                                            $table[$arrayindex]['mittelwert'] = number_format((($table[$arrayindex]['trifft_nicht_zu']*1 + $table[$arrayindex]['trifft_wenig_zu']*2 + $table[$arrayindex]['trifft_teilweise_zu']*3 + $table[$arrayindex]['trifft_überwiegend_zu']*4 + $table[$arrayindex]['trifft_völlig_zu']*5)/$table[$arrayindex]['gesamt']), 5, ',', '');
                                        }
                                    }

                                } else {
                                
                                    $field_id = $field->getFieldId();
                                    
                                    $arrayindex = $topicid . '-' . $subtopicid . '-' . $fieldindex . '-' . $field_id;

                                    $table[$arrayindex]['topic'] = $topic;
                                    $table[$arrayindex]['subtopic'] = $subtopic;
                                    if(isset($field->getAttributesJsonDecoded()['title'])) {
                                        $table[$arrayindex]['label'] = $field->getAttributesJsonDecoded()['title'];
                                    } else {
                                        $table[$arrayindex]['label'] = "";
                                    }
                                    $table[$arrayindex]['trifft_nicht_zu'] = 0;
                                    $table[$arrayindex]['trifft_wenig_zu'] = 0;
                                    $table[$arrayindex]['trifft_teilweise_zu'] = 0;
                                    $table[$arrayindex]['trifft_überwiegend_zu'] = 0;
                                    $table[$arrayindex]['trifft_völlig_zu'] = 0;
                                    $table[$arrayindex]['gesamt'] = 0;
                                    $table[$arrayindex]['mittelwert'] = '0,0';
                                    $table[$arrayindex]['mittelwert_subtopic'] = '0,0';
                                    $table[$arrayindex]['mittelwert_topic'] = '0,0';

                                    foreach ($data as $eingabe) {
                                        if ($eingabe->getData() == 1) {
                                            $table[$arrayindex]['trifft_nicht_zu']++;
                                        } else if ($eingabe->getData() == 2) {
                                            $table[$arrayindex]['trifft_wenig_zu']++;
                                        } else if ($eingabe->getData() == 3) {
                                            $table[$arrayindex]['trifft_teilweise_zu']++;
                                        } else if ($eingabe->getData() == 4) {
                                            $table[$arrayindex]['trifft_überwiegend_zu']++;
                                        } else if ($eingabe->getData() == 5) {
                                            $table[$arrayindex]['trifft_völlig_zu']++;
                                        }
                                    }

                                    // Ausgabe
                                    $anzahl_zeile = $table[$arrayindex]['trifft_nicht_zu']+$table[$arrayindex]['trifft_wenig_zu']+$table[$arrayindex]['trifft_teilweise_zu']+$table[$arrayindex]['trifft_überwiegend_zu']+$table[$arrayindex]['trifft_völlig_zu'];
                                    $table[$arrayindex]['gesamt'] = $anzahl_zeile;
                                    // Mindestanzahl erreicht
                                    if ($anzahl_zeile < self::MINTEILNEHMER) {
                                        $table[$arrayindex]['trifft_nicht_zu'] = 0;
                                        $table[$arrayindex]['trifft_wenig_zu'] = 0;
                                        $table[$arrayindex]['trifft_teilweise_zu'] = 0;
                                        $table[$arrayindex]['trifft_überwiegend_zu'] = 0;
                                        $table[$arrayindex]['trifft_völlig_zu'] = 0;
                                        $table[$arrayindex]['gesamt'] = 0;
                                    }
                                    else
                                    {
                                        $table[$arrayindex]['mittelwert'] = number_format((($table[$arrayindex]['trifft_nicht_zu']*1 + $table[$arrayindex]['trifft_wenig_zu']*2 + $table[$arrayindex]['trifft_teilweise_zu']*3 + $table[$arrayindex]['trifft_überwiegend_zu']*4 + $table[$arrayindex]['trifft_völlig_zu']*5)/$table[$arrayindex]['gesamt']), 5, ',', '');
                                    }
                                }

                                $fieldindex++;
                            }
                            $subtopicid++;
                        }
                        $topicid++;
                    }
                    ksort($table);

                    // Mittelwerte berechnen
                    $mittelwerte_raw = array();
                    foreach($table as $row)
                    {
                        if($row['gesamt'] > 0)
                        {
                            $mittelwerte_raw[$row['topic']][$row['subtopic']][] = (($row['trifft_nicht_zu']*1+$row['trifft_wenig_zu']*2+$row['trifft_teilweise_zu']*3+$row['trifft_überwiegend_zu']*4+$row['trifft_völlig_zu']*5)/$row['gesamt']);  
                        }
                    }

                    $mittelwerte = array();
                    foreach($mittelwerte_raw as $topic => $topicarray)
                    {
                        foreach($topicarray as $subtopic => $values)
                        {
                            $summe = 0;
                            foreach($values as $value) {
                                $summe += $value;
                            }
                            $mittelwerte[$subtopic] = number_format(round($summe/sizeof($values), 5), 5, ',', '');
                        }
                    }

                    $mittelwerte_topic_raw = array();
                    foreach($table as $row)
                    {
                        $mittelwerte_topic_raw[$row['topic']]['trifft_nicht_zu'] = 0;
                        $mittelwerte_topic_raw[$row['topic']]['trifft_wenig_zu'] = 0;
                        $mittelwerte_topic_raw[$row['topic']]['trifft_teilweise_zu'] = 0;
                        $mittelwerte_topic_raw[$row['topic']]['trifft_überwiegend_zu'] = 0;
                        $mittelwerte_topic_raw[$row['topic']]['trifft_völlig_zu'] = 0;
                        $mittelwerte_topic_raw[$row['topic']]['gesamt'] = 0;
                    }
                    foreach($table as $row)
                    {
                        $mittelwerte_topic_raw[$row['topic']]['trifft_nicht_zu'] += $row['trifft_nicht_zu'];
                        $mittelwerte_topic_raw[$row['topic']]['trifft_wenig_zu'] += $row['trifft_wenig_zu'];
                        $mittelwerte_topic_raw[$row['topic']]['trifft_teilweise_zu'] += $row['trifft_teilweise_zu'];
                        $mittelwerte_topic_raw[$row['topic']]['trifft_überwiegend_zu'] += $row['trifft_überwiegend_zu'];
                        $mittelwerte_topic_raw[$row['topic']]['trifft_völlig_zu'] += $row['trifft_völlig_zu'];
                        $mittelwerte_topic_raw[$row['topic']]['gesamt'] += $row['gesamt'];
                    }
                    
                    $mittelwerte_topic = array();
                    foreach($mittelwerte_topic_raw as $topic => $values)
                    {
                        if($values['gesamt'] > 0)
                            $mittelwerte_topic[$topic] = number_format((($values['trifft_nicht_zu']*1 + $values['trifft_wenig_zu']*2 + $values['trifft_teilweise_zu']*3 + $values['trifft_überwiegend_zu']*4 + $values['trifft_völlig_zu']*5)/$values['gesamt']), 5, ',', '');
                    }

                    foreach($table as $arrayindex => $row)
                    {
                        if(isset($mittelwerte[$row['subtopic']])) {
                            $table[$arrayindex]['mittelwert_subtopic'] = $mittelwerte[$row['subtopic']];
                        }
                        if(isset($mittelwerte_topic[$row['topic']])) {
                            $table[$arrayindex]['mittelwert_topic'] = $mittelwerte_topic[$row['topic']];
                        }
                    }
                }
            }
            
            return $twig->render("company/csv-download.html", ["table" => $table, "sep" => ";", "mode" => $mode]);
        }
        return "0";
    }
    // ENDE: CSV Download

    /****************************************************
    HELPER
    ***************************************************/

    /**
    * Returns the user ID for the current user - either the selected user in the user mode or itself
    * 
    * @return User ID
    */
    public function getUserId(){
        $uid = get_current_user_id();
        $selectui = '' . get_user_meta(wp_get_current_user()->ID, 'coach_select_user', true);
        if ($selectui != '') {
            $uid = $selectui;
        }
        return $uid;
    }

    /**
    * Checks if a form ID is a TS Form
    *
    * @param formid Form ID
    * @return boolean true if TS Form, false if NF
    */
    private function isTsForm($formid) {
        if(is_numeric($formid) && strtolower(get_post_type($formid)) == "formulare") {
            return true;
        }
        return false;
    }

    private function getCompaniesByKAdmin($userid){
        $companiesThisKAdmin = array();
        $allCompanies = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getAllCompanies(false, true, false, false);

        foreach($allCompanies as $company){
            if($company->getKAdmin()!= null){
                if($company->getKAdmin()->getid() == $userid){
                    $companiesThisKAdmin[] = $company->getId();
                }
            }
        }

        return $companiesThisKAdmin;
    }
}

