<?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 Conseil d'apprentissage (CAPP) : sélecteur de session,
 * mode récapitulatif ("toute la promotion") ou mode élève (grille de saisie
 * avec colonnes consultatives Enseignements/Stages + appréciation globale +
 * workflow).
 *
 * @package    local_kid
 */

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

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

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

$sessionid = optional_param('sessionid', 0, PARAM_INT);
$studentid = optional_param('studentid', 0, PARAM_INT) ?: null;
$mode = optional_param('mode', 'bilan', PARAM_ALPHA);

$PAGE->set_url('/local/kid/pages/capp.php', array_filter(['sessionid' => $sessionid, 'studentid' => $studentid, 'mode' => $mode !== 'bilan' ? $mode : null]));
$PAGE->set_context($context);
$PAGE->set_pagelayout('standard');
$PAGE->set_title(get_string('page_capp', 'local_kid'));
local_kid_setup_page($PAGE);

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

if (!$sessionid) {
    // No session selected: let the teacher pick which active CAPP session to fill in.
    $promotion = \local_kid\local\promotion_selector::resolve($USER->id);
    $inner = $promotion
        ? $renderer->render_capp_picker_page(new \local_kid\output\capp_picker_page((int) $promotion->id))
        : $renderer->render_from_template('local_kid/empty_state', ['message' => get_string('no_promotion_yet', 'local_kid')]);
} else {
    $session = capp_repository::get_session($sessionid);
    if (!$session) {
        throw new \moodle_exception('invalidrecord', 'error');
    }
    capp_repository::ensure_entries($sessionid, $USER->id);

    if ($studentid) {
        $entry = capp_repository::get_entry_for_student($sessionid, $studentid);
        if (!$entry) {
            throw new \moodle_exception('invalidrecord', 'error');
        }
        $competencies = competency_repository::get_active_for_promotion((int) $session->promotionid);
        capp_repository::seed_commentaires_from_sources($sessionid, $studentid, (int) $entry->id, array_map(fn($c) => (int) $c->id, $competencies));
        $results = capp_repository::get_results((int) $entry->id);

        $competencyids = array_map(fn($c) => (int) $c->id, $competencies);

        // Every CAPP session strictly before this one in the promotion's
        // ordered sequence (same ordering the "Récupérer les niveaux" link
        // already relies on via get_previous_session()/
        // get_active_sessions_for_promotion()) — feeds the "Niveau CAPP N"
        // lines below. Empty (and no lines shown) both on the promotion's
        // first CAPP session and if this session isn't in the active list
        // at all (same masking as get_previous_session()).
        $history = capp_repository::get_niveau_history((int) $session->promotionid, $studentid, $competencyids);
        $historysessionids = array_map(fn($s) => (int) $s->id, $history['sessions']);
        $currentindex = array_search($sessionid, $historysessionids, true);
        $priorsessions = $currentindex !== false ? array_slice($history['sessions'], 0, $currentindex) : [];

        $priorlinesbycompetency = [];
        foreach ($competencyids as $competencyid) {
            $lines = [];
            foreach ($priorsessions as $priorsession) {
                $lines[] = [
                    'shortname' => capp_repository::short_name($priorsession),
                    'niveau' => $history['niveaux'][$competencyid][$priorsession->id] ?? null,
                ];
            }
            $priorlinesbycompetency[$competencyid] = $lines;
        }

        $competencylabels = [];
        $consultative = [];
        foreach ($competencies as $competency) {
            $competencylabels[$competency->id] = competency_repository::label($competency);
            $consultative[$competency->id] = [
                'eval' => capp_repository::get_consultative_eval_data($sessionid, $studentid, (int) $competency->id),
                'stage' => capp_repository::get_consultative_stage_data($sessionid, $studentid, (int) $competency->id),
                'priors' => $priorlinesbycompetency[$competency->id] ?? [],
            ];
        }

        $commenthistory = \local_kid\local\comment_history_service::get_for_entry('capp', (int) $entry->id);
        $historycontext = get_string('nav_capp', 'local_kid') . ' · '
            . \local_kid\local\promotion_repository::get_student_fullname($studentid);

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

        $form = new local_kid_capp_grid_form($PAGE->url, [
            'competencies' => $competencylabels,
            'niveaux' => niveau_repository::get_all(),
            'results' => $results,
            'consultative' => $consultative,
            'commenthistory' => $commenthistory,
            'historycontext' => $historycontext,
            'readonly' => !access_helper::has_capability_or_teacher('local/kid:evaluate_capp', $context),
        ]);
        $form->set_data([
            'entryid' => $entry->id,
            'appreciationglobale' => $entry->appreciationglobale,
            'origappreciationglobale' => $entry->appreciationglobale,
            '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_capp', $context);
            $freshentry = capp_repository::get_entry((int) $data->entryid);
            $freshresults = capp_repository::get_results((int) $data->entryid);
            $conflict = entry_conflict_service::detect(
                $freshentry, $freshresults, (int) $data->expectedtimemodified,
                (array) $data->results, 'appreciationglobale',
                $data->origappreciationglobale ?? '', $data->appreciationglobale ?? '');
            if ($conflict) {
                $conflict = entry_conflict_service::enrich($conflict, 'capp', (int) $data->entryid, $competencylabels,
                    get_string('capp_appreciation_globale', 'local_kid'));
            } else {
                capp_repository::save_results((int) $data->entryid, (array) $data->results, $data->appreciationglobale, $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_capp_grid_page(new \local_kid\output\capp_grid_page($session, $studentid, $form->render(), $mode, $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_capp_grid_page(new \local_kid\output\capp_grid_page($session, null, '', $mode));
        $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('capp'), $inner);
echo $OUTPUT->footer();
