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

/**
 * Transitions de workflow (valider/finaliser/rouvrir) pour un dossier CAPP.
 *
 * @package    local_kid
 */

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

use local_kid\local\access_helper;
use local_kid\local\capp_repository;
use local_kid\local\workflow_service;

require_login();
$context = context_system::instance();

$sessionid = required_param('sessionid', PARAM_INT);
$studentid = required_param('studentid', PARAM_INT);
$action = required_param('action', PARAM_ALPHA);
require_sesskey();

$entry = capp_repository::get_entry_for_student($sessionid, $studentid);
if (!$entry) {
    throw new \moodle_exception('invalidrecord', 'error');
}

$returnurl = new moodle_url('/local/kid/pages/capp.php', ['sessionid' => $sessionid, 'studentid' => $studentid]);
$table = 'local_kid_capp_entry';

switch ($action) {
    case 'valider':
        access_helper::require_capability_or_teacher('local/kid:evaluate_capp', $context);
        workflow_service::set_status('capp', $table, (int) $entry->id, workflow_service::STATUS_VALIDE, $USER->id);
        break;

    case 'finaliser':
        access_helper::require_capability_or_teacher('local/kid:evaluate_capp', $context);
        workflow_service::set_status('capp', $table, (int) $entry->id, workflow_service::STATUS_FINALISE, $USER->id);
        break;

    case 'reopen':
        access_helper::require_capability_or_teacher('local/kid:evaluate_capp', $context);
        workflow_service::reopen('capp', $table, (int) $entry->id, $USER->id);
        break;

    default:
        throw new \moodle_exception('invalidparameter', 'error');
}

redirect($returnurl, get_string('changessaved'), null, \core\output\notification::NOTIFY_SUCCESS);
