<?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 appréciations d'ensemble d'une session CAPP.
 *
 * @package local_kid
 */

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

use local_kid\local\access_helper;
use local_kid\local\capp_repository;

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

$sessionid = required_param('sessionid', PARAM_INT);
$session = capp_repository::get_session($sessionid);
if (!$session) {
    throw new \moodle_exception('invalidrecord', 'error');
}

$url = new moodle_url('/local/kid/pages/capp_import_appreciations.php', ['sessionid' => $sessionid]);
$returnurl = new moodle_url('/local/kid/pages/capp.php', ['sessionid' => $sessionid, 'mode' => 'import']);

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

$form = new local_kid_capp_import_appreciations_form($url->out(false));
$form->set_data(['sessionid' => $sessionid]);

$report = null;
if ($form->is_cancelled()) {
    redirect($returnurl);
} else if ($data = $form->get_data()) {
    $content = $form->get_file_content('csvfile');
    $report = capp_repository::import_csv_appreciations($session, $content, $USER->id);
}

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

$inner = '';
if ($report !== null) {
    $inner .= $OUTPUT->notification(
        get_string('capp_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('capp_import_appreciations_action', 'local_kid'), 2) . $form->render();
}

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