<?php
/**
 * Unternehmens-Details
 *
 * @package    Company Details
 * @subpackage Company-Details/public
 * @author     Max Sternitzke <max.sternitzke@stud.th-luebeck.de>
 */
class Trainingssystem_Plugin_Module_Company_Details
{

    const MINTEILNEHMER = '8';
    
    public function __construct()
    {
    }

    public function showDetails()
    {
        $cid = isset($_GET['cid']) ? sanitize_text_field($_GET['cid']) : "";
        $gid = isset($_GET['gid']) ? sanitize_text_field($_GET['gid']) : "";
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrdetails")) {
            ob_start();

            if ($cid != "" || $gid != "") {
                $company = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getCompanyById($cid);

                $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 if (trim($cid) != "" && is_numeric($cid) && $company != null) {
                    // COMPANY

                    $groups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getGroups($cid);
                    $allmemberids = array();
                    $allmembers = array();
                    foreach ($groups as $group) {
                        if(!is_null($group->getMembers())) {
                            foreach ($group->getMembers() as $member) {
                                if (!isset($allmemberids[$member->getId()])) {
                                    $allmemberids[$member->getId()] = $member->getId();
                                    $allmembers[$member->getId()] = $member;
                                }
                            }
                        }
                    }
                    ksort($allmembers);
                    
                    $userDetailPermaLink = get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["user_list_detail"]);
                    $detailpageslinks = array();
                    foreach($allmembers as $user) {
                        $detailpageslinks[$user->getId()] = add_query_arg("userid", $user->getId(), $userDetailPermaLink);
                    }

                    $show = false;
                    if(sizeof($allmemberids) >= self::MINTEILNEHMER || Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrdetailsnothreshold")) {
                        $show = true;
                    }

                    $lastlogin_boss = "";
                    if($company->getBoss() != null) {
                        $lastlogin_boss = Trainingssystem_Plugin_Database::getInstance()->LastLoginDao->getLastlogin($company->getBoss()->getId());
                    }

                    $countHourActive = $show ? $this::getCountHourActiveMembers($allmemberids) : array();
                    $sumHourActive = $show ? $this::getSumHourActiveMembers($allmemberids) : array();
                    $countWeekdayActive = $show ? $this::getCountWeekdayActiveMembers($allmemberids) : array();
                    $sumWeekdayActive = $show ? $this::getSumWeekdayActiveMembers($allmemberids) : array();
                    $countPageView = $show ? $this::getCountPageViewMembers($allmemberids) : array();
                    $sumPageView = $show ? $this::getSumPageViewMembers($allmemberids) : array();

                    $company_group_links = array();
                    foreach($groups as $group) {
                        $company_group_links[$group->getId()] = add_query_arg(array("gid" => $group->getId(), "ocid" => $company->getId()), get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["company_details"]));
                    }

                    //echo "<pre>"; print_r($allmembers[array_key_first($allmembers)]);echo "</pre>";
                    echo $twig->render('company-details/company-details.html', ["company_overview_link" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["user_grouper"]),
                        "company_group_links" => $company_group_links,
                        "company" => $company,
                        "groups" => $groups,
                        "allmembers" => $allmembers,
                        "member_detail_links" => $detailpageslinks,
                        "boss_lastlogin" => $lastlogin_boss,
                        'counthouractive_l' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countHourActive['labels']) : null,
                        'counthouractive_v' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countHourActive['values']) : null,
                        'sumhouractive_l' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumHourActive['labels']) : null,
                        'sumhouractive_v' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumHourActive['values']) : null,
                        'countweekdayactive_l' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countWeekdayActive['labels']) : null,
                        'countweekdayactive_v' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countWeekdayActive['values']) : null,
                        'sumweekdayactive_l' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumWeekdayActive['labels']) : null,
                        'sumweekdayactive_v' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumWeekdayActive['values']) : null,
                        'countpageactive_l' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countPageView['labels']) : null,
                        'countpageactive_v' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countPageView['values']) : null,
                        'sumpageactive_l' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumPageView['labels']) : null,
                        'sumpageactive_v' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumPageView['values']) : null,
                        'hideMails' => isset(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['hide_mails']),
                        'show' => $show,
                        'MINTEILNEHMER' => self::MINTEILNEHMER,
                        'userCanSeeTrainingsProgress' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingprogress"),
                        'showUserDetails' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("userdetails"),
                        'canSeeUsername' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("seeusername"),
                        "canSeeUsermail" => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("seeusermail"),
                    ]);
                } else {
                    $group = Trainingssystem_Plugin_Database::getInstance()->CompanygroupDao->getCompanygroupById($gid);

                    if (trim($gid) != "" && is_numeric($gid) && $group != null) {
                        // COMPANY GROUP
                        $ocid = isset($_GET['ocid']) ? sanitize_text_field($_GET['ocid']) : "";

                        $company = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getCompanyById($ocid);

                        $allmemberids = array();
                        $allmembers = array();
                        
                        if(!is_null($group->getMembers())){
                            foreach ($group->getMembers() as $member) {
                                if (!isset($allmemberids[$member->getId()])) {
                                    $allmemberids[$member->getId()] = $member->getId();
                                    $allmembers[$member->getId()] = $member;
                                }
                            }
                        }
                        
                        ksort($allmembers);

                        $userDetailPermaLink = get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["user_list_detail"]);
                        $detailpageslinks = array();
                        foreach($allmembers as $user) {
                            $detailpageslinks[$user->getId()] = add_query_arg("userid", $user->getId(), $userDetailPermaLink);
                        }
                        
                        $show = false;
                        if(sizeof($allmemberids) >= self::MINTEILNEHMER || Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrdetailsnothreshold")) {
                            $show = true;
                        }

                        $countHourActive = $show ? $this::getCountHourActiveMembers($allmemberids) : array();
                        $sumHourActive = $show ? $this::getSumHourActiveMembers($allmemberids) : array();
                        $countWeekdayActive = $show ? $this::getCountWeekdayActiveMembers($allmemberids) : array();
                        $sumWeekdayActive = $show ? $this::getSumWeekdayActiveMembers($allmemberids) : array();
                        $countPageView = $show ? $this::getCountPageViewMembers($allmemberids) : array();
                        $sumPageView = $show ? $this::getSumPageViewMembers($allmemberids) : array();

                        echo $twig->render('company-details/company-group-details.html', ["company_overview_link" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["user_grouper"]),
                            "company_detail_link" => add_query_arg("cid", $company->getId(), get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["company_details"])),
                            "company" => $company,
                            "group" => $group,
                            "allmembers" => $allmembers,
                            "member_detail_links" => $detailpageslinks,
                            'counthouractive_l' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countHourActive['labels']) : null,
                            'counthouractive_v' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countHourActive['values']) : null,
                            'sumhouractive_l' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumHourActive['labels']) : null,
                            'sumhouractive_v' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumHourActive['values']) : null,
                            'countweekdayactive_l' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countWeekdayActive['labels']) : null,
                            'countweekdayactive_v' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countWeekdayActive['values']) : null,
                            'sumweekdayactive_l' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumWeekdayActive['labels']) : null,
                            'sumweekdayactive_v' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumWeekdayActive['values']) : null,
                            'countpageactive_l' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countPageView['labels']) : null,
                            'countpageactive_v' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countPageView['values']) : null,
                            'sumpageactive_l' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumPageView['labels']) : null,
                            'sumpageactive_v' => $show ? Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumPageView['values']) : null,
                            'hideMails' => isset(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['hide_mails']),
                            'show' => $show,
                            'MINTEILNEHMER' => self::MINTEILNEHMER,
                            'userCanSeeTrainingsProgress' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingprogress"),
                            'showUserDetails' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("userdetails"),
                            'canSeeUsername' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("seeusername"),
                            "canSeeUsermail" => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("seeusermail"),
                        ]);

                    } else {
                        echo $twig->render('company-details/invalid-id.html', ["company_overview_link" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["user_grouper"])]);
                    }
                }
            } else {
                echo $twig->render('company-details/invalid-id.html', ["company_overview_link" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["user_grouper"])]);
            }
            return ob_get_clean();
        } else {
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
    }

    private function getCountHourActiveMembers($memberids = array())
    {
        $stats = array();

        foreach ($memberids as $mid) {
            $stats[] = Trainingssystem_Plugin_Database::getInstance()->UserLogs->countHour($mid);
        }

        return $this::mergeStatistics($stats);
    }

    private function getSumHourActiveMembers($memberids = array())
    {
        $stats = array();

        foreach ($memberids as $mid) {
            $stats[] = Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumHour($mid);
        }

        return $this::mergeStatistics($stats);
    }

    private function getCountWeekdayActiveMembers($memberids = array())
    {
        $stats = array();

        foreach ($memberids as $mid) {
            $stats[] = Trainingssystem_Plugin_Database::getInstance()->UserLogs->countWeekday($mid);
        }

        return $this::mergeStatistics($stats);
    }

    private function getSumWeekdayActiveMembers($memberids = array())
    {
        $stats = array();

        foreach ($memberids as $mid) {
            $stats[] = Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumWeekday($mid);
        }

        return $this::mergeStatistics($stats);
    }

    private function getCountPageViewMembers($memberids = array())
    {
        $stats = array();

        foreach ($memberids as $mid) {
            $stats[] = Trainingssystem_Plugin_Database::getInstance()->UserLogs->countPageView($mid);
        }

        return $this::mergeStatistics($stats);
    }

    private function getSumPageViewMembers($memberids = array())
    {
        $stats = array();

        foreach ($memberids as $mid) {
            $stats[] = Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumPageView($mid);
        }

        return $this::mergeStatistics($stats);
    }

    private function mergeStatistics($stats)
    {
        $ret = array();
        $ret['labels'] = array();
        $ret['values'] = array();

        foreach ($stats as $stat) {
            foreach ($stat['labels'] as $lkey => $lval) {
                $lf = false;
                foreach ($ret['labels'] as $value) {
                    if ($lval == $value) {
                        $lf = true;
                        break;
                    }
                }
                if (!$lf) {
                    $ret['labels'][] = $lval;
                }
            }

            foreach ($stat['values'] as $vkey => $vval) {
                foreach ($ret['labels'] as $rlkey => $rlval) {
                    if ($rlval == $stat['labels'][$vkey]) {
                        $insertkey = $rlkey;
                    }
                }

                if (isset($ret['values'][$insertkey])) {
                    $ret['values'][$insertkey] += $vval;
                } else {
                    $ret['values'][$insertkey] = $vval;
                }
            }
        }

        asort($ret['labels']);

        $ret2 = array();
        $ret2['labels'] = array();
        $ret2['values'] = array();

        if (count($ret['labels']) == count($ret['values'])) {
            $i = 0;

            foreach ($ret['labels'] as $lkey => $lval) {
                $ret2['labels'][$i] = $lval;
                $ret2['values'][$i] = $ret['values'][$lkey];
                $i++;
            }
        }

        return $ret2;
    }
}
