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

/**
 * Administration — dispatcher à 8 onglets (Promotions/Compétences/
 * Enseignements/Stages/CAPP/Niveaux/Export ADESI/Journal). Le dernier,
 * Journal, a rejoint cette page en tant qu'onglet (ancienne page de premier
 * niveau pages/journal.php, désormais un simple redirect) — il réutilise
 * {@see \local_kid\output\journal_page} sans le modifier.
 *
 * @package    local_kid
 */

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

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

require_login();
$context = context_system::instance();

$tab = optional_param('tab', admin_tabs::get_default(), PARAM_ALPHA);
if (!admin_tabs::is_valid($tab)) {
    $tab = admin_tabs::get_default();
}
// Chaque onglet a sa propre capacité (voir admin_tabs::CAPABILITIES) : un
// gestionnaire scindé (ex. manage_stage seul) ne peut dispatcher que vers
// les onglets pour lesquels il est habilité.
access_helper::require_capability_or_teacher(admin_tabs::get_capability($tab), $context);

/**
 * Renders the promotion-switcher form used by every promotion-scoped admin
 * tab, and resolves which promotion is active for this request — a GET
 * `promotionid` wins (and is persisted as the new displayed preference),
 * otherwise the stored/most-recent-active promotion resolves it.
 *
 * @return array{0: ?int, 1: string} [promotionid or null, rendered switcher HTML]
 */
function local_kid_resolve_promotion_switcher(string $tab): array {
    global $USER;

    $promotions = promotion_repository::get_active();
    if (empty($promotions)) {
        return [null, ''];
    }

    $requested = optional_param('promotionid', 0, PARAM_INT);
    if ($requested && promotion_repository::get($requested)) {
        promotion_selector::set_selected($requested, $USER->id);
        $promotionid = $requested;
    } else {
        $resolved = promotion_selector::resolve($USER->id);
        $promotionid = $resolved ? (int) $resolved->id : (int) reset($promotions)->id;
    }

    $options = [];
    foreach ($promotions as $promotion) {
        $options[$promotion->id] = format_string($promotion->name);
    }

    $form = new local_kid_promotion_switch_form(
        new moodle_url('/local/kid/pages/admin.php'),
        ['hidden' => ['tab' => $tab], 'promotions' => $options]
    );
    $form->set_data(['promotionid' => $promotionid]);

    return [$promotionid, $form->render()];
}

/**
 * Same switcher widget as local_kid_resolve_promotion_switcher() (identical
 * moodleform/rendering, so the Compétences tab's "choose a promotion"
 * control looks and behaves exactly like Évaluations/Stages/CAPP/Export
 * ADESI's) but bound to competences_promotion_selector (sélecteur B)
 * instead of promotion_selector (sélecteur A) — changing it still never
 * touches the plugin-wide "promotion affichée". Deliberately duplicates
 * local_kid_resolve_promotion_switcher() rather than parameterising it,
 * same rationale as competences_promotion_selector itself: the two states
 * must never be able to accidentally share a code path.
 *
 * @return array{0: ?int, 1: string} [promotionid or null, rendered switcher HTML]
 */
function local_kid_resolve_competences_promotion_switcher(): array {
    global $USER;

    $promotions = promotion_repository::get_active();
    if (empty($promotions)) {
        return [null, ''];
    }

    $requested = optional_param('promotionid', 0, PARAM_INT);
    if ($requested && promotion_repository::get($requested)) {
        \local_kid\local\competences_promotion_selector::set_selected($requested, $USER->id);
        $promotionid = $requested;
    } else {
        $resolved = \local_kid\local\competences_promotion_selector::resolve($USER->id);
        $promotionid = $resolved ? (int) $resolved->id : (int) reset($promotions)->id;
    }

    $options = [];
    foreach ($promotions as $promotion) {
        $options[$promotion->id] = format_string($promotion->name);
    }

    $form = new local_kid_promotion_switch_form(
        new moodle_url('/local/kid/pages/admin.php'),
        ['hidden' => ['tab' => 'competences'], 'promotions' => $options]
    );
    $form->set_data(['promotionid' => $promotionid]);

    return [$promotionid, $form->render()];
}

$urlparams = ['tab' => $tab];
if ($tab === 'journal') {
    $urlparams += array_filter([
        'userid' => optional_param('userid', 0, PARAM_INT),
        'promotionid' => optional_param('promotionid', 0, PARAM_INT),
        'domain' => optional_param('domain', '', PARAM_ALPHA),
        'action' => optional_param('action', '', PARAM_ALPHANUMEXT),
        'studentquery' => optional_param('studentquery', '', PARAM_TEXT),
        'datefrom' => optional_param('datefrom', '', PARAM_TEXT),
        'dateto' => optional_param('dateto', '', PARAM_TEXT),
        'sort' => optional_param('sort', '', PARAM_ALPHA),
        'dir' => optional_param('dir', '', PARAM_ALPHA),
        'page' => optional_param('page', 0, PARAM_INT),
    ]);
}
$PAGE->set_url('/local/kid/pages/admin.php', $urlparams);
$PAGE->set_context($context);
$PAGE->set_pagelayout('standard');
$PAGE->set_title(get_string('page_admin', 'local_kid'));
local_kid_setup_page($PAGE);

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

