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

/**
 * Point d'action unique du livret CAPP PDF, exposé à deux surfaces :
 * - Vue d'ensemble du CAPP (liste des sessions) : lien GET sans sélection
 *   -> mode cohorte d'office (page de garde + Bilan général + toutes les
 *   fiches).
 * - Vue de session (barre d'actions groupées) : POST avec studentids[] ->
 *   mode dérivé de la sélection par capp_rapport_builder::resolve_selection()
 *   (tout coché = cohorte, sous-ensemble = individuel sans Bilan général).
 *
 * Jamais de verrou de finalisation : l'export est possible à tout moment,
 * le document porte son propre horodatage de provenance.
 *
 * @package local_kid
 */

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

use local_kid\event\export_generated;
use local_kid\local\access_helper;
use local_kid\local\capp_repository;
use local_kid\local\capp_rapport_builder;
use local_kid\local\pdf_service;

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

$sessionid = required_param('sessionid', PARAM_INT);
$studentids = optional_param_array('studentids', [], PARAM_INT);
require_sesskey();

$session = capp_repository::get_session($sessionid);
if (!$session) {
    throw new \moodle_exception('invalidrecord', 'error');
}
capp_repository::ensure_entries($sessionid, $USER->id);

$dto = capp_rapport_builder::build($sessionid, $studentids);
$pdf = pdf_service::build_capp_rapport($dto);

export_generated::create([
    'context' => $context,
    'userid' => (int) $USER->id,
    'other' => [
        'format' => 'pdf_capp_rapport', 'domain' => 'capp', 'promotionid' => (int) $session->promotionid,
        'sessionid' => $sessionid, 'mode' => $dto->mode, 'count' => count($dto->students),
    ],
])->trigger();

$suffix = $dto->mode === 'individuel' ? '_selection' : '';
$filename = clean_param('livret_capp_' . $dto->session->code . $suffix . '.pdf', PARAM_FILE);
pdf_service::send($pdf, $filename);
