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

namespace local_kid\output;

use local_kid\local\access_helper;
use local_kid\local\eval_repository;
use local_kid\local\student_nav_helper;
use local_kid\local\workflow_service;

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

/**
 * Two display modes for one evaluation: the whole-promotion summary table
 * (no student selected) and a single student's grid (studentid given). The
 * grid <form> itself is rendered separately by the page controller
 * (moodleform HTML is not template-friendly) and passed in as raw content.
 */
class eval_grid_page implements \renderable, \templatable {

    protected \stdClass $eval;
    protected ?int $studentid;
    protected string $formhtml;
    protected ?array $conflict;

    /**
     * @param array|null $conflict a non-null {@see entry_conflict_service::enrich()}
     *   result when the just-attempted save was rejected by the optimistic
     *   check — the template embeds it as JSON for amd/src/conflict_view.js
     *   to render as an auto-opened modal; null on every ordinary render.
     */
    public function __construct(\stdClass $eval, ?int $studentid, string $formhtml = '', ?array $conflict = null) {
        $this->eval = $eval;
        $this->studentid = $studentid;
        $this->formhtml = $formhtml;
        $this->conflict = $conflict;
    }

    public function export_for_template(\renderer_base $output): array {
        $context = \context_system::instance();
        $entries = eval_repository::get_entries_for_eval((int) $this->eval->id);
        $canexport = access_helper::has_capability_or_teacher('local/kid:view', $context);
        $canimport = has_capability('local/kid:evaluate_evaluation', $context);
        $canevaluate = has_capability('local/kid:evaluate_evaluation', $context);
        $canpublishcap = has_capability('local/kid:publish_evaluation', $context);

        $steps = [
            ['id' => workflow_service::STATUS_SAISIE, 'label' => get_string('workflow_saisie', 'local_kid')],
            ['id' => workflow_service::STATUS_VALIDE, 'label' => get_string('workflow_valide', 'local_kid')],
            ['id' => workflow_service::STATUS_FINALISE, 'label' => get_string('workflow_finalise', 'local_kid')],
        ];

        if ($this->studentid === null) {
            $rows = [];
            foreach ($entries as $entry) {
                $rows[] = [
                    'studentid' => (int) $entry->studentid,
                    'name' => $entry->lastname . ' ' . $entry->firstname,
                    'statusbadge' => workflow_service::render_status_badge($entry->workflowstatus),
                    'publishedlabel' => $entry->published ? get_string('published_yes', 'local_kid') : get_string('published_no', 'local_kid'),
                    'publishedclass' => $entry->published ? 'fr-badge fr-badge--success' : 'fr-badge',
                    'openurl' => (new \moodle_url('/local/kid/pages/evaluations.php',
                        ['evalid' => $this->eval->id, 'studentid' => $entry->studentid]))->out(false),
                ];
            }
            $data = [
                'summarymode' => true,
                'titre' => format_string($this->eval->titre),
                'rows' => $rows,
                'hasrows' => !empty($rows),
                'canimport' => $canimport,
                'importurl' => (new \moodle_url('/local/kid/pages/eval_import.php', ['evalid' => $this->eval->id]))->out(false),
                'templateurl' => (new \moodle_url('/local/kid/pages/eval_template.php', ['evalid' => $this->eval->id]))->out(false),
                'canexport' => $canexport,
                'canbulkpublish' => $canpublishcap,
                'hasbulkactions' => $canexport || $canpublishcap,
                'bulkscreen' => 'evaluations',
                'bulkitemid' => (int) $this->eval->id,
                'sesskey' => sesskey(),
            ];
            return $data;
        }

        $entry = eval_repository::get_entry_for_student((int) $this->eval->id, $this->studentid);
        $steppositions = array_values(array_map(function ($step, $i) use ($entry) {
            $order = [workflow_service::STATUS_SAISIE, workflow_service::STATUS_VALIDE, workflow_service::STATUS_FINALISE];
            $currentidx = array_search($entry->workflowstatus, $order, true);
            return [
                'label' => $step['label'],
                'position' => $i + 1,
                'isdone' => $i < $currentidx,
                'isactive' => $i === $currentidx,
                'islast' => $i === count($order) - 1,
            ];
        }, $steps, array_keys($steps)));

        $data = [
            'summarymode' => false,
            'titre' => format_string($this->eval->titre),
            'studentnav' => student_nav_helper::build('evaluations', (int) $this->eval->id,
                (int) $this->eval->promotionid, $this->studentid),
            'steps' => $steppositions,
            'hasmoodlefeedback' => $this->eval->sourcetype === 'moodle_devoir',
            'moodlefeedbacktext' => $entry->feedbacktext
                ? format_text($entry->feedbacktext, (int) $entry->feedbackformat, ['context' => \context_system::instance()])
                : '',
            'moodlefeedbackchanged' => !empty($entry->feedbackchanged),
            'moodlefeedbacklastsync' => $entry->lastsyncat
                ? userdate((int) $entry->lastsyncat, get_string('strftimedatetimeshort', 'core_langconfig'))
                : get_string('eval_sync_never', 'local_kid'),
            'formhtml' => $this->formhtml,
            'conflictjson' => $this->conflict ? json_encode($this->conflict) : null,
            'workflowstatus' => $entry->workflowstatus,
            'ispublished' => (bool) $entry->published,
            'canvalidate' => $entry->workflowstatus === workflow_service::STATUS_SAISIE && $canevaluate,
            'canfinalise' => $entry->workflowstatus === workflow_service::STATUS_VALIDE && $canevaluate,
            'canreopen' => ($entry->workflowstatus === workflow_service::STATUS_FINALISE || $entry->published) && $canevaluate,
            'validateurl' => $this->action_url('valider'),
            'finaliseurl' => $this->action_url('finaliser'),
            'reopenurl' => $this->action_url('reopen'),
            'backurl' => (new \moodle_url('/local/kid/pages/evaluations.php', ['evalid' => $this->eval->id]))->out(false),
            'canimport' => $canimport,
            'templateoneurl' => (new \moodle_url('/local/kid/pages/eval_template.php', [
                'evalid' => $this->eval->id, 'studentid' => $this->studentid,
            ]))->out(false),
            'canexport' => $canexport,
        ];
        if ($canexport) {
            $data['fichestudenturl_docx'] = (new \moodle_url('/local/kid/pages/fiche_download.php', [
                'studentid' => $this->studentid, 'promotionid' => $this->eval->promotionid, 'format' => 'docx',
            ]))->out(false);
            $data['fichestudenturl_pdf'] = (new \moodle_url('/local/kid/pages/fiche_download.php', [
                'studentid' => $this->studentid, 'promotionid' => $this->eval->promotionid, 'format' => 'pdf',
            ]))->out(false);
        }
        return $data;
    }

    private function action_url(string $action): string {
        return (new \moodle_url('/local/kid/pages/eval_workflow_action.php', [
            'evalid' => $this->eval->id, 'studentid' => $this->studentid, 'action' => $action, 'sesskey' => sesskey(),
        ]))->out(false);
    }

}
