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

/**
 * Liaison d'une promotion à une cohorte Moodle réelle.
 *
 * @package    local_kid
 */

require(__DIR__ . '/../../../config.php');
require_once($CFG->dirroot . '/local/kid/lib.php');
require_once($CFG->dirroot . '/local/kid/classes/form/cohort_link_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 = required_param('id', PARAM_INT);
$promotion = promotion_repository::get($id);
if (!$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_link.php', ['id' => $id]);
$PAGE->set_context($context);
$PAGE->set_pagelayout('standard');
$PAGE->set_title(get_string('promotion_link_title', 'local_kid'));
local_kid_setup_page($PAGE);

$cohorts = promotion_repository::get_all_moodle_cohorts();
$form = new local_kid_cohort_link_form($PAGE->url, ['cohorts' => $cohorts]);
$form->set_data(['promotionid' => $id]);

if ($form->is_cancelled()) {
    redirect($returnurl);
} else if ($data = $form->get_data()) {
    $result = promotion_repository::link_cohort((int) $data->promotionid, (int) $data->cohortid, $USER->id);
    redirect($returnurl, get_string('promotion_link_result', 'local_kid', (object) $result), 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('promotion_link_title', 'local_kid') . ' — ' . format_string($promotion->name), 2) . $form->render()
);
echo $OUTPUT->footer();
