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

/**
 * Téléchargement définitif d'un des deux CSV ADESI — revalide intégralement
 * côté serveur (section 21.8/21.9), ne fait jamais confiance à un état
 * "prévisualisé" côté client.
 *
 * @package local_kid
 */

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

use local_kid\local\access_helper;
use local_kid\local\adesi_export_service;

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

$promotionid = required_param('promotionid', PARAM_INT);
$sessionid = required_param('sessionid', PARAM_INT);
$type = required_param('type', PARAM_ALPHA);

if ($type === 'niveaux') {
    $result = adesi_export_service::export_niveaux($promotionid, $sessionid, $USER->id);
} else if ($type === 'commentaires') {
    $result = adesi_export_service::export_commentaires($promotionid, $sessionid, $USER->id);
} else {
    throw new \moodle_exception('invalidparameter', 'error');
}

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

if (!$result['success']) {
    redirect($returnurl, get_string('adesi_export_blocked', 'local_kid'), null, \core\output\notification::NOTIFY_ERROR);
}

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment;filename="' . $result['filename'] . '"');
header('Cache-Control: max-age=0');
echo $result['content'];
