<?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 modification d'une compétence.
 *
 * @package    local_kid
 */

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

use local_kid\local\access_helper;
use local_kid\local\competency_repository;

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

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

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

$PAGE->set_url('/local/kid/pages/competency_edit.php', ['id' => $id, 'promotionid' => $promotionid]);
$PAGE->set_context($context);
$PAGE->set_pagelayout('standard');
$title = $competency ? get_string('competency_edit_title', 'local_kid') : get_string('competency_add', 'local_kid');
$PAGE->set_title($title);
local_kid_setup_page($PAGE);

$form = new local_kid_competency_form($PAGE->url, ['showactive' => (bool) $competency]);
if ($competency) {
    $form->set_data([
        'id' => $competency->id,
        'promotionid' => $promotionid,
        'libelle' => $competency->libelle,
        'codeadesi' => $competency->codeadesi,
        'active' => $competency->active,
    ]);
} else {
    $form->set_data(['promotionid' => $promotionid]);
}

if ($form->is_cancelled()) {
    redirect($returnurl);
} else if ($data = $form->get_data()) {
    if ($data->id) {
        competency_repository::update((int) $data->id, $data->libelle, $data->codeadesi, !empty($data->active), $USER->id);
    } else {
        competency_repository::create($promotionid, $data->libelle, $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($title, 2) . $form->render()
);
echo $OUTPUT->footer();
