<?php
// This file is part of Moodle - https://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 <https://www.gnu.org/licenses/>.

/**
 * Plugin version and other meta-data are defined here.
 *
 * @package     local_hshexport
 * @copyright   2024 Elke Kreim elke.kreim@hs-hannover.de
 * @license     https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

use local_hshexport\form\evaluserexportform;
use local_hshexport\local\exporter;

require(__DIR__ . '/../../config.php');

$courseid = required_param('id',PARAM_INT);

$course = $DB->get_record('course', ['id' => $courseid], '*', MUST_EXIST);

$title = get_string('pluginname', 'local_hshexport');

require_login($course, true);

$PAGE->set_url('/local/hshexport/export.php', ['id' => $course->id]);
$PAGE->set_title($title);

$coursecontext = context_course::instance($course->id);
$PAGE->set_context($coursecontext);
require_capability('local/hshexport:canexport', $coursecontext);

$customdata = [
    'courseid' => $courseid,
    'coursecontext' => $coursecontext,
];

$mform = new evaluserexportform('#', $customdata);

$formdata = $mform->get_data();

if ($mform->is_cancelled()) {
    $returnurl = new moodle_url('/user/index.php', ['id' => $course->id]);
    redirect($returnurl);
} elseif ($formdata) {
    $exporter = new exporter($formdata);
    $exporter->csv_download();
} else {
    $mform->set_data($formdata);
}

echo $OUTPUT->header();
echo $OUTPUT->heading($title);

$mform->display();

echo $OUTPUT->footer();