<?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 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_session_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:manage_capp', $context);

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

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

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

$form = new local_kid_capp_session_form($PAGE->url, ['isediting' => (bool) $session]);

if ($session) {
    $form->set_data([
        'id' => $session->id,
        'promotionid' => $promotionid,
        'code' => $session->code,
        'libelle' => $session->libelle,
        'active' => $session->active,
    ]);
} else {
    $form->set_data(['promotionid' => $promotionid]);
}

if ($form->is_cancelled()) {
    redirect($returnurl);
} else if ($data = $form->get_data()) {
    if ($data->id) {
        capp_repository::update_session((int) $data->id, $data->code, $data->libelle, (bool) ($data->active ?? true), $USER->id);
    } else {
        capp_repository::create_session($promotionid, $data->code, $data->libelle, $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();
