<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * @package    block_ned_teacher_tools
 * @copyright  Michael Gardener <mgardener@cissq.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

use block_ned_teacher_tools\utils;
use local_ned_controller\marking_manager\marking_manager as MM;
use local_ned_controller\ned_grade_controller as NGC;
use block_ned_teacher_tools\output\menu_bar as MB;
use block_ned_teacher_tools\shared_lib as SH;

require_once(dirname(__FILE__) . '/../../config.php');
require_once(__DIR__ . '/lib.php');

const GV_COMPLETION = 0;
const GV_GRADES = 1;
const GV_PERCENTAGE = 2;
const GV_OPTIONS = [
    GV_COMPLETION => 'completionview',
    GV_GRADES => 'gradesview',
    GV_PERCENTAGE => 'percentageview',
];

class_exists('\local_tem\helper') && \local_tem\helper::tem_submission_notify_or_redirect_check();

$show = optional_param('show', 0, PARAM_INT);
$range = optional_param('range', 0, PARAM_INT);
$instances = optional_param('instances', 0, PARAM_INT);
$gstatus = optional_param('gstatus', 0, PARAM_INT);
$history = optional_param('history', 0, PARAM_INT);

$showopts = SH::strings2menu(['all', 'ps', 'aic'], false, '&nbsp;&nbsp;');
$rangeopts = SH::strings2menu(['all', 'range40p', 'range60p', 'range80p', 'range90p', 'range100'], false, '&nbsp;&nbsp;');
$instancesopts = SH::strings2menu(['all', 'instance2p', 'instance3p', 'instance4p', 'instance5p'], false, '&nbsp;&nbsp;');
$gstatusopts = SH::strings2menu(['all', 'graded', 'ungraded'], false, '&nbsp;&nbsp;');
$historyopts = SH::strings2menu(['no', 'yes'], false, '&nbsp;&nbsp;');

$show = SH::isset_key($showopts, $show, 0);
$range = SH::isset_key($rangeopts, $range, 0);
$instances = SH::isset_key($instancesopts, $instances, 0);
$gstatus = SH::isset_key($gstatusopts, $gstatus, 0);
$history = SH::isset_key($historyopts, $history, 0);

$MB = new MB(MB::PAGE_RAPS, ['show' => $show, 'range' => $range, 'instances' => $instances, 'gstatus' => $gstatus, 'history' => $history]);
$MB->show_error_for_not_teacher();
$courseid = $MB->courseid;
$coursecontext = SH::ctx($courseid);

$course = $MB->course;
$tag = $MB->tag_id;
$base_moodle_url = $MB->get_url();

$PAGE->set_url($base_moodle_url);
SH::js_call_amds(['progress_report', 'reviewmodalmessage']);
SH::js_call_amd('userextension', 'add', ['body', $coursecontext->id]);
$PAGE->add_body_class(GV_OPTIONS[GV_GRADES]);
$tablecontainer_relative_classes = ['tablecontainer-relative'];
$tablecontainer_overflow_classes = ['tablecontainer-overflow'];

// Print header.
$page_title = SH::str('rapstitle');
$PAGE->navbar->add($page_title, new moodle_url(''));
$PAGE->set_title($page_title);
$PAGE->set_heading($course->fullname . ': ' . $page_title);

SH::require_capability('canviewrapsreport', $coursecontext);

$plugincfg = SH::get_config();
/** @var \block_ned_teacher_tools\course_users_status $course_users_status */
$course_users_status = new SH::$course_users_status($courseid);
$enable_course_status_controller_on_this_course = $course_users_status->enable_on_course();
$tt_config = SH::get_block_config($courseid, SH::TT_NAME);
$pp_on = $tt_config->participationpower_option ?? false;
$course_status_controller = $plugincfg->enablecoursecompletionstatuscontroller && $enable_course_status_controller_on_this_course;

if ($course_status_controller){
    $tablecontainer_overflow_classes[] = 'pl-4';
}

echo $OUTPUT->header();
echo SH::render($MB);

