<?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écharger la fiche PDF/DOCX" de la barre d'actions groupées — une
 * fiche par élève sélectionné (état de travail complet, pas
 * publishedonly), regroupées dans un seul ZIP. Remplace l'ancien
 * fiche_zip.php (toute la promotion sans sélection) : cocher "tout
 * sélectionner" puis cette action reproduit exactement son comportement.
 *
 * POST uniquement (formulaire construit par amd/src/bulk_actions.js), pas
 * d'appel core/ajax possible pour une réponse binaire. La sélection reçue
 * n'est jamais fiée telle quelle : seuls les studentid réellement présents
 * parmi les dossiers de cet item (screen+itemid) sont retenus.
 *
 * @package local_kid
 */

require(__DIR__ . '/../../../config.php');
require_once($CFG->libdir . '/filelib.php');

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

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

$screen = required_param('screen', PARAM_ALPHA);
$itemid = required_param('itemid', PARAM_INT);
$format = required_param('format', PARAM_ALPHA);
$studentids = required_param_array('studentids', PARAM_INT);
require_sesskey();

if (!bulk_action_service::is_valid_screen($screen) || !in_array($format, ['docx', 'pdf'], true)) {
    throw new \moodle_exception('invalidparameter', 'error');
}

$item = bulk_action_service::get_item($screen, $itemid);
if (!$item) {
    throw new \moodle_exception('invalidrecord', 'error');
}
$promotionid = (int) $item->promotionid;

$entries = bulk_action_service::get_entries($screen, $itemid);
$studentids = array_values(array_unique(array_map('intval', $studentids)));
$selected = array_values(array_intersect($studentids, array_keys($entries)));
if (empty($selected)) {
    throw new \moodle_exception('error_no_active_students', 'local_kid');
}

$dir = make_request_directory();
$zippath = $dir . '/fiches.zip';
$zip = new \ZipArchive();
$zip->open($zippath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

$usedfilenames = [];
foreach ($selected as $studentid) {
    $dto = fiche_builder::build($studentid, $promotionid, false);

    $source = $format === 'docx'
        ? docx_service::save_to_temp_file(docx_service::build_fiche($dto))
        : pdf_service::save_to_temp_file(pdf_service::build_fiche($dto));

    $basename = clean_param($dto->student->fullname, PARAM_FILE);
    $entryname = $basename . '.' . $format;
    $suffix = 2;
    while (isset($usedfilenames[$entryname])) {
        $entryname = $basename . '_' . $suffix++ . '.' . $format;
    }
    $usedfilenames[$entryname] = true;

    $zip->addFile($source, $entryname);
}
$zip->close();

export_generated::create([
    'context' => $context,
    'userid' => (int) $USER->id,
    'other' => ['format' => $format . '_zip', 'domain' => bulk_action_service::SCREENS[$screen]['domain'], 'promotionid' => $promotionid, 'count' => count($selected)],
])->trigger();

$filename = clean_param('fiches_selection.zip', PARAM_FILE);
send_temp_file($zippath, $filename);
