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

/**
 * Onglet admin "Export ADESI" : sélection promotion/session CAPP,
 * prévisualisation (section 21.8), liens de téléchargement des deux CSV.
 *
 * @package local_kid
 */

namespace local_kid\output;

use local_kid\local\adesi_export_service;
use local_kid\local\capp_repository;

defined('MOODLE_INTERNAL') || die();

class adesi_export_page implements \renderable, \templatable {

    protected int $promotionid;
    protected int $sessionid;

    public function __construct(int $promotionid, int $sessionid) {
        $this->promotionid = $promotionid;
        $this->sessionid = $sessionid;
    }

    public function export_for_template(\renderer_base $output): array {
        $sessions = capp_repository::get_sessions_for_promotion($this->promotionid);
        if (empty($sessions)) {
            return ['hasnosession' => true];
        }

        $sessionoptions = [];
        $sessionid = $this->sessionid;
        if (!$sessionid) {
            $last = end($sessions);
            $sessionid = $last ? (int) $last->id : 0;
        }
        foreach ($sessions as $session) {
            $sessionoptions[] = [
                'id' => $session->id,
                'label' => format_string($session->code . ' — ' . $session->libelle),
                'selected' => ((int) $session->id === $sessionid),
            ];
        }

        $preview = adesi_export_service::preview($this->promotionid, $sessionid);

        return [
            'hasnosession' => false,
            'promotionid' => $this->promotionid,
            'sessionid' => $sessionid,
            'sessionoptions' => $sessionoptions,
            'promotionname' => $preview['promotionname'],
            'sessioncode' => $preview['sessioncode'],
            'niveauxrowcount' => $preview['niveaux_rowcount'],
            'commentairesrowcount' => $preview['commentaires_rowcount'],
            'haserrors' => !empty($preview['errors']),
            'errors' => $preview['errors'],
            'norows' => $preview['norows'],
            'canexport' => !$preview['blocked'],
            'downloadniveauxurl' => (new \moodle_url('/local/kid/pages/adesi_download.php', [
                'promotionid' => $this->promotionid, 'sessionid' => $sessionid, 'type' => 'niveaux', 'sesskey' => sesskey(),
            ]))->out(false),
            'downloadcommentairesurl' => (new \moodle_url('/local/kid/pages/adesi_download.php', [
                'promotionid' => $this->promotionid, 'sessionid' => $sessionid, 'type' => 'commentaires', 'sesskey' => sesskey(),
            ]))->out(false),
        ];
    }
}
