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

/**
 * Synchronisation du référentiel de compétences depuis un référentiel
 * core_competency Moodle réel.
 *
 * @package    local_kid
 */

require(__DIR__ . '/../../../config.php');
require_once($CFG->dirroot . '/local/kid/lib.php');
require_once($CFG->dirroot . '/local/kid/classes/form/competency_sync_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);

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

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

$frameworks = competency_repository::get_all_frameworks();
if (empty($frameworks)) {
    echo $OUTPUT->header();
    echo $OUTPUT->notification(get_string('competency_sync_none', 'local_kid'), \core\output\notification::NOTIFY_WARNING);
    echo $OUTPUT->continue_button($returnurl);
    echo $OUTPUT->footer();
    exit;
}

$form = new local_kid_competency_sync_form($PAGE->url, ['frameworks' => $frameworks]);
$form->set_data(['promotionid' => $promotionid]);

if ($form->is_cancelled()) {
    redirect($returnurl);
} else if ($data = $form->get_data()) {
    $result = competency_repository::sync_from_framework($promotionid, (int) $data->frameworkid, $USER->id);
    redirect($returnurl, get_string('competency_sync_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('competency_sync_action', 'local_kid'), 2) . $form->render()
);
echo $OUTPUT->footer();
