';
echo '';
if ($display == 'useroverview' || $display == 'sessionoverview' || $display == 'courseoverview') {
    echo '';
    echo Display::return_icon("export_csv.png", get_lang('ExportAsCSV'), [], 32);
    echo '';
}
echo ''.
    Display::return_icon('printer.png', get_lang('Print'), '', ICON_SIZE_MEDIUM).'';
echo '';
if (!empty($session_id) &&
    !in_array($display, ['accessoverview', 'lpprogressoverview', 'progressoverview', 'exerciseprogress', 'surveyoverview'])
) {
    echo ''.Display::return_icon('back.png', get_lang('Back'), '', ICON_SIZE_MEDIUM).'';
    if (!api_is_platform_admin()) {
        if (api_get_setting('add_users_by_coach') == 'true') {
            if ($is_coach) {
                echo "
";
            }
        }
    } else {
        echo "
";
    }
} else {
    echo Display::url(
        Display::return_icon('stats.png', get_lang('MyStats'), '', ICON_SIZE_MEDIUM),
        api_get_path(WEB_CODE_PATH)."auth/my_progress.php"
    );
    echo Display::url(
        Display::return_icon("certificate_list.png", get_lang("GradebookSeeListOfStudentsCertificates"), [], ICON_SIZE_MEDIUM),
        api_get_path(WEB_CODE_PATH)."gradebook/certificate_report.php"
    );
}
// Actions menu
$nb_menu_items = count($menu_items);
if (empty($session_id) ||
    in_array($display, ['accessoverview', 'lpprogressoverview', 'progressoverview', 'exerciseprogress', 'surveyoverview'])
) {
    if ($nb_menu_items > 1) {
        foreach ($menu_items as $key => $item) {
            echo $item;
        }
    }
}
echo '';
$userId = api_get_user_id();
$stats = Tracking::getStats($userId, true);
$numberStudents = $stats['student_count'];
$students = $stats['student_list'];
$numberStudentBosses = $stats['student_bosses'];
$numberTeachers = $stats['teachers'];
$countHumanResourcesUsers = $stats['drh'];
$countAssignedCourses = $stats['assigned_courses'];
$countCourses = $stats['courses'];
$sessions = $stats['session_list'];
$sessionIdList = [];
if (!empty($sessions)) {
    foreach ($sessions as $session) {
        $sessionIdList[] = $session['id'];
    }
}
// Sessions for the user
$countSessions = count($sessions);
$total_time_spent = 0;
$total_courses = 0;
$avgTotalProgress = 0;
$nb_inactive_students = 0;
$numberAssignments = 0;
$inactiveTime = time() - (3600 * 24 * 7);
$daysAgo = 7;
$studentIds = [];
$avg_courses_per_student = 0;
$linkAddUser = null;
$linkCourseDetailsAsTeacher = null;
$linkAddCourse = null;
$linkAddSession = null;
if (api_is_platform_admin()) {
    $linkAddUser = ' '.Display::url(
        Display::return_icon('2rightarrow.png', get_lang('Add')),
        api_get_path(WEB_CODE_PATH).'admin/dashboard_add_users_to_user.php?user='.api_get_user_id(),
        ['class' => '']
    );
    $linkCourseDetailsAsTeacher = ' '.Display::url(
        Display::return_icon('2rightarrow.png', get_lang('Details')),
        api_get_path(WEB_CODE_PATH).'mySpace/course.php',
        ['class' => '']
    );
    $linkAddCourse = ' '.Display::url(
        Display::return_icon('2rightarrow.png', get_lang('Details')),
        api_get_path(WEB_CODE_PATH).'mySpace/course.php?follow',
        ['class' => '']
    );
    $linkAddSession = ' '.Display::url(
        Display::return_icon('2rightarrow.png', get_lang('Add')),
        api_get_path(WEB_CODE_PATH).'admin/dashboard_add_sessions_to_user.php?user='.api_get_user_id(),
        ['class' => '']
    );
}
echo Display::page_subheader(get_lang('Overview'));
echo '
        
            
                | '.Display::url(
                    get_lang('FollowedStudents'),
                    api_get_path(WEB_CODE_PATH).'mySpace/student.php'
                ).' | 
                '.$numberStudents.' | 
            
            
                | '.Display::url(
                    get_lang('FollowedStudentBosses'),
                    api_get_path(WEB_CODE_PATH).'mySpace/users.php?status='.STUDENT_BOSS
                ).' | 
                '.$numberStudentBosses.' | 
            
            
                | '.Display::url(
                    get_lang('FollowedTeachers'),
                    api_get_path(WEB_CODE_PATH).'mySpace/teachers.php'
                ).
                ' | 
                '.$numberTeachers.' | 
            
            
                | '.Display::url(
                get_lang('FollowedHumanResources'),
                api_get_path(WEB_CODE_PATH).'mySpace/users.php?status='.DRH
            ).
            ' | 
            '.$countHumanResourcesUsers.' | 
            
            
             | '.Display::url(
                get_lang('FollowedUsers'),
                api_get_path(WEB_CODE_PATH).'mySpace/users.php'
            ).
            ' | 
                '.($numberStudents + $numberStudentBosses + $numberTeachers + $countHumanResourcesUsers).$linkAddUser.' | 
            
            
                | '.Display::url(
                    get_lang('AssignedCourses'),
                    api_get_path(WEB_CODE_PATH).'mySpace/course.php'
                ).
                ' | 
                '.$countCourses.$linkCourseDetailsAsTeacher.' | 
            
            
                | '.Display::url(
                    get_lang('FollowedCourses'),
                    api_get_path(WEB_CODE_PATH).'mySpace/course.php?follow'
                ).
                ' | 
                '.$countAssignedCourses.$linkAddCourse.' | 
            
            
                | '.Display::url(
                    get_lang('FollowedSessions'),
                    api_get_path(WEB_CODE_PATH).'mySpace/session.php'
                ).
                ' | 
            '.$countSessions.$linkAddSession.' | 
            
            
