addElement('text', 'score', get_lang('Percentage'));
if ($global) {
    $form->addElement('hidden', 'view', 'admin');
} else {
    // Get exam lists
    $courseId = api_get_course_int_id();
    $sql = "SELECT quiz.title, id FROM $quizTable AS quiz
            WHERE
                c_id = $courseId AND
                active='1'
                $sessionCondition
            ORDER BY quiz.title ASC";
    $result = Database::query($sql);
    $exerciseList = array(get_lang('All'));
    while ($row = Database::fetch_array($result)) {
        $exerciseList[$row['id']] = $row['title'];
    }
    $form->addElement('select', 'exercise_id', get_lang('Exercise'), $exerciseList);
}
$form->addElement('style_submit_button', 'submit', get_lang('Filter'), 'class="search"');
$filter_score = isset($_REQUEST['score']) ? intval($_REQUEST['score']) : 70;
$exerciseId = isset($_REQUEST['exercise_id']) ? intval($_REQUEST['exercise_id']) : 0;
$form->setDefaults(array('score' => $filter_score));
if (!$exportToXLS) {
    Display :: display_header(get_lang('Reporting'));
    echo '
';
    if ($global) {
        echo '
'.
        Display::return_icon('stats.png', get_lang('MyStats'), '', ICON_SIZE_MEDIUM);
        echo '';
        echo '
';
        echo ''.
            Display::return_icon('export_excel.png',get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'';
        echo ''.
            Display::return_icon('printer.png',get_lang('Print'),'',ICON_SIZE_MEDIUM).'';
        echo '';
        $menuItems[] = Display::url(
            Display::return_icon('teacher.png', get_lang('TeacherInterface'), array(), 32),
            api_get_path(WEB_CODE_PATH).'mySpace/?view=teacher'
        );
        if (api_is_platform_admin()) {
            $menuItems[] = Display::url(
                Display::return_icon('star.png', get_lang('AdminInterface'), array(), 32),
                api_get_path(WEB_CODE_PATH).'mySpace/admin_view.php'
            );
        } else {
            $menuItems[] = Display::url(
                Display::return_icon('star.png', get_lang('CoachInterface'), array(), 32),
                api_get_path(WEB_CODE_PATH).'mySpace/index.php?view=coach'
            );
        }
        $menuItems[] = Display::return_icon('quiz_na.png', get_lang('ExamTracking'), array(), 32);
        $nb_menu_items = count($menuItems);
        if ($nb_menu_items > 1) {
            foreach ($menuItems as $key=> $item) {
                echo $item;
            }
        }
    } else {
        echo Display::url(
            Display::return_icon('user.png', get_lang('StudentsTracking'), array(), 32),
            'courseLog.php?'.api_get_cidreq().'&studentlist=true'
        );
        echo Display::url(
            Display::return_icon('course.png', get_lang('CourseTracking'), array(), 32),
            'courseLog.php?'.api_get_cidreq().'&studentlist=false'
        );
        echo Display::url(
            Display::return_icon('tools.png', get_lang('ResourcesTracking'), array(), 32),
            'courseLog.php?'.api_get_cidreq().'&studentlist=resouces'
        );
        echo Display::url(
            Display::return_icon('export_excel.png', get_lang('ExportAsXLS'), array(), 32),
            api_get_self().'?'.api_get_cidreq().'&export=1&score='.$filter_score.'&exercise_id='.$exerciseId
        );
    }
    echo '
 ';
    $form->display();
    echo ''.sprintf(get_lang('FilteringWithScoreX'), $filter_score).'%
';
}
$html = null;
if ($global) {
    $html .= '';
    $html .= '| '.get_lang('Courses').' | ';
    $html .= ''.get_lang('Quiz').' | ';
    $html .= ''.get_lang('ExamTaken').' | ';
    $html .= ''.get_lang('ExamNotTaken').' | ';
    $html .= ''.sprintf(get_lang('ExamPassX'), $filter_score).'% | ';
    $html .= ''.get_lang('ExamFail').' | ';
    $html .= ''.get_lang('TotalStudents').' | ';
    $html .= '
';
} else {
    $html .= '';
    $html .= '| '.get_lang('Quiz').' | ';
    $html .= ''.get_lang('User').' | ';
    //$html .= ''.sprintf(get_lang('ExamPassX'), $filter_score).' | ';
    $html .= ''.get_lang('Percentage').' % | ';
    $html .= ''.get_lang('Status').' | ';
    $html .= ''.get_lang('Attempts').' | ';
    $html .= '
';
}
$export_array_global = $export_array = array();
$s_css_class = null;
if (!empty($courseList) && is_array($courseList)) {
    foreach ($courseList as $courseInfo) {
        $sessionList = SessionManager::get_session_by_course($courseInfo['code']);
        $newSessionList = array();
        if (!empty($sessionList)) {
            foreach ($sessionList as $session) {
                $newSessionList[$session['id']] = $session['name'];
            }
        }
        $courseId = $courseInfo['real_id'];
        if ($global) {
            $sql = "SELECT count(id) as count
                    FROM $quizTable AS quiz
                    WHERE active='1' AND c_id = $courseId AND session_id = 0";
            $result = Database::query($sql);
            $countExercises = Database::store_result($result);
            $exerciseCount = $countExercises[0]['count'];
            $sql = "SELECT count(id) as count
                    FROM $quizTable AS quiz
                    WHERE active='1' AND c_id = $courseId AND session_id <> 0";
            $result = Database::query($sql);
            $countExercises = Database::store_result($result);
            $exerciseSessionCount = $countExercises[0]['count'];
            $exerciseCount =  $exerciseCount + $exerciseCount *count($newSessionList) + $exerciseSessionCount;
            // Add course and session list.
            if ($exerciseCount == 0) {
                $exerciseCount = 2;
            }
            $html .= "
                        | ";
            $html .= $courseInfo['title'];
            $html .= " | ";
        }
        $sql = "SELECT visibility FROM $toolTable
                WHERE c_id = $courseId AND name = 'quiz'";
        $result = Database::query($sql);
        // If main tool is visible.
        if (Database::result($result, 0 ,'visibility') == 1) {
            // Getting the exam list.
            if ($global) {
                $sql = "SELECT quiz.title, id, session_id
                    FROM $quizTable AS quiz
                    WHERE c_id = $courseId AND active='1'
                    ORDER BY session_id, quiz.title ASC";
            } else {
                //$sessionCondition = api_get_session_condition($sessionId, true, false);
                if (!empty($exerciseId)) {
                    $sql = "SELECT quiz.title, id, session_id
                            FROM $quizTable AS quiz
                            WHERE
                                c_id = $courseId AND
                                active = '1' AND
                                id = $exerciseId
                                $sessionCondition
                            ORDER BY session_id, quiz.title ASC";
                } else {
                    $sql = "SELECT quiz.title, id, session_id
                            FROM $quizTable AS quiz
                            WHERE
                                c_id = $courseId AND
                                active='1'
                                $sessionCondition
                            ORDER BY session_id, quiz.title ASC";
                }
            }
            $resultExercises = Database::query($sql);
            if (Database::num_rows($resultExercises) > 0) {
                $export_array_global = array();
                while ($exercise = Database::fetch_array($resultExercises)) {
                    $exerciseSessionId = $exercise['session_id'];
                    if (empty($exerciseSessionId)) {
                        if ($global) {
                            // If the exercise was created in the base course.
                            // Load all sessions.
                            foreach ($newSessionList as $currentSessionId => $sessionName) {
                                $result = processStudentList(
                                    $filter_score,
                                    $global,
                                    $exercise,
                                    $courseInfo,
                                    $currentSessionId,
                                    $newSessionList
                                );
                                $html .= $result['html'];
                                $export_array_global = array_merge($export_array_global, $result['export_array_global']);
                            }
                            // Load base course.
                            $result = processStudentList(
                                $filter_score,
                                $global,
                                $exercise,
                                $courseInfo,
                                0,
                                $newSessionList
                            );
                            $html .= $result['html'];
                            $export_array_global = array_merge($export_array_global, $result['export_array_global']);
                        } else {
                            if (empty($sessionId)) {
                                // Load base course.
                                $result = processStudentList(
                                    $filter_score,
                                    $global,
                                    $exercise,
                                    $courseInfo,
                                    0,
                                    $newSessionList
                                );
                                $html .= $result['html'];
                                $export_array_global = array_merge(
                                    $export_array_global,
                                    $result['export_array_global']
                                );
                            } else {
                                $result = processStudentList(
                                    $filter_score,
                                    $global,
                                    $exercise,
                                    $courseInfo,
                                    $sessionId,
                                    $newSessionList
                                );
                                $html .= $result['html'];
                                $export_array_global = array_merge(
                                    $export_array_global,
                                    $result['export_array_global']
                                );
                            }
                        }
                    } else {
                        // If the exercise only exists in this session.
                        $result = processStudentList(
                            $filter_score,
                            $global,
                            $exercise,
                            $courseInfo,
                            $exerciseSessionId,
                            $newSessionList
                        );
                        $html .= $result['html'];
                        $export_array_global = array_merge($export_array_global, $result['export_array_global']);
                    }
                }
            } else {
                $html .= "
                            | 
                                ".get_lang('NoExercise')."
                             | 
                        
                     ";
            }
        } else {
            $html .= "
                        | 
                            ".get_lang('NoExercise')."
                         | 
                    
                 ";
        }
    }
}
$html .= '
';
if (!$exportToXLS) {
    echo $html;
}
$filename = 'exam-reporting-'.date('Y-m-d-h:i:s').'.xls';
if ($exportToXLS) {
    if ($global) {
        export_complete_report_xls($filename, $export_array_global);
    } else {
        export_complete_report_xls($filename, $export_array);
    }
    exit;
}
/**
 * @param $a
 * @param $b
 * @return int
 */
function sort_user($a, $b) {
    if (is_numeric($a['score']) && is_numeric($b['score'])) {
        if ($a['score'] < $b['score']) {
            return 1;
        }
        return 0;
    }
    return 1;
}
/**
 * @param string $filename
 * @param array $array
 */
function export_complete_report_xls($filename, $array)
{
    global $charset, $global, $filter_score;
    $workbook = new Spreadsheet_Excel_Writer();
    $workbook ->setTempDir(api_get_path(SYS_ARCHIVE_PATH));
    $workbook->send($filename);
    $workbook->setVersion(8); // BIFF8
    $worksheet =& $workbook->addWorksheet('Report');
    //$worksheet->setInputEncoding(api_get_system_encoding());
    $worksheet->setInputEncoding($charset);
    $line = 0;
    $column = 0; //skip the first column (row titles)
    if ($global) {
        $worksheet->write($line, $column, get_lang('Courses'));
        $column++;
        $worksheet->write($line, $column, get_lang('Exercises'));
        $column++;
        $worksheet->write($line, $column, get_lang('ExamTaken'));
        $column++;
        $worksheet->write($line, $column, get_lang('ExamNotTaken'));
        $column++;
        $worksheet->write($line, $column, sprintf(get_lang('ExamPassX'), $filter_score) . '%');
        $column++;
        $worksheet->write($line, $column, get_lang('ExamFail'));
        $column++;
        $worksheet->write($line, $column, get_lang('TotalStudents'));
        $column++;
        $line++;
        foreach ($array as $row) {
            $column = 0;
            foreach ($row as $item) {
                $worksheet->write($line,$column,html_entity_decode(strip_tags($item)));
                $column++;
            }
            $line++;
        }
        $line++;
    } else {
        $worksheet->write($line,$column,get_lang('Exercises'));
        $column++;
        $worksheet->write($line,$column,get_lang('User'));
        $column++;
        $worksheet->write($line,$column,get_lang('Percentage'));
        $column++;
        $worksheet->write($line,$column,get_lang('Status'));
        $column++;
        $worksheet->write($line,$column,get_lang('Attempts'));
        $column++;
        $line++;
        foreach ($array as $row) {
            $column = 0;
            $worksheet->write($line,$column,html_entity_decode(strip_tags($row['exercise'])));
            $column++;
            foreach ($row['users'] as $key=>$user) {
                $column = 1;
                $worksheet->write($line,$column,html_entity_decode(strip_tags($user)));
                $column++;
                foreach ($row['results'][$key] as $result_item) {
                    $worksheet->write($line,$column,html_entity_decode(strip_tags($result_item)));
                    $column++;
                }
                $line++;
            }
        }
        $line++;
    }
    $workbook->close();
    exit;
}
function processStudentList($filter_score, $global, $exercise, $courseInfo, $sessionId, $newSessionList)
{
    $exerciseStatsTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
    $courseId = api_get_course_int_id($courseInfo['code']);
    if (empty($sessionId)) {
        $students = CourseManager::get_student_list_from_course_code(
            $courseInfo['code'],
            false,
            0,
            null,
            null,
            false
        );
    } else {
        $students = CourseManager::get_student_list_from_course_code(
            $courseInfo['code'],
            true,
            $sessionId,
            null,
            null,
            false
        );
    }
    $html = null;
    $totalStudents = count($students);
    if (!$global) {
        $html .= "";
    }
    if (!$global) {
        $html .= '| ';
    } else {
        $html .= ' | ';
    }
    $html .= $exercise['title'];
    if ($global && !empty($sessionId)) {
        $sessionName = isset($newSessionList[$sessionId]) ? $newSessionList[$sessionId] : null;
        $html .= Display::return_icon('star.png', get_lang('Session')).' ('.$sessionName.')';
    }
    $html .= ' | ';
    $globalRow = array(
        $courseInfo['title'],
        $exercise['title']
    );
    $total_with_parameter_score = 0;
    $taken = 0;
    $export_array_global = array();
    $studentResult = array();
    foreach ($students as $student) {
        $studentId = isset($student['user_id']) ? $student['user_id'] : $student['id_user'];
        $sql = "SELECT COUNT(ex.exe_id) as count
                FROM $exerciseStatsTable AS ex
                WHERE
                    ex.c_id = $courseId AND
                    ex.exe_exo_id = ".$exercise['id']." AND
                    exe_user_id='".$studentId."' AND
                    session_id = $sessionId
                ";
        $result = Database::query($sql);
        $attempts = Database::fetch_array($result);
        $sql = "SELECT exe_id, exe_result, exe_weighting
                FROM $exerciseStatsTable
                WHERE
                    exe_user_id = ".$studentId." AND
                    c_id = $courseId AND
                    exe_exo_id = ".$exercise['id']." AND
                    session_id = $sessionId
                ORDER BY exe_result DESC
                LIMIT 1";
        $result = Database::query($sql);
        $score = 0;
        $weighting = 0;
        while ($scoreInfo = Database::fetch_array($result)) {
            $score = $score + $scoreInfo['exe_result'];
            $weighting = $weighting + $scoreInfo['exe_weighting'];
        }
        $percentageScore = 0;
        if ($weighting != 0) {
            $percentageScore = round(($score*100)/$weighting);
        }
        if ($attempts['count'] > 0 ) {
            $taken++;
        }
        if ($percentageScore >= $filter_score) {
            $total_with_parameter_score++;
        }
        $tempArray = array();
        if (!$global) {
            $userInfo = api_get_user_info($studentId);
            // User
            $userRow = '';
            $userRow .= $userInfo['complete_name'];
            $userRow .= ' | ';
            // Best result
            if (!empty($attempts['count'])) {
                $userRow .= '';
                $userRow .= $percentageScore;
                $tempArray[] = $percentageScore;
                $userRow .= ' | ';
                if ($percentageScore >= $filter_score) {
                    $userRow .= '';
                    $userRow .= get_lang('PassExam').' | ';
                    $tempArray[] = get_lang('PassExam');
                } else {
                    $userRow .= '';
                    $userRow .= get_lang('ExamFail').' | ';
                    $tempArray[] = get_lang('ExamFail');
                }
                $userRow .= '';
                $userRow .= $attempts['count'];
                $tempArray[] = $attempts['count'];
                $userRow .= ' | ';
            } else {
                $score = '-';
                $userRow .= '';
                $userRow .=  '-';
                $tempArray[] = '-';
                $userRow .= ' | ';
                $userRow .= '';
                $userRow .= get_lang('NoAttempt');
                $tempArray[] = get_lang('NoAttempt');
                $userRow .= ' | ';
                $userRow .= '';
                $userRow .= 0;
                $tempArray[] = 0;
                $userRow .= ' | ';
            }
            $userRow .= '
';
            $studentResult[$studentId] = array(
                'html' => $userRow,
                'score' => $score,
                'array' => $tempArray,
                'user' => $userInfo['complete_name']
            );
        }
    }
    $row_not_global['exercise'] = $exercise['title'];
    if (!$global) {
        if (!empty($studentResult)) {
            $studentResultEmpty = $studentResultContent = array();
            foreach ($studentResult as $row) {
                if ($row['score'] == '-') {
                    $studentResultEmpty[] = $row;
                } else {
                    $studentResultContent[] = $row;
                }
            }
            // Sort only users with content
            usort($studentResultContent, 'sort_user');
            $studentResult = array_merge($studentResultContent, $studentResultEmpty);
            foreach ($studentResult as $row) {
                $html .= $row['html'];
                $row_not_global['results'][] = $row['array'];
                $row_not_global['users'][] = $row['user'];
            }
            $export_array[] = $row_not_global;
        }
    }
    if ($global) {
        // Exam taken
        $html .= '';
        $html .= $taken;
        $globalRow[]= $taken;
        $html .= ' | ';
        // Exam NOT taken
        $html .= '';
        $html .= $not_taken = $totalStudents - $taken;
        $globalRow[]= $not_taken;
        $html .= ' | ';
        // Exam pass
        if (!empty($total_with_parameter_score)) {
            $html .= '';
        } else {
            $html .= ' | ';
        }
        $html .= $total_with_parameter_score;
        $globalRow[]= $total_with_parameter_score;
        $html .= ' | ';
        // Exam fail
        $html .= '';
        $html .= $fail = $taken - $total_with_parameter_score;
        $globalRow[]= $fail;
        $html .= ' | ';
        $html .= '';
        $html .= $totalStudents;
        $globalRow[]= $totalStudents;
        $html .= ' | ';
        $html .= '';
        $export_array_global[] = $globalRow;
    }
    return array(
        'html' => $html,
        'export_array_global' => $export_array_global,
        'total_students' => $totalStudents
    );
}
Display :: display_footer();