<?php

use block_ned_teacher_tools as NED;
use block_ned_teacher_tools\output\menu_bar as MB;
use local_ned_controller\marking_manager\marking_manager as MM;
use local_ned_controller\mod_assign\assign as ned_assign;

require_once('../../config.php');
require_once(__DIR__ . '/common_lib.php');
require_once(NED\PLUGIN_PATH . '/classes/output/menu_bar.php');
require_once(NED\PLUGIN_PATH . '/lib.php');

$id = required_param('id', PARAM_INT);  // activity ID.
$userid = required_param('user', PARAM_INT);
$returnurl = optional_param('returnurl', '', PARAM_TEXT);

$error = false;
$user = null;
$url = new moodle_url(NED\PLUGIN_URL . '/submit_draft.php', ['id' => $id, 'user' => $userid]);
$name = NED\str('submit_draft');
$PAGE->set_url($url);

[$course, $cm] = get_course_and_cm_from_cmid($id, 'assign');
require_login($course, false, $cm);

$PAGE->navbar->add($name, $url);
$PAGE->set_title($name);
$PAGE->set_heading($name);

while(!$error){
    $user = $DB->get_record('user', ['id' => $userid]);
    if (!$user){
        $error = get_string('nousersfound');
        break;
    }

    $ned_assign = new ned_assign(context_module::instance($cm->id), $cm, $cm->get_course());
    $result = $ned_assign->draft2submit($userid);
    $error = $result === true ? false : $result;
    break;
}

$msg_attrs = ['assign' => $cm->name, 'user' => fullname($user) ?: get_string('user')];
if ($error){
    echo $OUTPUT->header();
    throw new moodle_exception('generalexceptionmessage', 'error', '',
        NED\str('submit_draft:error', $msg_attrs), NED\str_check($error));
} else {
    $url = !empty($returnurl) ? $returnurl :
        MB::get_page_moodle_url(MB::PAGE_MM, [MM::P_COURSEID => $course->id, MM::P_STATUS => MM::ST_DRAFT, MM::P_MID => $id]);
    NED\redirect($url, NED\str('submit_draft:success', $msg_attrs));
}
