<?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 par le staff de la fiche d'un élève — l'état de travail
 * complet (fiche_builder::build(..., publishedonly=false)), quel que soit
 * le statut de publication, puisque c'est un document interne pour les
 * écrans Évaluations/Stages/CAPP et l'action "Voir la fiche" du tableau de
 * bord, pas le téléchargement côté élève.
 *
 * @package local_kid
 */

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

use local_kid\event\export_generated;
use local_kid\local\access_helper;
use local_kid\local\docx_service;
use local_kid\local\fiche_builder;
use local_kid\local\pdf_service;
use local_kid\local\promotion_repository;

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

$studentid = required_param('studentid', PARAM_INT);
$promotionid = required_param('promotionid', PARAM_INT);
$format = required_param('format', PARAM_ALPHA);

if (!promotion_repository::get($promotionid)) {
    throw new \moodle_exception('invalidrecord', 'error');
}

$dto = fiche_builder::build($studentid, $promotionid, false);
$filename = clean_param('fiche_' . $dto->student->fullname . '.' . $format, PARAM_FILE);

export_generated::create([
    'context' => $context,
    'userid' => (int) $USER->id,
    'other' => ['format' => $format, 'studentid' => $studentid, 'promotionid' => $promotionid],
])->trigger();

if ($format === 'docx') {
    docx_service::send(docx_service::build_fiche($dto), $filename);
} else if ($format === 'pdf') {
    pdf_service::send(pdf_service::build_fiche($dto), $filename);
} else {
    throw new \moodle_exception('invalidparameter', 'error');
}
