<?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 Stages : sélecteur de stage, mode récapitulatif ("toute la
 * promotion", avancement + import/export) ou mode élève (grille de saisie +
 * documents + 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\niveau_repository;
use local_kid\local\stage_repository;
use local_kid\local\workflow_service;

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

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

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

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

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

    if ($studentid) {
        $entry = stage_repository::get_entry_for_student($stageid, $studentid);
        if (!$entry) {
            throw new \moodle_exception('invalidrecord', 'error');
        }
        $competencies = stage_repository::get_scope_competencies($stage);
        $results = stage_repository::get_results((int) $entry->id);
        $commenthistory = \local_kid\local\comment_history_service::get_for_entry('stage', (int) $entry->id);
        $historycontext = get_string('nav_stages', 'local_kid') . ' · '
            . \local_kid\local\promotion_repository::get_student_fullname($studentid);

        // A finalised dossier is read-only for everyone, evaluate_stage capability
        // included — matches "réouvrable comme le reste" (workflow_action=reopen
        // is the only way back to an editable state, not a permission override).
        $islocked = $entry->workflowstatus === workflow_service::STATUS_FINALISE;
        $readonly = $islocked || !access_helper::has_capability_or_teacher('local/kid:evaluate_stage', $context);

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

        $form = new local_kid_entry_grid_form($PAGE->url, [
            'competencies' => $competencies,
            'niveaux' => niveau_repository::get_all(),
            'results' => $results,
            'commenthistory' => $commenthistory,
            'historycontext' => $historycontext,
            'showglobalcomment' => true,
            'readonly' => $readonly,
        ]);
        $form->set_data([
            'entryid' => $entry->id,
            'commentaireglobal' => $entry->commentaireglobal,
            'origcommentaireglobal' => $entry->commentaireglobal,
            '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_stage', $context);
            if ($islocked) {
                // Defence in depth: the frozen form never posts a submit button, but
                // a hand-crafted POST could still reach here — refuse regardless.
                throw new \moodle_exception('error_entry_locked', 'local_kid');
            }
            $freshentry = stage_repository::get_entry((int) $data->entryid);
            $freshresults = stage_repository::get_results((int) $data->entryid);
            $conflict = entry_conflict_service::detect(
                $freshentry, $freshresults, (int) $data->expectedtimemodified,
                (array) $data->results, 'commentaireglobal',
                $data->origcommentaireglobal ?? '', $data->commentaireglobal ?? '');
            if ($conflict) {
                $competencylabels = [];
                foreach ($competencies as $competency) {
                    $competencylabels[$competency->id] = competency_repository::label($competency);
                }
                $conflict = entry_conflict_service::enrich($conflict, 'stage', (int) $data->entryid, $competencylabels,
                    get_string('stage_commentaire_global', 'local_kid'));
            } else {
                stage_repository::save_results((int) $data->entryid, (array) $data->results, $data->commentaireglobal ?? null, $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_stage_grid_page(new \local_kid\output\stage_grid_page($stage, $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_stage_grid_page(new \local_kid\output\stage_grid_page($stage, 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('stages'), $inner);
echo $OUTPUT->footer();
