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

/**
 * Activer/désactiver un stage.
 *
 * @package    local_kid
 */

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

use local_kid\local\access_helper;
use local_kid\local\stage_repository;

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

$id = required_param('id', PARAM_INT);
$promotionid = required_param('promotionid', PARAM_INT);
$action = required_param('action', PARAM_ALPHA);
require_sesskey();

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

if ($action === 'toggle') {
    stage_repository::toggle_active($id, $USER->id);
    redirect($returnurl, get_string('changessaved'), null, \core\output\notification::NOTIFY_SUCCESS);
}

if ($action === 'delete') {
    if (strtoupper($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
        throw new \moodle_exception('invalidrequest', 'error');
    }
    if (!stage_repository::get($id)) {
        throw new \moodle_exception('invalidrecord', 'error');
    }
    stage_repository::delete($id);
    redirect($returnurl, get_string('stage_deleted', 'local_kid'), null, \core\output\notification::NOTIFY_SUCCESS);
}

throw new \moodle_exception('invalidparameter', 'error');