switch ($tab) {
    case 'promotions':
        $inner = $renderer->render_promotions_admin_page(new \local_kid\output\promotions_admin_page());
        break;

    case 'competences':
        [$promotionid, $switcher] = local_kid_resolve_competences_promotion_switcher();
        if (!$promotionid) {
            $inner = $renderer->render_from_template('local_kid/empty_state', [
                'message' => get_string('no_promotion_yet', 'local_kid'),
            ]);
        } else {
            $inner = $switcher . $renderer->render_competencies_admin_page(new \local_kid\output\competencies_admin_page($promotionid));
        }
        break;

    case 'niveaux':
        $inner = $renderer->render_niveaux_admin_page(new \local_kid\output\niveaux_admin_page());
        break;

    case 'evaluations':
        [$promotionid, $switcher] = local_kid_resolve_promotion_switcher($tab);
        if (!$promotionid) {
            $inner = $renderer->render_from_template('local_kid/empty_state', [
                'message' => get_string('no_promotion_yet', 'local_kid'),
            ]);
        } else {
            $inner = $switcher . $renderer->render_evaluations_admin_page(new \local_kid\output\evaluations_admin_page($promotionid));
        }
        break;

    case 'stages':
        [$promotionid, $switcher] = local_kid_resolve_promotion_switcher($tab);
        if (!$promotionid) {
            $inner = $renderer->render_from_template('local_kid/empty_state', [
                'message' => get_string('no_promotion_yet', 'local_kid'),
            ]);
        } else {
            $inner = $switcher . $renderer->render_stages_admin_page(new \local_kid\output\stages_admin_page($promotionid));
        }
        break;

    case 'capp':
        [$promotionid, $switcher] = local_kid_resolve_promotion_switcher($tab);
        if (!$promotionid) {
            $inner = $renderer->render_from_template('local_kid/empty_state', [
                'message' => get_string('no_promotion_yet', 'local_kid'),
            ]);
        } else {
            $inner = $switcher . $renderer->render_capp_admin_page(new \local_kid\output\capp_admin_page($promotionid));
        }
        break;

    case 'export':
        [$promotionid, $switcher] = local_kid_resolve_promotion_switcher($tab);
        if (!$promotionid) {
            $inner = $renderer->render_from_template('local_kid/empty_state', [
                'message' => get_string('no_promotion_yet', 'local_kid'),
            ]);
        } else {
            $sessionid = optional_param('sessionid', 0, PARAM_INT);
            $inner = $switcher . $renderer->render_adesi_export_page(new \local_kid\output\adesi_export_page($promotionid, $sessionid));
        }
        break;

    case 'journal':
        $journalfilters = [
            'userid' => optional_param('userid', 0, PARAM_INT),
            'promotionid' => optional_param('promotionid', 0, PARAM_INT),
            'domain' => optional_param('domain', '', PARAM_ALPHA),
            'action' => optional_param('action', '', PARAM_ALPHANUMEXT),
            'studentquery' => optional_param('studentquery', '', PARAM_TEXT),
        ];
        $journaldatefromraw = optional_param('datefrom', '', PARAM_TEXT);
        $journaldatetoraw = optional_param('dateto', '', PARAM_TEXT);
        $journalfilters['datefrom'] = $journaldatefromraw !== '' ? strtotime($journaldatefromraw . ' 00:00:00') ?: 0 : 0;
        $journalfilters['dateto'] = $journaldatetoraw !== '' ? strtotime($journaldatetoraw . ' 23:59:59') ?: 0 : 0;
        $journalsort = optional_param('sort', 'timecreated', PARAM_ALPHA);
        $journaldir = optional_param('dir', 'DESC', PARAM_ALPHA);
        $journalpage = optional_param('page', 0, PARAM_INT);
        $inner = $renderer->render_journal_page(new \local_kid\output\journal_page($journalfilters, $journalsort, $journaldir, $journalpage));
        break;

    default:
        $inner = $renderer->render_from_template('local_kid/empty_state', [
            'message' => get_string('placeholder_notice', 'local_kid'),
        ]);
        break;
}

$adminshell = $renderer->render_admin_shell(
    get_string('page_admin', 'local_kid'),
    '',
    admin_tabs::get_tab_items($tab),
    $inner
);

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