<?php

class Trainingssystem_Plugin_Module_Company_GBU_Chart{

    const MINTEILNEHMER = '8';

    public function __construct(){
    }

    function showGBUChart($atts){
        
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if(0 !== get_current_user_id()) {
            $charttype = "all";
            if(isset($atts['charttype'])){

                if(trim($atts['charttype']) == "bar"){
                    $charttype = "bar";
                }
                else if(trim($atts['charttype']) == "line"){
                    $charttype = "line";
                }
            }


            $formIds = array();
            if(isset($atts['id'])){
                if(trim($atts['id']) == ""){
                    return $twig->render("company/company-forward-content-missingid.html");
                }
                else{
                    $formIdString = trim($atts['id']);
                    $formIdsArray = explode(",", $formIdString);
                    for($i = 0; $i < sizeof($formIdsArray); $i++){
                        $formIds[] = trim($formIdsArray[$i]);
                    }
                }
            }
            else{
                return $twig->render("company/company-forward-content-missingid.html");
            }

            $charttitles = array();
            if(isset($atts['charttitle'])){
                if(trim($atts['charttitle'])!= ""){
                    $charttitleString = trim($atts['charttitle']);
                    $charttitleArray = explode("|", $charttitleString);
                    for($j = 0; $j < sizeof($charttitleArray); $j++){
                        $charttitles[] = trim($charttitleArray[$j]);
                    }
                }
            }

            $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] = "";
                }
            }
            
            $current_user = wp_get_current_user();
            $current_user_id = $current_user->ID;

            $chartdata = array();
            $isBoss = false;
            $isKAdmin = false;
            $isTeamleader = false;
            if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("gbuchartkadmin")){
                $companiesThisKAdmin = $this::getCompaniesByKAdmin($current_user_id);
                if(sizeof($companiesThisKAdmin) > 0){
                    $isKAdmin = true;
                    foreach($companiesThisKAdmin as $company){
                        $companyInformation = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getCompanyById($company);
                        $companyName = $companyInformation->getName();
                        $companyGroups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroups($company);
                        $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());
                        }
    
                        foreach($formIds as $formid){
                            $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']." (".$fHead['value'].")";
                                        $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'];
                                        $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;
                                        }
                                    }
        
        
                                    $meanQuestionsTotal = array();
                                    $sumMeansTotal = array();
                                    $sumMeansGroup = array();
        
                                    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($chartdata[$company])){
                                                $chartdata[$company] = array();
                                            }
    
                                            $chartdata[$company]['companyname'] = $companyName;
    
                                            if(!isset($chartdata[$company]['groups'])){
                                                $chartdata[$company]['groups'] = array();
                                            }
    
                                            $chartdata[$company]['groups'][$groupID]['groupname'] = $group['name'];
    
                                            if(!isset($chartdata[$company]['groups'][$groupID]['formdata'])){
                                                $chartdata[$company]['groups'][$groupID]['formdata'] = array();
                                            }
    
                                            if(!isset($chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'])){
                                                $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'] = array();
                                            }
    
                                            if(!isset($chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion])){
                                                $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion] = array();
                                            }
    
                                            if(!isset($chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'])){
                                                $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'] = array();
                                            }
    
                                            $cIndex = count($chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart']);
                                            $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]['labels'] = $labelsThisField;
                                            $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]['values'] = array_values($groupFieldData[$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] > 0){
                                                $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean"] = round($meanThisGroup,1);
                                            }
                                            else{
                                                $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean"] = $meanThisGroup;
                                            }
                                            
                                            if($groupFieldTN[$groupID][$fQKey] > 0){
                                                if($mode[$formid] == "+-"){
                                                    if(round($meanThisGroup,1)<= 2.3){
                                                        $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "bfe2ca";
                                                    }
                                                    else if(round($meanThisGroup,1)>= 3.7){
                                                        $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "f4858e";
                                                    }
                                                    else{
                                                        $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "fed88f";
                                                    }
                                                }
                                                else if($mode[$formid] == "-+"){
                                                    if(round($meanThisGroup,1)<= 2.3){
                                                        $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "f4858e";
                                                    }
                                                    else if(round($meanThisGroup,1)>= 3.7){
                                                        $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "bfe2ca";
                                                    }
                                                    else{
                                                        $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "fed88f";
                                                    }
                                                }
                                                else{
                                                    $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "ffffff";
                                                }
                                            }
                                            else{
                                                $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "ffffff";
                                            }
                                            
                                            $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mintn"] = true;
        
                                            if($groupFieldTN[$groupID][$fQKey] < self::MINTEILNEHMER){
                                                $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mintn"] = false;
                                                $subscalesTNReached[$groupID][$metaThisQuestion] = false;
                                            }
        
                                            $chartdata[$company]['groups'][$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["charttitle"] = $fQValue;
                                        }
                                    }
        
                                    foreach($groups as $gID => $g){
                                        $chartdata[$company]['groups'][$gID]['formdata'][$formid]['bar'][0]['mintn'] = true;
                                        if(!in_array(true, $subscalesTNReached[$gID])){
                                            $chartdata[$company]['groups'][$gID]['formdata'][$formid]['bar'][0]['mintn'] = false; 
                                        }
                                        $chartdata[$company]['groups'][$gID]['formdata'][$formid]['bar'][0]['labels'] = $g['name'];
    
                                        $valuesTotalThisChart = array();
                                        $valuesGroupThisChart = array();
                                        $subscalesThisChart = array();
                                        $subscalesTNNotReachThisChart = array();
        
                                        foreach($subscales as $subscale){
        
                                            if($subscalesTNReached[$gID][$subscale] == true){
        
                                                $valuesTotalThisChart[] = round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale], 1); 
                                                $valuesGroupThisChart[] = round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale], 1);
                                                $subscalesThisChart[] = $subscale;
                                            }
                                            else{
                                                $subscalesTNNotReachThisChart[] = $subscale;
                                            }
                                        }
    
                                        $chartdata[$company]['groups'][$gID]['formdata'][$formid]['bar'][0]['gesamt'] = $valuesTotalThisChart;
                                        $chartdata[$company]['groups'][$gID]['formdata'][$formid]['bar'][0]['values'] = $valuesGroupThisChart;
                                        $chartdata[$company]['groups'][$gID]['formdata'][$formid]['bar'][0]['chartlabels'] = $subscalesThisChart;
                                        $chartdata[$company]['groups'][$gID]['formdata'][$formid]['bar'][0]['subscalesTNNotReached'] = $subscalesTNNotReachThisChart;
                                    }
                                    
                                }
                            }
                        }
                    }
                }

            }
            else if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("gbuchartboss")){
                $company_users = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getUsersByBossId($current_user_id);
                if(sizeof($company_users) > 0){
                    $isBoss = true;
                    $groups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroupsByBossId($current_user_id);
                    foreach($formIds as $formid){
                        $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']." (".$fHead['value'].")";
                                    $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'];
                                    $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;
                                    }
                                }
    
    
                                $meanQuestionsTotal = array();
                                $sumMeansTotal = array();
                                $sumMeansGroup = array();
    
                                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){
    
                                        $chartdata[$groupID]['groupname'] = $group['name'];
    
                                        if(!isset($chartdata[$groupID]['formdata'])){
                                            $chartdata[$groupID]['formdata'] = array();
                                        }
    
                                        if(!isset($chartdata[$groupID]['formdata'][$formid]['line'])){
                                            $chartdata[$groupID]['formdata'][$formid]['line'] = array();
                                        }
    
                                        if(!isset($chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion])){
                                            $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion] = array();
                                        }
    
                                        if(!isset($chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'])){
                                            $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'] = array();
                                        }
    
                                        $cIndex = count($chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart']);
                                        $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]['labels'] = $labelsThisField;
                                        $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]['values'] = array_values($groupFieldData[$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] > 0){
                                            $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean"] = round($meanThisGroup,1);
                                        }
                                        else{
                                            $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean"] = $meanThisGroup;
                                        }
                                        

                                        if($groupFieldTN[$groupID][$fQKey] > 0){
                                            if($mode[$formid] == "+-"){
                                                if(round($meanThisGroup,1)<= 2.3){
                                                    $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "bfe2ca";
                                                }
                                                else if(round($meanThisGroup,1)>= 3.7){
                                                    $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "f4858e";
                                                }
                                                else{
                                                    $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "fed88f";
                                                }
                                            }
                                            else if($mode[$formid] == "-+"){
                                                if(round($meanThisGroup,1)<= 2.3){
                                                    $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "f4858e";
                                                }
                                                else if(round($meanThisGroup,1)>= 3.7){
                                                    $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "bfe2ca";
                                                }
                                                else{
                                                    $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "fed88f";
                                                }
                                            }
                                            else{
                                                $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "ffffff";
                                            }
                                        }
                                        else{
                                            $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "ffffff";
                                        }

                                        $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mintn"] = true;
    
                                        if($groupFieldTN[$groupID][$fQKey] < self::MINTEILNEHMER){
                                            $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mintn"] = false;
                                            $subscalesTNReached[$groupID][$metaThisQuestion] = false;
                                        }
    
                                        $chartdata[$groupID]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["charttitle"] = $fQValue;
    
                                    }
                                }
    
    
                                
                                foreach($groups as $gID => $g){
    
                                    $chartdata[$gID]['formdata'][$formid]['bar'][0]['mintn'] = true;
                                    if(!in_array(true, $subscalesTNReached[$gID])){
                                        $chartdata[$gID]['formdata'][$formid]['bar'][0]['mintn'] = false; 
                                    }
                                    $chartdata[$gID]['formdata'][$formid]['bar'][0]['labels'] = $g['name']; 
    
                                    $valuesTotalThisChart = array();
                                    $valuesGroupThisChart = array();
                                    $subscalesThisChart = array();
                                    $subscalesTNNotReachThisChart = array();
    
                                    foreach($subscales as $subscale){
    
                                        if($subscalesTNReached[$gID][$subscale] == true){
    
                                            $valuesTotalThisChart[] = round($sumMeansTotal[$subscale]/$subscalesItemsCount[$subscale], 1); 
                                            $valuesGroupThisChart[] = round($sumMeansGroup[$gID][$subscale]/$subscalesItemsCount[$subscale], 1);
                                            $subscalesThisChart[] = $subscale;
                                        }
                                        else{
                                            $subscalesTNNotReachThisChart[] = $subscale;
                                        }
                                    }
    
                                    $chartdata[$gID]['formdata'][$formid]['bar'][0]['gesamt'] = $valuesTotalThisChart;
                                    $chartdata[$gID]['formdata'][$formid]['bar'][0]['values'] = $valuesGroupThisChart;
                                    $chartdata[$gID]['formdata'][$formid]['bar'][0]['chartlabels'] = $subscalesThisChart;
                                    $chartdata[$gID]['formdata'][$formid]['bar'][0]['subscalesTNNotReached'] = $subscalesTNNotReachThisChart;
                                }
    
                                
                                
                            }
                        }
                    }
                }
            }
            else if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("gbuchartteamleader")){
                $teamleaderGroupId = get_user_meta($current_user_id, "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 != $current_user_id){
                            $teamleaderGroupIds[] = $groupMemberId;
                        }
                        
                    }
                    $teamleadergroupName = $teamleaderGroup->getName();
    
                    foreach($formIds as $formid){
                        $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']." (".$fHead['value'].")";
                                    $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();
    
                                $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];
    
                                    
    
                                    $chartdata[$teamleaderGroupId]['groupname'] = $teamleadergroupName;
    
                                    if(!isset($chartdata[$teamleaderGroupId]['formdata'])){
                                        $chartdata[$teamleaderGroupId]['formdata'] = array();
                                    }
    
                                    if(!isset($chartdata[$teamleaderGroupId]['formdata'][$formid]['line'])){
                                        $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'] = array();
                                    }
    
                                    if(!isset($chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion])){
                                        $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion] = array();
                                    }
    
                                    if(!isset($chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'])){
                                        $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'] = array();
                                    }
    
                                    $cIndex = count($chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart']);
                                    $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]['labels'] = $labelsThisField;
                                    $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]['values'] = array_values($groupFieldData[$teamleaderGroupId][$fQKey]);
                                        
                                    $sumValuesThisGroup = 0;
                                    foreach($groupFieldData[$teamleaderGroupId][$fQKey] as $vKey => $vVal){
                                        $sumValuesThisGroup += $vKey*$vVal;
                                    }
                    
                                    $meanThisGroup = 0;
                                    if($groupFieldTN[$teamleaderGroupId][$fQKey] == 0){
                                        $meanThisGroup = "-";
                                    }
                                    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] > 0){
                                        $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean"] = round($meanThisGroup,1);
                                    }
                                    else{
                                        $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean"] = $meanThisGroup;
                                    }

                                    if($groupFieldTN[$teamleaderGroupId][$fQKey] > 0){
                                        if($mode[$formid] == "+-"){
                                            if(round($meanThisGroup,1)<= 2.3){
                                                $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "bfe2ca";
                                            }
                                            else if(round($meanThisGroup,1)>= 3.7){
                                                $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "f4858e";
                                            }
                                            else{
                                                $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "fed88f";
                                            }
                                        }
                                        else if($mode[$formid] == "-+"){
                                            if(round($meanThisGroup,1)<= 2.3){
                                                $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "f4858e";
                                            }
                                            else if(round($meanThisGroup,1)>= 3.7){
                                                $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "bfe2ca";
                                            }
                                            else{
                                                $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "fed88f";
                                            }
                                        }
                                        else{
                                            $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "ffffff";
                                        }
                                    }
                                    else{
                                        $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mean_color"] = "ffffff";
                                    }
                                    
                                    $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mintn"] = true;
    
                                    if($groupFieldTN[$teamleaderGroupId][$fQKey] < self::MINTEILNEHMER){
                                        $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["mintn"] = false;
                                        $subscalesTNReached[$teamleaderGroupId][$metaThisQuestion] = false;
                                    }
    
                                    $chartdata[$teamleaderGroupId]['formdata'][$formid]['line'][$metaThisQuestion]['chart'][$cIndex]["charttitle"] = $fQValue;
    
                                    
                                }
    
                                $chartdata[$teamleaderGroupId]['formdata'][$formid]['bar'][0]['mintn'] = true;
                                if(!in_array(true, $subscalesTNReached[$teamleaderGroupId])){
                                    $chartdata[$teamleaderGroupId]['formdata'][$formid]['bar'][0]['mintn'] = false; 
                                }
                                $chartdata[$teamleaderGroupId]['formdata'][$formid]['bar'][0]['labels'] = $teamleadergroupName; 
    
                                $valuesGroupThisChart = array();
                                $subscalesThisChart = array();
                                $subscalesTNNotReachThisChart = array();
    
                                foreach($subscales as $subscale){
    
                                    if($subscalesTNReached[$teamleaderGroupId][$subscale] == true){
    
                                        $valuesGroupThisChart[] = round($sumMeansGroup[$teamleaderGroupId][$subscale]/$subscalesItemsCount[$subscale], 1);
                                        $subscalesThisChart[] = $subscale;
                                    }
                                    else{
                                        $subscalesTNNotReachThisChart[] = $subscale;
                                    }
                                }
    
                                $chartdata[$teamleaderGroupId]['formdata'][$formid]['bar'][0]['values'] = $valuesGroupThisChart;
                                $chartdata[$teamleaderGroupId]['formdata'][$formid]['bar'][0]['chartlabels'] = $subscalesThisChart;
                                $chartdata[$teamleaderGroupId]['formdata'][$formid]['bar'][0]['subscalesTNNotReached'] = $subscalesTNNotReachThisChart;
                                
    
                            }
                        }
                    }
                }
            }

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

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

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

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

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

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

            $pdfDownloadTitleLineChart = "Auswertung (Häufigkeiten) als PDF herunterladen";
            if(isset($atts['pdfdownloadtitle_line'])){
                if(trim($atts['pdfdownloadtitle_line']) != ""){
                    $pdfDownloadTitleLineChart = trim($atts['pdfdownloadtitle_line']);
                }
            }

            $alpha = 1;
            if(isset($atts['alpha']) && trim($atts['alpha']) != "" && is_numeric($atts['alpha'])){
                $alpha = trim($atts['alpha']);
            }

            $barColorTotal = "#95989C";
            $barColorTeam = "#3C3F42";

            if(isset($atts['barcolortotal']) && trim($atts['barcolortotal']) != ""){
                if(preg_match("/#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){1}|([a-f]|[A-F]|[0-9]){3}|([a-f]|[A-F]|[0-9]){5})?\b/", trim($atts['barcolortotal']))) {
                    $barColorTotal = trim($atts['barcolortotal']);
                }
            }

            if(isset($atts['barcolorteam']) && trim($atts['barcolorteam']) != ""){
                if(preg_match("/#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){1}|([a-f]|[A-F]|[0-9]){3}|([a-f]|[A-F]|[0-9]){5})?\b/", trim($atts['barcolorteam']))) {
                    $barColorTeam = trim($atts['barcolorteam']);
                }
            }

            return $twig->render("company/company-gbu-chart.html", [
                "isBoss" => $isBoss,
                "isKAdmin" => $isKAdmin,
                "isTeamleader" => $isTeamleader,
                "charttype" => $charttype,
                "charttitles" => $charttitles,
                "chartdata" => $chartdata,
                "formids" => $formIds,
                "outputId" => $outputId,
                "MINTEILNEHMER" => self::MINTEILNEHMER,
                "showPDFDownload" => $showPDFDownload,
                "showPDFDownloadBarChart" => $showPDFDownloadBarChart,
                "showPDFDownloadLineChart" => $showPDFDownloadLineChart,
                "pdfDownloadTitle" => $pdfDownloadTitle,
                "pdfDownloadTitleBarChart" => $pdfDownloadTitleBarChart,
                "pdfDownloadTitleLineChart" => $pdfDownloadTitleLineChart,
                "mode" => $mode,
                "alpha" => $alpha,
                "barColorTotal" => $barColorTotal,
                "barColorTeam" => $barColorTeam
            ]);

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

        }
    }

    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;
    }

}