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

/**
 * Écran principal Évaluations : sélecteur d'éval, mode récapitulatif ou
 * mode élève (grille de saisie + workflow).
 *
 * @package    local_kid
 */

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

use local_kid\local\access_helper;
use local_kid\local\competency_repository;
use local_kid\local\entry_conflict_service;
use local_kid\local\eval_repository;
use local_kid\local\niveau_repository;

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

$evalid = optional_param('evalid', 0, PARAM_INT);
$studentid = optional_param('studentid', 0, PARAM_INT) ?: null;

$PAGE->set_url('/local/kid/pages/evaluations.php', array_filter(['evalid' => $evalid, 'studentid' => $studentid]));
$PAGE->set_context($context);
$PAGE->set_pagelayout('standard');
$PAGE->set_title(get_string('page_evaluations', 'local_kid'));
local_kid_setup_page($PAGE);

$renderer = $PAGE->get_renderer('local_kid');

if (!$evalid) {
    // No evaluation selected: let the teacher pick which active eval to fill in.
    $promotion = \local_kid\local\promotion_selector::resolve($USER->id);
    $inner = $promotion
        ? $renderer->render_evaluations_picker_page(new \local_kid\output\evaluations_picker_page((int) $promotion->id))
        : $renderer->render_from_template('local_kid/empty_state', ['message' => get_string('no_promotion_yet', 'local_kid')]);
} else {
    $eval = eval_repository::get($evalid);
    if (!$eval) {
        throw new \moodle_exception('invalidrecord', 'error');
    }
    eval_repository::ensure_entries($evalid, (int) $eval->promotionid, $USER->id);

    if ($studentid) {
        $entry = eval_repository::get_entry_for_student($evalid, $studentid);
        if (!$entry) {
            throw new \moodle_exception('invalidrecord', 'error');
        }
        $competencies = eval_repository::get_competencies($evalid);
        $results = eval_repository::get_results((int) $entry->id);
        $commenthistory = \local_kid\local\comment_history_service::get_for_entry('eval', (int) $entry->id);
        $historycontext = get_string('nav_evaluations', 'local_kid') . ' · '
            . \local_kid\local\promotion_repository::get_student_fullname($studentid);

        $selfurl = new moodle_url('/local/kid/pages/evaluations.php', ['evalid' => $evalid, 'studentid' => $studentid]);

        $form = new local_kid_entry_grid_form($PAGE->url, [
            'competencies' => $competencies,
            'niveaux' => niveau_repository::get_all(),
            'results' => $results,
            'commenthistory' => $commenthistory,
            'historycontext' => $historycontext,
            'readonly' => !access_helper::has_capability_or_teacher('local/kid:evaluate_evaluation', $context),
        ]);
        $form->set_data([
            'entryid' => $entry->id,
            'expectedtimemodified' => $entry->timemodified,
            'returnurl' => $selfurl->out_as_local_url(false),
        ]);

        $conflict = null;
        if ($data = $form->get_data()) {
            access_helper::require_capability_or_teacher('local/kid:evaluate_evaluation', $context);
            $freshentry = eval_repository::get_entry((int) $data->entryid);
            $freshresults = eval_repository::get_results((int) $data->entryid);
            $conflict = entry_conflict_service::detect(
                $freshentry, $freshresults, (int) $data->expectedtimemodified,
                (array) $data->results, null, null, null);
            if ($conflict) {
                $competencylabels = [];
                foreach ($competencies as $competency) {
                    $competencylabels[$competency->id] = competency_repository::label($competency);
                }
                $conflict = entry_conflict_service::enrich($conflict, 'eval', (int) $data->entryid, $competencylabels);
            } else {
                eval_repository::save_results((int) $data->entryid, (array) $data->results, $USER->id);
                $returnurl = $data->returnurl ? new moodle_url($data->returnurl) : $selfurl;
                redirect($returnurl, get_string('changessaved'), null, \core\output\notification::NOTIFY_SUCCESS);
            }
        }

        $inner = $renderer->render_eval_grid_page(new \local_kid\output\eval_grid_page($eval, $studentid, $form->render(), $conflict));
        $PAGE->requires->js_call_amd('local_kid/student_nav', 'init');
        $PAGE->requires->js_call_amd('local_kid/unsaved_guard', 'init');
        $PAGE->requires->js_call_amd('local_kid/conflict_view', 'init');
        $PAGE->requires->js_call_amd('local_kid/comment_history', 'init');
    } else {
        $inner = $renderer->render_eval_grid_page(new \local_kid\output\eval_grid_page($eval, null));
        $PAGE->requires->js_call_amd('local_kid/bulk_actions', 'init');
    }
}

echo $OUTPUT->header();
echo $renderer->render_shell(\local_kid\local\nav_helper::get_sidebar_items('evaluations'), $inner);
echo $OUTPUT->footer();
