<?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.

/**
 * Import CSV des niveaux/commentaires d'un stage.
 *
 * @package local_kid
 */

require(__DIR__ . '/../../../config.php');
require_once($CFG->dirroot . '/local/kid/lib.php');
require_once($CFG->dirroot . '/local/kid/classes/form/stage_import_form.php');

use local_kid\local\access_helper;
use local_kid\local\stage_repository;

require_login();
$context = context_system::instance();
access_helper::require_capability_or_teacher('local/kid:evaluate_stage', $context);

$stageid = required_param('stageid', PARAM_INT);
$studentid = optional_param('studentid', 0, PARAM_INT);
$stage = stage_repository::get($stageid);
if (!$stage) {
    throw new \moodle_exception('invalidrecord', 'error');
}

$url = new moodle_url('/local/kid/pages/stage_import.php', ['stageid' => $stageid, 'studentid' => $studentid]);
$returnurl = new moodle_url('/local/kid/pages/stages.php', array_filter(['stageid' => $stageid, 'studentid' => $studentid]));

$PAGE->set_url($url);
$PAGE->set_context($context);
$PAGE->set_pagelayout('standard');
$PAGE->set_title(get_string('stage_import_action', 'local_kid'));
local_kid_setup_page($PAGE);

$form = new local_kid_stage_import_form($url->out(false));
$form->set_data(['stageid' => $stageid, 'studentid' => $studentid]);

$report = null;
if ($form->is_cancelled()) {
    redirect($returnurl);
} else if ($data = $form->get_data()) {
    $content = $form->get_file_content('csvfile');
    $report = stage_repository::import_csv($stage, $content, $USER->id, $studentid ?: null);
}

$renderer = $PAGE->get_renderer('local_kid');
echo $OUTPUT->header();

$inner = '';
if ($report !== null) {
    $inner .= $OUTPUT->notification(
        get_string('stage_import_result', 'local_kid', $report['added']),
        empty($report['errors']) ? \core\output\notification::NOTIFY_SUCCESS : \core\output\notification::NOTIFY_WARNING
    );
    if (!empty($report['errors'])) {
        $items = '';
        foreach ($report['errors'] as $error) {
            $items .= html_writer::tag('li', $error);
        }
        $inner .= html_writer::tag('ul', $items);
    }
    $inner .= html_writer::link($returnurl, get_string('back'), ['class' => 'btn btn-secondary']);
} else {
    $inner .= $OUTPUT->heading(get_string('stage_import_action', 'local_kid'), 2) . $form->render();
}

echo $renderer->render_shell(\local_kid\local\nav_helper::get_sidebar_items('stages'), $inner);
echo $OUTPUT->footer();
