<?php

use block_ned_student_menu as NED;
use block_ned_student_menu\shared_lib as SH;
use local_ned_controller\tt_config_manager as CM;

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

$cmid = required_param('cmid', PARAM_INT);
$userid = optional_param('userid', 0, PARAM_INT);

require_login();
[$course, $cm] = SH::get_course_and_cm_from_cmid($cmid, SH::ASSIGN);
$context = context_course::instance($course->id);

if (NED\is_SM){
    if (!has_capability('mod/assignment:submit', $context)){
        SH::print_error(SH::$C::str('permissionerror'));
    }
    $userid = $USER->id;
} elseif (NED\is_aTT) {
    if (!has_capability('moodle/grade:viewall', $context)){
        SH::print_error(SH::$C::str('permissionerror'));
    }
} else {
    SH::print_error(SH::$C::str('permissionerror'));
}

while (true){
    $submission_info = new local_ned_controller\mod_assign\assign_info($cm, $userid);
    if (!$submission_info->exist || $submission_info->submissions_count < 2){
        $error_text = '1';
        break;
    }
    if (!CM::is_resubmission_enable_for_activity($cmid, $course->id)){
        $error_text = '2';
        break;
    }
    if (($submission_info->last_grade_time && !$submission_info->overriden) || $submission_info->last_submit_time){
        $error_text = '3';
        break;
    }
    if (!NED\remove_last_submission($cmid, $userid, ASSIGN_SUBMISSION_STATUS_REOPENED)){
        $error_text = '4';
        break;
    }

    $url = SH::url('~/student_progress.php', ['courseid' => $course->id, 'user' => $userid, 'prevpage' => 'student_progress']);
    redirect($url, SH::str('unusedresubmissions_removed_successfully_one', ['activity' => $cm->name]), null, SH::NOTIFY_SUCCESS);
}

if (!empty($error_text)){
    SH::print_error('Error: '.$error_text);
}
