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

/**
 * Tableau de bord — 3 onglets : "Vue d'ensemble" (scopée à une promotion),
 * "Vue globale" (réservée aux détenteurs de local/kid:manage, toutes
 * promotions à la fois — l'écran d'atterrissage quand aucune promotion
 * n'existe/n'est encore sélectionnée, pour qu'un admin n'arrive jamais sur
 * une impasse au premier usage), et "Comparateur de bilans" — ce dernier
 * onglet appelle directement {@see \local_kid\output\comparateur_page}
 * (ancienne page de premier niveau pages/comparateur.php, désormais un
 * simple redirect), jamais de vue dupliquée.
 *
 * Les 5 anciens sous-onglets morts (Compétences, Stages, Évaluations, CAPP,
 * Évolution, retirés le 2026-08-13) redirigent toujours vers l'onglet
 * Comparateur, pour ne pas casser un favori navigateur existant.
 *
 * @package local_kid
 */

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

use local_kid\local\access_helper;
use local_kid\local\nav_helper;
use local_kid\local\promotion_repository;
use local_kid\local\promotion_selector;

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

$promotionid = optional_param('promotionid', 0, PARAM_INT);
if (!$promotionid) {
    $resolved = promotion_selector::resolve((int) $USER->id);
    $promotionid = $resolved ? (int) $resolved->id : 0;
}

$requestedtab = optional_param('tab', '', PARAM_ALPHA);
if (in_array($requestedtab, ['competences', 'stages', 'evaluations', 'capp', 'evolution'], true)) {
    redirect(new moodle_url('/local/kid/pages/dashboard.php', array_filter(['tab' => 'comparateur', 'promotionid' => $promotionid])));
}

$canmanage = has_capability('local/kid:manage', $context);
$defaulttab = $promotionid ? 'apercu' : ($canmanage ? 'global' : 'apercu');

$validtabs = ['apercu', 'comparateur'];
if ($canmanage) {
    array_unshift($validtabs, 'global');
}

$tab = optional_param('tab', $defaulttab, PARAM_ALPHA);
if (!in_array($tab, $validtabs, true)) {
    $tab = $defaulttab;
}

$urlparams = ['tab' => $tab, 'promotionid' => $promotionid];
if ($tab === 'comparateur') {
    $urlparams += array_filter([
        'onlyobserved' => optional_param('onlyobserved', 0, PARAM_BOOL) ? 1 : 0,
        'showcomments' => optional_param('showcomments', 1, PARAM_BOOL) ? 1 : 0,
    ]);
}
$PAGE->set_url('/local/kid/pages/dashboard.php', $urlparams);
$PAGE->set_context($context);
$PAGE->set_pagelayout('standard');
$PAGE->set_title(get_string('page_dashboard', 'local_kid'));
local_kid_setup_page($PAGE);

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

if (!$promotionid && !in_array($tab, ['global', 'comparateur'], true)) {
    $inner = $renderer->render_from_template('local_kid/empty_state', [
        'message' => get_string('no_promotion_yet', 'local_kid'),
    ]);
} else if ($tab === 'global') {
    $inner = $renderer->render_dashboard_global_page(new \local_kid\output\dashboard_global_page());
} else if ($tab === 'comparateur') {
    $comparateurfilters = [
        'promotionid' => $promotionid,
        'studentids' => optional_param_array('studentids', [], PARAM_INT),
        'sourcekeys' => optional_param_array('sourcekeys', [], PARAM_ALPHANUMEXT),
        'competencyids' => optional_param_array('competencyids', [], PARAM_INT),
        'niveaucodes' => optional_param_array('niveaucodes', [], PARAM_ALPHANUMEXT),
        'onlyobserved' => (bool) optional_param('onlyobserved', 0, PARAM_BOOL),
        'showcomments' => (bool) optional_param('showcomments', 1, PARAM_BOOL),
    ];
    $PAGE->requires->js_call_amd('local_kid/comparateur', 'init');
    $inner = $renderer->render_comparateur_page(new \local_kid\output\comparateur_page($comparateurfilters, (int) $USER->id));
} else {
    $inner = $renderer->render_dashboard_overview_page(new \local_kid\output\dashboard_overview_page($promotionid));
}

$tabitems = [];
foreach ($validtabs as $tabid) {
    $tabitems[] = [
        'label' => get_string($tabid === 'global' ? 'dashboard_tab_global' : 'dashboard_tab_' . $tabid, 'local_kid'),
        'url' => (new moodle_url('/local/kid/pages/dashboard.php', ['tab' => $tabid, 'promotionid' => $promotionid]))->out(false),
        'isactive' => $tabid === $tab,
    ];
}

if ($tab === 'global') {
    $title = get_string('dashboard_global_title', 'local_kid');
    $subtitle = get_string('dashboard_global_subtitle', 'local_kid');
} else if ($tab === 'comparateur') {
    $title = get_string('page_comparateur', 'local_kid');
    $subtitle = '';
} else {
    $title = get_string('dashboard_title', 'local_kid', $promotionid ? format_string(promotion_repository::get($promotionid)->name) : '');
    $subtitle = get_string('dashboard_subtitle', 'local_kid');
}

$shell = $renderer->render_admin_shell($title, $subtitle, $tabitems, $inner);

echo $OUTPUT->header();
echo $renderer->render_shell(nav_helper::get_sidebar_items('dashboard'), $shell);
echo $OUTPUT->footer();
