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

/**
 * Renderable/templatable data for the "Vue élève" screen. Two different
 * audiences, two different fiche_builder::build() modes: the real student
 * looking at their own dossier always gets publishedonly=true (publication
 * stays the one deliberate release gate towards a student — never
 * bypassed) ; staff previewing another student via ?studentid= gets the
 * exhaustive "totale" (publishedonly=false, same as the existing "Voir la
 * fiche" DOCX/PDF download already used from this same screen in preview
 * mode) — every active dossier regardless of workflow/publication status,
 * each one individually labelled with both, so staff get one single
 * cross-domain view of a student's record instead of hunting through the
 * separate Évaluations/Stages/CAPP screens for anything not yet published.
 *
 * @package    local_kid
 */

namespace local_kid\output;

use local_kid\local\fiche_builder;
use local_kid\local\niveau_repository;
use local_kid\local\workflow_service;

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

class student_page implements \renderable, \templatable {

    protected int $studentid;
    protected int $promotionid;
    protected bool $ispreview;
    protected bool $candownload;
    protected array $previewoptions;

    /**
     * @param int $studentid local_kid_student.id, or 0 if the viewer has no
     *        active student record and nothing was previewed.
     * @param array $previewoptions rows from promotion_repository::get_active_students()
     */
    public function __construct(int $studentid, int $promotionid, bool $ispreview, bool $candownload, array $previewoptions = []) {
        $this->studentid = $studentid;
        $this->promotionid = $promotionid;
        $this->ispreview = $ispreview;
        $this->candownload = $candownload;
        $this->previewoptions = $previewoptions;
    }

    public function export_for_template(\renderer_base $output): array {
        $data = [
            'ispreview' => $this->ispreview,
            'nopromotion' => !$this->studentid,
            'previewoptions' => null,
        ];

        if (!empty($this->previewoptions)) {
            $data['previewoptions'] = [
                'action' => (new \moodle_url('/local/kid/pages/student.php'))->out(false),
                'students' => array_map(fn($s) => [
                    'id' => $s->studentid,
                    'name' => fullname($s),
                    'selected' => (int) $s->studentid === $this->studentid,
                ], array_values($this->previewoptions)),
            ];
        }

        if (!$this->studentid) {
            $data['message'] = get_string('student_no_promotion', 'local_kid');
            return $data;
        }

        $dto = fiche_builder::build($this->studentid, $this->promotionid, !$this->ispreview);

        $data['previewbanner'] = $this->ispreview
            ? get_string('student_preview_banner', 'local_kid', $dto->student->fullname)
            : null;
        $data['fullname'] = $dto->student->fullname;
        $data['promotionname'] = $dto->student->promotionname;
        $data['codeena'] = $dto->student->codeena;

        $suffix = $this->ispreview ? '_staff' : '';
        $data['sections'] = [
            $this->section_data(
                get_string('student_section_eval' . $suffix, 'local_kid'), get_string('student_section_eval_empty' . $suffix, 'local_kid'),
                $dto->evaluations, 'evaluations', 'evalid'
            ),
            $this->section_data(
                get_string('student_section_stage' . $suffix, 'local_kid'), get_string('student_section_stage_empty' . $suffix, 'local_kid'),
                $dto->stages, 'stages', 'stageid'
            ),
            $this->section_data(
                get_string('student_section_capp' . $suffix, 'local_kid'), get_string('student_section_capp_empty' . $suffix, 'local_kid'),
                $dto->capp, 'capp', 'sessionid'
            ),
        ];

        if ($this->candownload) {
            $params = $this->ispreview
                ? ['studentid' => $this->studentid, 'promotionid' => $this->promotionid]
                : [];
            $endpoint = $this->ispreview ? 'fiche_download.php' : 'student_fiche_download.php';
            $data['downloadurl_docx'] = (new \moodle_url('/local/kid/pages/' . $endpoint, $params + ['format' => 'docx']))->out(false);
            $data['downloadurl_pdf'] = (new \moodle_url('/local/kid/pages/' . $endpoint, $params + ['format' => 'pdf']))->out(false);
        }

        return $data;
    }

    /**
     * @param string $screen page controller under pages/ owning this
     *        domain's entry screen ('evaluations'|'stages'|'capp').
     * @param string $itemparam URL param identifying the item on that
     *        controller ('evalid'|'stageid'|'sessionid').
     */
    private function section_data(string $title, string $emptylabel, array $items, string $screen, string $itemparam): array {
        return [
            'title' => $title,
            'slug' => $screen,
            'emptylabel' => $emptylabel,
            'hasitems' => !empty($items),
            'items' => array_map(fn($item) => [
                'titre' => $item->titre,
                'date' => $item->date ?? null,
                'statusbadge' => workflow_service::render_status_badge($item->workflowstatus),
                'publishedlabel' => get_string($item->published ? 'published_yes' : 'published_no', 'local_kid'),
                'publishedclass' => $item->published ? 'fr-badge fr-badge--success' : 'fr-badge',
                'itemopenurl' => (new \moodle_url('/local/kid/pages/' . $screen . '.php', [
                    $itemparam => $item->id, 'studentid' => $this->studentid,
                ]))->out(false),
                'appreciationglobale' => $item->appreciationglobale ?? null,
                'commentaireglobal' => $item->commentaireglobal ?? null,
                'competences' => array_map(fn($c) => [
                    'code' => $c->code,
                    'libelle' => $c->libelle,
                    'niveaulabel' => $c->niveau,
                    'niveauclass' => niveau_repository::badge_class($c->niveaucode ?? null),
                    'commentaire' => $c->commentaire,
                    'moodlefeedback' => $c->moodlefeedback,
                    'hasmoodlefeedback' => $c->hasmoodlefeedback,
                ], $item->competences),
            ], $items),
        ];
    }
}