if ($MB->groupid == SH::GROUP_NONE || (empty($MB->students ?? 0))){
    if (empty($MB->allstudents ?? 0)){
        echo $OUTPUT->heading(get_string("nostudentsyet"));
    }
    echo $OUTPUT->footer($course);
    return;
}

$show_all_groups = $MB->groupid == SH::GROUP_ALL;
$activities = SH::get_important_activities_for_users($courseid, $MB->students, true);
$MM = MM::get_MM_by_params($MB->parameters_for_MM(['studuserid' => 0]));
if (SH::get_kica_enabled($courseid)){
    SH::kg_get_grades_by_course($courseid, array_keys($MB->students), false, true);
}

$filter = [
    MM::BY_ACTIVITY, MM::SORT, MM::GET_TAGS,
    MM::NOT_ZERO => true, MM::CHECK_TAG => $tag, $show
];
$mod_data = $MM->get_status_data($filter, MM::MOD_ALL);

$filter = [MM::USE_KICA, MM::BY_ACTIVITY_USER, MM::SORT, MM::ST_ALL, MM::GET_TAGS, MM::COUNT_MISSED_DEADLINE];
$MM->filter_hide_grades_before_midn_if_need($filter);

$suspended_userids = $MB->show_inactive ? get_suspended_userids($MB->context) : [];
$fn_base_url = MB::get_page_url(MB::PAGE_MM);
$fn_base_param_url = [
    MB::PAR_COURSE => $courseid, MB::PAR_GROUP => $MB->groupid, MM::P_STATUS => 'unmarked', MB::PAR_TAG => $tag,
    'dir' => 'DESC', 'sort' => 'date', 'unsubmitted' => 0, 'activity_type' => 0, 'view' => 'less'
];

// table content
$tablehtml = html_writer::start_div('table-responsive');
$tablehtml .= html_writer::start_tag('table', ['class'=>'generaltable simplegradebook progress_report raps-table', 'id' => 'datatable']);
$tablehtml .= html_writer::start_tag('thead', array());
$tablehtml .= html_writer::start_tag('tr', array());

$tablehtml .= html_writer::tag('th', SH::str('class'), ['class' => 'grade-cell mod-icon sorter-true', 'rowspan' => 2]);
$tablehtml .= html_writer::tag('th', SH::img('i/course', ''), ['class' => 'grade-cell mod-icon sorter-true',
    'title' => get_string('courseavg', 'grades'), 'rowspan' => 2]);

// student column
$name_head = SH::str('student');
$name_head .= SH::span('('.SH::str('firstname').' ↑)', 'px-1 font-weight-normal sort-info sort-info-up');
$name_head .= SH::span('('.SH::str('lastname').' ↑)', 'px-1 font-weight-normal sort-info sort-info-down');

$tablehtml .= html_writer::tag('th', $name_head, ['class' => 'name mod-icon sorter-true', 'rowspan' => 2]);

// Create table head and filter which activities we will show
foreach ($activities as $key => $cm){
    $mod = $mod_data[$cm->id] ?? null;

    if ($mod && ($mod->modname == 'assign' || $mod->modname == 'quiz')
        && isset($DB->get_tables(true)['plagiarism_copyleaks_config'])
        && $DB->record_exists('plagiarism_copyleaks_config', ['cm' => $cm->id, 'name' => 'plagiarism_copyleaks_enable', 'value' => 1])) {
        $tags = SH::cm_get_tags($cm);
        if (in_array(SH::TAG_SUMMATIVE, $tags)) {
            $add_head = '';

            $prefix = '';
            $postfix = '';

            $add_head = '';
            $head_class = ['mod-icon', 'add-tag-icon', 'border'];
            if ($mod->is_midterm){
                $add_head .= SH::div('', 'activity-midterm-point', ['title' => SH::str('midtermpoint:title')]);
                $head_class[] = 'column-midterm-point';
            }
            if (!$cm->available){
                $head_class[] = 'column-restricted-activity';
            }

            $displayname = $full_cm_name = $cm->get_formatted_name();
            $attributes = ['data-title' => $full_cm_name, 'data-toggle' => 'tooltip', 'data-placement' => 'top'];

            if ($plugincfg->truncateactivitynames){
                $displayname = substr($displayname, 0, (int)$plugincfg->truncateactivitynames);
            }

            $displayname = shorten_text($displayname, 30);
            $shorten_link_cm = SH::cm_get_text_icon_link($mod, $courseid, null, true, true, false,
                true, $displayname, null, null, 'text-decoration-none', ['title' => '']);
            $cm_name = SH::div(SH::span($shorten_link_cm, 'cm-name-rotated'),'cm-name');
            $cm_icon = SH::cm_get_text_icon_link($mod, $courseid, null, false, true, true,
                true, null, null, null, null, ['title' => '']);

            $colspan = ($show == 0) ? 2 : 1;

            $tablehtml .= html_writer::tag('th', $add_head . $cm_name . $prefix . $cm_icon . $postfix, [
                'class' => implode(' ', $head_class),
                'data-title' => $full_cm_name,
                'data-toggle' => 'tooltip',
                'data-placement' => 'top',
                'colspan' => $colspan
            ]);
            continue;
        }
    }
    unset($activities[$key]);
}

