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

/**
 * Comparateur de bilans — export CSV/XLSX. Always revalidates the filters
 * server-side and calls {@see \local_kid\local\comparateur_repository::flatten()}
 * — the exact same function the on-screen matrix uses — never a separately
 * derived query, so the export always matches what the current filters
 * would show on screen.
 *
 * @package local_kid
 */

require(__DIR__ . '/../../../config.php');
require_once($CFG->dirroot . '/local/kid/lib.php');

use local_kid\local\access_helper;
use local_kid\local\comparateur_repository;
use local_kid\local\csv_import_service;
use local_kid\local\xlsx_service;

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

$format = optional_param('format', 'xlsx', PARAM_ALPHA);
if (!in_array($format, ['csv', 'xlsx'], true)) {
    throw new \moodle_exception('invalidparameter', 'error');
}

$promotionid = required_param('promotionid', PARAM_INT);
$promotion = \local_kid\local\promotion_repository::get($promotionid);
if (!$promotion) {
    throw new \moodle_exception('invalidrecord', 'error');
}

$filters = [
    'promotionid' => $promotionid,
    'studentids' => optional_param_array('studentids', [], PARAM_INT),
    'sourcekeys' => optional_param_array('sourcekeys', [], PARAM_ALPHANUMEXT),
    'competencyids' => optional_param_array('competencyids', [], PARAM_INT),
    'niveaucodes' => optional_param_array('niveaucodes', [], PARAM_ALPHANUMEXT),
    'onlyobserved' => (bool) optional_param('onlyobserved', 0, PARAM_BOOL),
];

$cells = comparateur_repository::flatten($filters);

$headers = [
    get_string('comparateur_export_col_promotion', 'local_kid'),
    get_string('comparateur_export_col_student', 'local_kid'),
    get_string('comparateur_export_col_code', 'local_kid'),
    get_string('comparateur_export_col_competency', 'local_kid'),
    get_string('comparateur_export_col_source', 'local_kid'),
    get_string('comparateur_export_col_type', 'local_kid'),
    get_string('comparateur_export_col_niveau', 'local_kid'),
    get_string('comparateur_export_col_commentaire', 'local_kid'),
];

$typelabels = [
    'eval' => get_string('comparateur_type_eval', 'local_kid'),
    'stage' => get_string('comparateur_type_stage', 'local_kid'),
    'capp' => get_string('comparateur_type_capp', 'local_kid'),
];

$rows = [];
foreach ($cells as $cell) {
    $rows[] = [
        $cell->promotionname,
        $cell->studentname,
        $cell->competencycode,
        $cell->competencylabel,
        $cell->sourcelabel,
        $typelabels[$cell->sourcetype] ?? $cell->sourcetype,
        $cell->niveaulabel,
        $cell->commentaire,
    ];
}

$basefilename = clean_param('comparateur_' . $promotion->name, PARAM_FILE);

if ($format === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment;filename="' . $basefilename . '.csv"');
    header('Cache-Control: max-age=0');

    $lines = [csv_import_service::to_csv_row($headers)];
    foreach ($rows as $row) {
        $lines[] = csv_import_service::to_csv_row($row);
    }
    echo "\xEF\xBB\xBF" . implode("\r\n", $lines) . "\r\n";
    exit;
}

$spreadsheet = xlsx_service::generic_table($headers, $rows, true, true);
xlsx_service::send($spreadsheet, $basefilename . '.xlsx');
