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

/**
 * Renommage d'un niveau (aucune route de suppression n'existe).
 *
 * @package    local_kid
 */

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

use local_kid\local\access_helper;
use local_kid\local\niveau_repository;

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

$id = required_param('id', PARAM_INT);
$niveau = niveau_repository::get($id);
if (!$niveau) {
    throw new \moodle_exception('invalidrecord', 'error');
}

$returnurl = new moodle_url('/local/kid/pages/admin.php', ['tab' => 'niveaux']);

$PAGE->set_url('/local/kid/pages/niveau_edit.php', ['id' => $id]);
$PAGE->set_context($context);
$PAGE->set_pagelayout('standard');
$PAGE->set_title(get_string('niveau_rename_title', 'local_kid'));
local_kid_setup_page($PAGE);

$form = new local_kid_niveau_form($PAGE->url);
$form->set_data([
    'id' => $niveau->id,
    'code_display' => $niveau->code,
    'libelle' => $niveau->libelle,
    'couleur' => $niveau->couleur,
    'sortorder' => $niveau->sortorder,
    'codeadesi' => $niveau->codeadesi,
]);

if ($form->is_cancelled()) {
    redirect($returnurl);
} else if ($data = $form->get_data()) {
    niveau_repository::update((int) $data->id, $data->libelle, $data->couleur, (int) $data->sortorder, $data->codeadesi, $USER->id);
    redirect($returnurl, get_string('changessaved'), null, \core\output\notification::NOTIFY_SUCCESS);
}

$renderer = $PAGE->get_renderer('local_kid');
echo $OUTPUT->header();
echo $renderer->render_shell(
    \local_kid\local\nav_helper::get_sidebar_items('admin'),
    $OUTPUT->heading(get_string('niveau_rename_title', 'local_kid'), 2) . $form->render()
);
echo $OUTPUT->footer();