$tablehtml .= html_writer::end_tag('tr');
foreach ($activities as $key => $cm) {
    $mod = $mod_data[$cm->id] ?? null;
    if ($mod) {
        $attributes = ['class' => 'border score-header sorter-true', 'data-title' => SH::str('plagiarismscore'), 'data-toggle' => 'tooltip', 'data-placement' => 'top'];
        if (in_array($show, [0, 1])) {
            $tablehtml .= html_writer::tag('th', SH::str('ps'), $attributes);
        }
        if (in_array($show, [0, 2])) {
            $attributes['data-title'] = SH::str('aicontentscore');
            $tablehtml .= html_writer::tag('th', SH::str('aic'), $attributes);
        }
    }
}
$tablehtml .= html_writer::end_tag('tr');
$tablehtml .= html_writer::end_tag('thead');


$tablehtml .= html_writer::start_tag('tbody', array());

$users_statuses = $course_users_status->get_users_statuses(null, true);

foreach ($MB->students as $studentid => $student){
    if ($gstatus) {
        $MM = MM::get_MM_by_params(['course' => $course, 'set_students' => [$studentid => $student]]);
        $mm_data_list = $MM->get_data_all($filter);
    }
    $rowhtml = html_writer::start_tag('tr', ['data-userid' => $studentid]);
    $studentclass = [];

    $displayrow = false;
    $occurance = 0;
    $numofaccurance = $instances + 1;

    if ($MB->show_inactive){
        $supendedenrollment = $student->suspended || isset($suspended_userids[$studentid]);
        $simplegradebook[$studentid]['suspended'] = $supendedenrollment;
        if ($supendedenrollment){
            $studentclass[] = 'suspended';
        }
    } else {
        $simplegradebook[$studentid]['suspended'] = false;
    }

    if ($MB->userid == $studentid){
        $studentclass[] = 'highlight';
    }

    $rowhtml .= html_writer::start_tag('tr', ['class' =>  implode(' ', $studentclass),  'data-userid' => $studentid]);

    // Class
    $rowhtml .= html_writer::tag('td', $student->group->name ?? '', []);

    // course grade
    $is_view_grade = true;
    if ($course_status_controller && !is_siteadmin()){
        if (array_key_exists($studentid, $users_statuses) && !empty($users_statuses[$studentid]) && !empty($users_statuses[$studentid]->status)){
            $is_view_grade = SH::get_check_permission_view_grade($courseid, $users_statuses[$studentid]->status);
        }
    }
    if ($is_view_grade){
        $avg = SH::get_course_grade($courseid, $studentid);
        if ($avg != '-'){
            $percentage = round($avg, 0);
            $percentagecls = $avg >= 50 ? 'green' : 'red';
        } else {
            $percentage = ' - ';
            $percentagecls = 'red';
        }

        if ($MM->has_kica){
            $grade_link = [SH::PAGE_KICA, [SH::PAR_SETUSER => $studentid, SH::PAR_COURSE => $courseid]];
        } else {
            $grade_link = ['/grade/report/user/index.php', ['userid' => $studentid, 'id' => $courseid]];
        }
        $rowhtml .= html_writer::tag('td', SH::link($grade_link, $percentage, '', ['target' => '_blank']), ['class' => 'grade-cell '.$percentagecls]);
    } else {
        $rowhtml .= html_writer::tag('td',
            SH::fa("tt-status-icon tt-si-waitingfinalgrade"), ['class' => 'review-modal-message-text']);
    }

    // Username
    $username = SH::q_student_link($studentid, $courseid, 'ned-username', false, true, false);
    $sort_username = $student->firstname.'||'.$student->lastname;

    $rowhtml .= html_writer::tag('td', $username, [
        'class' => 'name', 'nowrap' => 'nowrap', 'data-sort-value' => $sort_username]);

    foreach ($activities as $cm){
        $gfilterpassed = true;
        if ($gstatus) {
            $gfilterpassed = false;
            $st_mod = $mm_data_list[$cm->id][$studentid];
            $isgraded = $st_mod->completed_grade_successfully ?? false;

            switch ($gstatus) {
                case 1: // Graded
                    if ($isgraded) {
                        $gfilterpassed = true;
                    }
                    break;
                case 2: // Ungraded
                    if (!$isgraded) {
                        $gfilterpassed = true;
                    }
                    break;
            }
        }
        if (in_array($show, [0, 1])) {
            list($similarityscore, $scores) = utils::render_copyleaks_score($cm, $studentid, 'similarityscore', false, $history);
            $minscore = is_array($scores) ? min($scores) : '';
            if ($minscore != '') {
                utils::raps_row_filter($range, $instances, $numofaccurance, $minscore, $gfilterpassed, $similarityscore, $displayrow, $occurance);
            }
            $rowhtml .= html_writer::tag('td', $similarityscore, ['class' => 'border', 'data-sort-value' => $minscore]);
        }
        if (in_array($show, [0, 2])) {
            list($aiscore, $scores) = utils::render_copyleaks_score($cm, $studentid, 'aiscore', false, $history);
            $minscore = is_array($scores) ? min($scores) : '';
            if ($minscore != '') {
                utils::raps_row_filter($range, $instances, $numofaccurance, $minscore, $gfilterpassed,$similarityscore, $displayrow, $occurance);
            }
            $rowhtml .= html_writer::tag('td', $aiscore, ['class' => 'border', 'data-sort-value' => $minscore]);
        }
    }

    $rowhtml .= html_writer::end_tag('tr');

    if ($displayrow) {
        $tablehtml .= $rowhtml;
    }
}
$tablehtml .= html_writer::end_tag('tbody');
$tablehtml .= html_writer::end_tag('table');
$tablehtml .= html_writer::end_div();

