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

/**
 * Rattachement (consultatif) d'une évaluation ou d'un stage à une session
 * CAPP, ou déliaison (sessionid=0).
 *
 * @package    local_kid
 */

require(__DIR__ . '/../../../config.php');

use local_kid\local\access_helper;
use local_kid\local\capp_repository;
use local_kid\local\eval_repository;
use local_kid\local\stage_repository;

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

$sourcetype = required_param('sourcetype', PARAM_ALPHA);
$sourceid = required_param('sourceid', PARAM_INT);
$sessionid = required_param('sessionid', PARAM_INT);

if (!in_array($sourcetype, ['eval', 'stage'], true)) {
    throw new \moodle_exception('invalidparameter', 'error');
}

$promotionid = $sourcetype === 'eval'
    ? (int) (eval_repository::get($sourceid)->promotionid ?? 0)
    : (int) (stage_repository::get($sourceid)->promotionid ?? 0);
if (!$promotionid) {
    throw new \moodle_exception('invalidrecord', 'error');
}

if ($sessionid) {
    $session = capp_repository::get_session($sessionid);
    if (!$session || (int) $session->promotionid !== $promotionid) {
        throw new \moodle_exception('invalidrecord', 'error');
    }
    capp_repository::attach_source($sessionid, $sourcetype, $sourceid, $USER->id);
} else {
    capp_repository::detach_source($sourcetype, $sourceid, $promotionid);
}

redirect(new moodle_url('/local/kid/pages/admin.php', ['tab' => 'capp', 'promotionid' => $promotionid]),
    get_string('changessaved'), null, \core\output\notification::NOTIFY_SUCCESS);
