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

/**
 * Ajout ou renommage d'une promotion.
 *
 * @package    local_kid
 */

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

use local_kid\local\access_helper;
use local_kid\local\promotion_repository;

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

$id = optional_param('id', 0, PARAM_INT);
$promotion = $id ? promotion_repository::get($id) : null;
if ($id && !$promotion) {
    throw new \moodle_exception('invalidrecord', 'error');
}

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

$PAGE->set_url('/local/kid/pages/promotion_edit.php', ['id' => $id]);
$PAGE->set_context($context);
$PAGE->set_pagelayout('standard');
$title = $promotion ? get_string('promotion_rename_title', 'local_kid') : get_string('promotion_add_title', 'local_kid');
$PAGE->set_title($title);
local_kid_setup_page($PAGE);

$form = new local_kid_promotion_form($PAGE->url);
if ($promotion) {
    $form->set_data(['id' => $promotion->id, 'name' => $promotion->name]);
}

if ($form->is_cancelled()) {
    redirect($returnurl);
} else if ($data = $form->get_data()) {
    if ($data->id) {
        promotion_repository::rename((int) $data->id, $data->name, $USER->id);
    } else {
        promotion_repository::create($data->name, $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($title, 2) . $form->render()
);
echo $OUTPUT->footer();