echo SH::tag('h2', SH::str('rapstitle'));

// Filter form.
$filterform = '';

// show-select
$filterform .= SH::div(
    SH::single_select($base_moodle_url, 'show', $showopts, $show, SH::str('show')),
    'groupselector show-selector'
);

// rance-select
$filterform .= SH::div(
    SH::single_select($base_moodle_url, 'range', $rangeopts, $range, SH::str('range')),
    'groupselector range-selector'
);

// instances-select
$filterform .= SH::div(
    SH::single_select($base_moodle_url, 'instances', $instancesopts, $instances, SH::str('instances')),
    'groupselector instances-selector'
);

// gstatus-select
$filterform .= SH::div(
    SH::single_select($base_moodle_url, 'gstatus', $gstatusopts, $gstatus, SH::str('gstatus')),
    'groupselector instances-selector'
);

// history-select
$filterform .= SH::div(
    SH::single_select($base_moodle_url, 'history', $historyopts, $history, SH::str('history')),
    'groupselector instances-selector'
);

echo SH::div($filterform, 'ned-teacher_tools-menu-wrapper');

echo SH::div(SH::div($tablehtml, $tablecontainer_overflow_classes), $tablecontainer_relative_classes);
echo block_ned_teacher_tools_footer($plugincfg);
echo $OUTPUT->footer($course);
