<?php

class Trainingssystem_Plugin_Module_Company_Forward_Content{

    public function __construct(){
    }

    // Shortcodes
    function showForwardContentForm($atts){

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

        if(0 !== get_current_user_id()) {
            if(!isset($atts['id'])){
                return $twig->render("company/company-forward-content-missingid.html");
            }
            else{
                $formid = trim($atts['id']);
                if($formid == ""){
                    return $twig->render("company/company-forward-content-missingid.html");
                }
                else{
                    $forwarded = false;
                    $current_user = wp_get_current_user();
                    $user_id = $current_user->ID;
                    // Rufe den Eintrag für den Meta_key "forward_content" für den aktuellen Benutzer ab
                    $usermetaEntry = get_user_meta($user_id,'forward_content',false);
                    // Eintrag existiert bereits für Benutzer
                    if(!empty($usermetaEntry)){
                        $formIdList = $usermetaEntry[0];
                        $formIdArray = explode(",", $formIdList);
                        if(in_array($formid, $formIdArray)){
                            $forwarded = true;
                        }
                    }

                    return $twig->render("company/company-forward-content-form.html", [
                        "id" => $formid,
                        "forwarded" => $forwarded
                    ]);
                }
            } 
        } else {
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
    }

    function showForwardContentList($atts){

        global $post;
        $post_id = $post->ID;

        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
        if(0 !== get_current_user_id()) {
            if(!isset($atts['id'])){
                return $twig->render("company/company-forward-content-missingid.html");
            }
            else{
                // Ids aller Felder, die im Parameter id dem Shortcode übergeben wurden
                $formIdString = $atts['id'];
                $formIdString = trim($formIdString);
                if($formIdString == ""){
                    return $twig->render("company/company-forward-content-missingid.html");
                }
                else{
                    $formIdsArray = explode(",", $formIdString);
                    $formIds = array();
                    for($i = 0; $i < sizeof($formIdsArray); $i++){
                        $formIds[] = trim($formIdsArray[$i]);
                    }

                    $current_user = wp_get_current_user();
                    $current_user_id = $current_user->ID;

                    // Abruf Daten für Führungskraft-Sicht
                    $isBoss = false;
                    $dataBoss = array();
                    if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("forwardcontentboss")){
                        $groupsThisBoss = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroupsByBossId($current_user_id);
                        if(sizeof($groupsThisBoss) > 0){
                            $isBoss = true;
                            $allBossUsers = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getUsersByBossId($current_user_id);
                            $newBossResults = Trainingssystem_Plugin_Database::getInstance()->Formdata->checkNewContent($allBossUsers, $formIds, $post_id);
                            $bossResults = array();
                            if(!empty($newBossResults)){

                                foreach($newBossResults as $bR){
                                    if(!isset($bossResults[$bR->user_ID])){
                                        $bossResults[$bR->user_ID] = array();
                                    }
                                    $bossResults[$bR->user_ID][$bR->field_ID] = $bR->data;
                                }
                            }
                            foreach($groupsThisBoss as $thisgroup){
                                $groupName = $thisgroup['name'];
                                $dataBoss[$groupName]['name'] = $groupName;
                                $userThisGroup = $thisgroup['users'];
                                shuffle($userThisGroup);
                                $groupSubmitIds = array();
                                foreach($userThisGroup as $userId){
                                    $userFormIds = explode(",", get_user_meta($userId, "forward_content", true));
                                    $groupSubmitIds[$userId] = $userFormIds; 
                                }
                                foreach($formIds as $id){
                                    // Abrufen der Labels für alle Felder des aktuellen Forms
                                    $fieldsThisForm = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($id);
                                    $labelFieldCounter = 0;
                                    foreach($fieldsThisForm as $formgroup){
                                        $formgroupAttributes = $formgroup->getAttributesJsonDecoded();
                                        $dataBoss[$groupName]["content"][$id][$labelFieldCounter]["label"] = $formgroupAttributes['label'];
                                        $labelFieldCounter++;
                                    }
                                    foreach($userThisGroup as $user){
                                        $formsThisUser = $groupSubmitIds[$user];
                                        if(in_array($id, $formsThisUser)){
                                            $formData = Trainingssystem_Plugin_Database::getInstance()->Formfield->getUserFormfieldsByForm($id, $user);
                                            foreach($formData as $formgroup){
                                                $fieldCounter = 0;
    
                                                foreach($formgroup as $field){
                                                    if($field->getFormdata() !== NULL){
                                                        $fieldText = $field->getFormdata()->getData();
                                                        $saveDate = $field->getFormdata()->getSaveDate();
                                                            if($fieldText != ""){
                                                                $dataBoss[$groupName]["content"][$id][$fieldCounter]["data"][] = $fieldText;
                                                                $dataBoss[$groupName]["content"][$id][$fieldCounter]["savedate"][] = $saveDate;
                                                                if(isset($bossResults[$user][$field->getFieldId()])){
                                                                    $dataBoss[$groupName]["content"][$id][$fieldCounter]["new"][] = true;
                                                                }
                                                                else{
                                                                    $dataBoss[$groupName]["content"][$id][$fieldCounter]["new"][] = false;
                                                                }
                                                                
                                                            }
                                                    }
                                                    $fieldCounter++;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Abruf Daten für kAdmin-Sicht
                    $isKAdmin = false;
                    $dataKAdmin = array();
                    if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("forwardcontentkadmin")){
                        $companiesThisKAdmin =$this::getCompaniesByKAdmin($current_user_id);
                        if(sizeof($companiesThisKAdmin) > 0){
                            $isKAdmin = true;
                            $allKAdminUsers = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getAllUserIdsByCreaterId($current_user_id);
                            $newKAdminResults = Trainingssystem_Plugin_Database::getInstance()->Formdata->checkNewContent($allKAdminUsers, $formIds, $post_id);
                            $kAdminResults = array();
                            if(!empty($newKAdminResults)){

                                foreach($newKAdminResults as $kR){
                                    if(!isset($kAdminResults[$kR->user_ID])){
                                        $kAdminResults[$kR->user_ID] = array();
                                    }
                                    $kAdminResults[$kR->user_ID][$kR->field_ID] = $kR->data;
                                }
                            }
                            foreach($companiesThisKAdmin as $company){
                                $companyInformation = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getCompanyById($company);
                                $companyName = $companyInformation->getName();
                                $dataKAdmin[$companyName]['name'] = $companyName;
                                $companyGroups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroups($company);
                                foreach($companyGroups as $group){
                                    $groupName = $group->getName();
                                    $dataKAdmin[$companyName]["groups"][$groupName]["name"] = $groupName;
                                    $userThisGroup = Trainingssystem_Plugin_Database::getInstance()->CompanygroupUserDao->getUserIdsByGroupId($group->getId());
                                    shuffle($userThisGroup);
                                    $groupSubmitIds = array();
                                    foreach($userThisGroup as $userId){
                                        $userFormIds = explode(",", get_user_meta($userId, "forward_content", true));
                                        $groupSubmitIds[$userId] = $userFormIds; 
                                    }
                                    foreach($formIds as $id){
                                        // Abrufen der Labels für alle Felder des aktuellen Forms
                                        $fieldsThisForm = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($id);
                                        $labelFieldCounter = 0;
                                        foreach($fieldsThisForm as $formgroup){
                                            $formgroupAttributes = $formgroup->getAttributesJsonDecoded();
                                            $dataKAdmin[$companyName]["groups"][$groupName]["content"][$id][$labelFieldCounter]["label"] = $formgroupAttributes['label'];
                                            $labelFieldCounter++;
                                        }
                                        foreach($userThisGroup as $user){
                                            $formsThisUser = $groupSubmitIds[$user];
                                            if(in_array($id, $formsThisUser)){
                                                $formData = Trainingssystem_Plugin_Database::getInstance()->Formfield->getUserFormfieldsByForm($id, $user);
                                                foreach($formData as $formgroup){
                                                    $fieldCounter = 0;
    
                                                    foreach($formgroup as $field){
                                                        if($field->getFormdata() !== NULL){
                                                            $fieldText = $field->getFormdata()->getData();
                                                            $saveDate = $field->getFormdata()->getSaveDate();
                                                                if($fieldText != ""){
                                                                    $dataKAdmin[$companyName]["groups"][$groupName]["content"][$id][$fieldCounter]["data"][] = $fieldText;
                                                                    $dataKAdmin[$companyName]["groups"][$groupName]["content"][$id][$fieldCounter]["savedate"][] = $saveDate;
                                                                    if(isset($kAdminResults[$user][$field->getFieldId()])){
                                                                        $dataKAdmin[$companyName]["groups"][$groupName]["content"][$id][$fieldCounter]["new"][] = true;
                                                                    }
                                                                    else{
                                                                        $dataKAdmin[$companyName]["groups"][$groupName]["content"][$id][$fieldCounter]["new"][] = false;
                                                                    }
                                                                }
                                                        }
                                                        $fieldCounter++;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Abruf Daten für  Teamleader-Sicht
                    $isTeamleader = false;
                    $dataTeamleader = array();

                    if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("forwardcontentteamleader")){
                        $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();
                            $dataTeamleader[$teamleadergroupName]['name'] = $teamleadergroupName;
                            shuffle($teamleaderGroupIds);
                            $groupSubmitIds = array();
                            foreach($teamleaderGroupIds as $userId){
                                $userFormIds = explode(",", get_user_meta($userId, "forward_content", true));
                                $groupSubmitIds[$userId] = $userFormIds; 
                            }

                            $newTeamleaderResults = Trainingssystem_Plugin_Database::getInstance()->Formdata->checkNewContent($teamleaderGroupIds, $formIds, $post_id);
                            $teamleaderResults = array();
                            if(!empty($newTeamleaderResults)){

                                foreach($newTeamleaderResults as $tR){
                                    if(!isset($teamleaderResults[$tR->user_ID])){
                                        $teamleaderResults[$tR->user_ID] = array();
                                    }
                                    $teamleaderResults[$tR->user_ID][$tR->field_ID] = $tR->data;
                                }
                            }

                            foreach($formIds as $id){
                                // Abrufen der Labels für alle Felder des aktuellen Forms
                                $fieldsThisForm = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($id);
                                $labelFieldCounter = 0;
                                foreach($fieldsThisForm as $formgroup){
                                    $formgroupAttributes = $formgroup->getAttributesJsonDecoded();
                                    $dataTeamleader[$teamleadergroupName]["content"][$id][$labelFieldCounter]["label"] = $formgroupAttributes['label'];
                                    $labelFieldCounter++;
                                }
                                foreach($teamleaderGroupIds as $user){
                                    $formsThisUser = $groupSubmitIds[$user];
                                    if(in_array($id, $formsThisUser)){
                                        $formData = Trainingssystem_Plugin_Database::getInstance()->Formfield->getUserFormfieldsByForm($id, $user);
                                        foreach($formData as $formgroup){
                                            $fieldCounter = 0;
    
                                            foreach($formgroup as $field){
                                                if($field->getFormdata() !== NULL){
                                                    $fieldText = $field->getFormdata()->getData();
                                                    $saveDate = $field->getFormdata()->getSaveDate();
                                                        if($fieldText != ""){
                                                            $dataTeamleader[$teamleadergroupName]["content"][$id][$fieldCounter]["data"][] = $fieldText;
                                                            $dataTeamleader[$teamleadergroupName]["content"][$id][$fieldCounter]["savedate"][] = $saveDate;
                                                            if(isset($teamleaderResults[$user][$field->getFieldId()])){
                                                                $dataTeamleader[$teamleadergroupName]["content"][$id][$fieldCounter]["new"][] = true;
                                                            }
                                                            else{
                                                                $dataTeamleader[$teamleadergroupName]["content"][$id][$fieldCounter]["new"][] = false;
                                                            }
                                                        }
                                                }
                                                $fieldCounter++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    $printlabels = false;
                    if(isset($atts['printlabels'])){
                        if($atts['printlabels'] == "1"){
                            $printlabels = true;
                        }
                    }
                    $showKAdminContent = false;
                    if(isset($atts['kadmin'])){
                        if($atts['kadmin'] == "1"){
                            $showKAdminContent = true;
                        }
                    }

                    $showBossContent = false;
                    if(isset($atts['boss'])){
                        if($atts['boss'] == "1"){
                            $showBossContent = true;
                        }
                    }

                    $showTeamleaderContent = false;
                    if(isset($atts['teamleader'])){
                        if($atts['teamleader'] == "1"){
                            $showTeamleaderContent = true;
                        }
                    }

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

                    $headlines = array();
                    if(isset($atts['headlines'])){
                        if(trim($atts['headlines']) != ""){
                            $headlinesString = $atts['headlines'];
                            $headlines = explode("|", $headlinesString);
                        }
                    }

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

                    $pdfDownloadTitle = "Inhalte als PDF herunterladen";
                    if(isset($atts['pdfdownloadtitle'])){
                        if(trim($atts['pdfdownloadtitle']) != ""){
                            $pdfDownloadTitle = trim($atts['pdfdownloadtitle']);
                        }
                    }
                    
                    $showSaveDate = false;
                    if(isset($atts['showsavedate'])){
                        if(trim($atts['showsavedate']) == "1"){
                            $showSaveDate = true;
                        }
                    }
                
                    return $twig->render("company/company-forward-content-list.html", [
                        "isBoss" => $isBoss,
                        "isKAdmin" => $isKAdmin,
                        "isTeamleader" => $isTeamleader,
                        "showKAdminContent" => $showKAdminContent,
                        "showBossContent" => $showBossContent,
                        "showTeamleaderContent" => $showTeamleaderContent,
                        "dataKAdmin" => $dataKAdmin,
                        "dataBoss" => $dataBoss,
                        "dataTeamleader" => $dataTeamleader,
                        "printlabels" => $printlabels,
                        "outputId" => $outputId,
                        "headlines" => $headlines,
                        "showPDFDownload" => $showPDFDownload,
                        "pdfDownloadTitle" => $pdfDownloadTitle,
                        "showSaveDate" => $showSaveDate
                    ]);

                }

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

    }

    function saveForwardContentId(){
        $formid = $_POST['formid'];
        $current_user = wp_get_current_user();
        if( 0 != $current_user->ID){
            $user_id = $current_user->ID;
            // Rufe den Eintrag für den Meta_key "forward_content" für den aktuellen Benutzer ab
            $usermetaEntry = get_user_meta($user_id,'forward_content',false);
            // Eintrag existiert bereits für Benutzer
            if(!empty($usermetaEntry)){
                $formIdList = $usermetaEntry[0];
                if(trim($formIdList) == ""){
                    update_user_meta($user_id, 'forward_content',$formid);
                }
                else{
                    $formIdArray = explode(",", $formIdList);
                    if(!in_array($formid, $formIdArray)){
                        $newFormIdList = $formIdList.','.$formid;
                        update_user_meta($user_id, 'forward_content', $newFormIdList);
                    }
                }

            }
            else{
                add_user_meta($user_id, 'forward_content', $formid);
            }
            echo "1";
        }

        wp_die();
    }

    function resetForwardContentId(){
        $formid = $_POST['formid'];
        $current_user = wp_get_current_user();
        if(0 != $current_user->ID){
            $user_id = $current_user->ID;
            // Rufe den Eintrag für den Meta_key "forward_content" für den aktuellen Benutzer ab
            $usermetaEntry = get_user_meta($user_id,'forward_content',true);
            $formIdArray = explode(",", $usermetaEntry);

            if(in_array($formid, $formIdArray)){
                $formIdArray2 = array();
                foreach($formIdArray as $thisFormId){
                    if($thisFormId != $formid){
                        $formIdArray2[] = $thisFormId;
                    }
                }
                $newUserMetaEntry = "";
                for($formIdIndex = 0; $formIdIndex < count($formIdArray2); $formIdIndex++){
                    if($formIdIndex != 0){
                        $newUserMetaEntry = ",".$newUserMetaEntry;
                    }
                    $newUserMetaEntry = $newUserMetaEntry.$formIdArray2[$formIdIndex];
                }
                update_user_meta($user_id, 'forward_content', $newUserMetaEntry);
            }
            echo "1";
        }
        wp_die();
    }

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

}