<?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 une session CAPP.
 *
 * @package    local_kid
 */

require(__DIR__ . '/../../../config.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 = 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' => 'capp', 'promotionid' => $promotionid]);

if ($action === 'toggle') {
    $session = capp_repository::get_session($id);
    if (!$session) {
        throw new \moodle_exception('invalidrecord', 'error');
    }
    capp_repository::update_session($id, $session->code, $session->libelle, !$session->active, $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 (!capp_repository::get_session($id)) {
        throw new \moodle_exception('invalidrecord', 'error');
    }
    capp_repository::delete_session($id);
    redirect($returnurl, get_string('capp_session_deleted', 'local_kid'), null, \core\output\notification::NOTIFY_SUCCESS);
}

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