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

/**
 * Un élève télécharge sa propre fiche publiée — le local_kid_student.id
 * n'est jamais pris depuis la requête, toujours résolu à partir de
 * $USER->id, et seuls les éléments publiés sont inclus
 * (fiche_builder::build(..., publishedonly=true)).
 *
 * @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:viewown', $context);

$format = required_param('format', PARAM_ALPHA);

$promotion = promotion_repository::get_active_promotion_for_user((int) $USER->id);
if (!$promotion) {
    throw new \moodle_exception('student_no_promotion', 'local_kid');
}
$studentrecord = promotion_repository::get_active_student_record((int) $promotion->id, (int) $USER->id);
if (!$studentrecord) {
    throw new \moodle_exception('student_no_promotion', 'local_kid');
}

$dto = fiche_builder::build((int) $studentrecord->id, (int) $promotion->id, true);
$filename = clean_param('fiche_' . fullname($USER) . '.' . $format, PARAM_FILE);

export_generated::create([
    'context' => $context,
    'userid' => (int) $USER->id,
    'other' => ['format' => $format, 'studentid' => (int) $studentrecord->id, 'promotionid' => (int) $promotion->id, 'self' => true],
])->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');
}