';
echo '
 ';
echo Display::page_subheader(get_lang('Students').' ('.$numberStudents.')');
$form = new FormValidator(
    'search_user',
    'get',
    api_get_path(WEB_CODE_PATH).'mySpace/student.php'
);
$form = Tracking::setUserSearchForm($form);
$form->display();
$skipData = api_get_configuration_value('tracking_skip_generic_data');
$totalTimeSpent = null;
$averageScore = null;
$posts = null;
if ($skipData == false) {
    if (!empty($students)) {
        // Students
        $studentIds = array_values($students);
        $progress = Tracking::get_avg_student_progress($studentIds);
        $countAssignments = Tracking::count_student_assignments($studentIds);
        // average progress
        $avgTotalProgress = $progress / $numberStudents;
        // average assignments
        $numberAssignments = $countAssignments / $numberStudents;
        $avg_courses_per_student = $countCourses / $numberStudents;
        $totalTimeSpent = Tracking::get_time_spent_on_the_platform($studentIds);
        $posts = Tracking::count_student_messages($studentIds);
        $averageScore = Tracking::getAverageStudentScore($studentIds);
    }
    if ($export_csv) {
        //csv part
        $csv_content[] = [get_lang('Students')];
        $csv_content[] = [get_lang('InactivesStudents'), $nb_inactive_students];
        $csv_content[] = [get_lang('AverageTimeSpentOnThePlatform'), $totalTimeSpent];
        $csv_content[] = [get_lang('AverageCoursePerStudent'), $avg_courses_per_student];
        $csv_content[] = [get_lang('AverageProgressInLearnpath'), is_null($avgTotalProgress) ? null : round($avgTotalProgress, 2).'%'];
        $csv_content[] = [get_lang('AverageResultsToTheExercices'), is_null($averageScore) ? null : round($averageScore, 2).'%'];
        $csv_content[] = [get_lang('AveragePostsInForum'), $posts];
        $csv_content[] = [get_lang('AverageAssignments'), $numberAssignments];
        $csv_content[] = [];
    } else {
        $lastConnectionDate = api_get_utc_datetime(strtotime('15 days ago'));
        $countActiveUsers = SessionManager::getCountUserTracking(
            null,
            1,
            null,
            [],
            []
        );
        $countSleepingTeachers = SessionManager::getTeacherTracking(
            api_get_user_id(),
            1,
            $lastConnectionDate,
            true,
            $sessionIdList
        );
        $countSleepingStudents = SessionManager::getCountUserTracking(
            null,
            1,
            $lastConnectionDate,
            $sessionIdList,
            $studentIds
        );
        // html part
        echo '
                
                    
                        | '.get_lang('AverageCoursePerStudent').' | 
                        '.(is_null($avg_courses_per_student) ? '' : round($avg_courses_per_student, 2)).' | 
                    
                    
                        | '.get_lang('InactivesStudents').' | 
                        '.$nb_inactive_students.' | 
                    
                    
                        | '.get_lang('AverageTimeSpentOnThePlatform').' | 
                        '.(is_null($totalTimeSpent) ? '' : api_time_to_hms($totalTimeSpent)).' | 
                    
                    
                        | '.get_lang('AverageProgressInLearnpath').' | 
                        '.(is_null($avgTotalProgress) ? '' : round($avgTotalProgress, 2).'%').' | 
                    
                    
                        | '.get_lang('AvgCourseScore').' | 
                        '.(is_null($averageScore) ? '' : round($averageScore, 2).'%').' | 
                    
                    
                        | '.get_lang('AveragePostsInForum').' | 
                        '.(is_null($posts) ? '' : round($posts, 2)).' | 
                    
                    
                        | '.get_lang('AverageAssignments').' | 
                        '.(is_null($numberAssignments) ? '' : round($numberAssignments, 2)).' | 
                    
                
              ';
    }
}
// Send the csv file if asked
if ($export_csv) {
    ob_end_clean();
    Export:: arrayToCsv($csv_content, 'reporting_index');
    exit;
}
if (!$export_csv) {
    Display::display_footer();
}