<?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\stage_repository;
use local_kid\local\student_nav_helper;
use local_kid\local\workflow_service;

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

/**
 * Two display modes for one stage: the whole-promotion avancement table (no
 * student selected) and a single student's grid + documents (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 stage_grid_page implements \renderable, \templatable {

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

    public function __construct(\stdClass $stage, ?int $studentid, string $formhtml = '', ?array $conflict = null) {
        $this->stage = $stage;
        $this->studentid = $studentid;
        $this->formhtml = $formhtml;
        $this->conflict = $conflict;
    }

    public function export_for_template(\renderer_base $output): array {
        $context = \context_system::instance();
        $entries = stage_repository::get_entries_for_stage((int) $this->stage->id);
        $canimport = has_capability('local/kid:evaluate_stage', $context);
        $canexport = access_helper::has_capability_or_teacher('local/kid:view', $context);
        $canevaluate = has_capability('local/kid:evaluate_stage', $context);
        $canpublishcap = has_capability('local/kid:publish_stage', $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 = [];
            $finalisedcount = 0;
            $publishedcount = 0;
            foreach ($entries as $entry) {
                if ($entry->workflowstatus === workflow_service::STATUS_FINALISE) {
                    $finalisedcount++;
                }
                if ($entry->published) {
                    $publishedcount++;
                }
                $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/stages.php',
                        ['stageid' => $this->stage->id, 'studentid' => $entry->studentid]))->out(false),
                ];
            }
            $data = [
                'summarymode' => true,
                'libelle' => format_string($this->stage->libelle),
                'rows' => $rows,
                'hasrows' => !empty($rows),
                'studentcount' => count($entries),
                'finalisedcount' => $finalisedcount,
                'publishedcount' => $publishedcount,
                'canimport' => $canimport,
                'importurl' => (new \moodle_url('/local/kid/pages/stage_import.php', ['stageid' => $this->stage->id]))->out(false),
                'templateurl' => (new \moodle_url('/local/kid/pages/stage_template.php', ['stageid' => $this->stage->id]))->out(false),
                'canexport' => $canexport,
                'canbulkpublish' => $canpublishcap,
                'hasbulkactions' => $canexport || $canpublishcap,
                'bulkscreen' => 'stages',
                'bulkitemid' => (int) $this->stage->id,
                'sesskey' => sesskey(),
            ];
            return $data;
        }

        $entry = stage_repository::get_entry_for_student((int) $this->stage->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)));

        $docs = [];
        foreach (stage_repository::list_docs((int) $entry->id) as $file) {
            $docs[] = [
                'filename' => $file->filename,
                'filesize' => display_size($file->filesize),
                'downloadurl' => (\moodle_url::make_pluginfile_url(
                    \context_system::instance()->id, 'local_kid', 'stagedoc', $entry->id, '/', $file->filename
                ))->out(false),
                'deleteurl' => (new \moodle_url('/local/kid/pages/stagedoc_delete.php', [
                    'docid' => $file->id, 'sesskey' => sesskey(),
                ]))->out(false),
            ];
        }

        $data = [
            'summarymode' => false,
            'libelle' => format_string($this->stage->libelle),
            'studentnav' => student_nav_helper::build('stages', (int) $this->stage->id,
                (int) $this->stage->promotionid, $this->studentid),
            'steps' => $steppositions,
            '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/stages.php', ['stageid' => $this->stage->id]))->out(false),
            'docs' => $docs,
            'hasdocs' => !empty($docs),
            'uploadurl' => (new \moodle_url('/local/kid/pages/stagedoc_upload.php'))->out(false),
            'entryid' => (int) $entry->id,
            'sesskey' => sesskey(),
            'candocedit' => $canevaluate,
            'canimport' => $canimport,
            'templateoneurl' => (new \moodle_url('/local/kid/pages/stage_template.php', [
                'stageid' => $this->stage->id, 'studentid' => $this->studentid,
            ]))->out(false),
            'importurl' => (new \moodle_url('/local/kid/pages/stage_import.php', [
                'stageid' => $this->stage->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->stage->promotionid, 'format' => 'docx',
            ]))->out(false);
            $data['fichestudenturl_pdf'] = (new \moodle_url('/local/kid/pages/fiche_download.php', [
                'studentid' => $this->studentid, 'promotionid' => $this->stage->promotionid, 'format' => 'pdf',
            ]))->out(false);
        }
        return $data;
    }

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

}
