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

/**
 * Resolves an élève's code_ena (section 21.4 du cahier des charges) —
 * jamais confondu avec le userid Moodle, un identifiant fonctionnel
 * distinct attendu par ADESI.
 *
 * Priorité : (1) champ de profil Moodle configuré (`local_kid/codeenafield`,
 * typiquement synchronisé depuis le SI via LDAP) ; (2) table de
 * correspondance manuelle `local_kid_codeena_map`.
 *
 * @package local_kid
 */

namespace local_kid\local;

defined('MOODLE_INTERNAL') || die();

class codeena_resolver {

    public static function resolve(int $userid): ?string {
        global $DB;

        $fieldname = trim((string) get_config('local_kid', 'codeenafield'));
        if ($fieldname !== '') {
            $sql = "SELECT d.data
                      FROM {user_info_data} d
                      JOIN {user_info_field} f ON f.id = d.fieldid
                     WHERE f.shortname = :shortname AND d.userid = :userid";
            $value = $DB->get_field_sql($sql, ['shortname' => $fieldname, 'userid' => $userid]);
            if ($value !== false && trim((string) $value) !== '') {
                return trim($value);
            }
        }

        $mapping = $DB->get_record('local_kid_codeena_map', ['userid' => $userid], '*', IGNORE_MISSING);
        return ($mapping && trim($mapping->codeena) !== '') ? trim($mapping->codeena) : null;
    }

    /**
     * Single point of truth for the ADESI export's code_ena — every row of
     * both adesi_export_service CSVs (niveaux, commentaires) and its
     * pre-export validation must go through this method, never resolve()
     * directly, so the provisional fallback below stays in exactly one
     * place.
     *
     * Provisional (section 21.4 du cahier des charges is not backed by a
     * real correspondance table on this instance yet): tries resolve()
     * first — the moment the real profile field or local_kid_codeena_map
     * table is populated for a student, this method starts returning that
     * value automatically, with zero change needed in adesi_export_service.php.
     * Only when resolve() has nothing does it fall back to the student's
     * email, then their name, purely as a stand-in identifier so the
     * export isn't permanently blocked while the real mapping is missing.
     *
     * TODO : remplacer par lecture table de correspondance code_ena — une
     * fois local_kid_codeena_map (déjà interrogée par resolve() ci-dessus)
     * systématiquement peuplée pour chaque élève, ce repli mail/nom devient
     * inutile : supprimer cette méthode et faire appeler resolve()
     * directement aux 3 endroits d'adesi_export_service.php qui l'utilisent.
     *
     * @return ?string null only if resolve() AND email AND name are all
     *         empty — callers must treat that as a hard error (see
     *         adesi_export_service::validate()'s adesi_error_codeena
     *         check), never silently emit a blank code_ena.
     */
    public static function resolve_for_adesi_export(int $userid, ?string $email, string $firstname, string $lastname): ?string {
        $resolved = self::resolve($userid);
        if ($resolved !== null) {
            return $resolved;
        }

        $email = trim((string) $email);
        if ($email !== '') {
            return $email;
        }

        $name = trim($lastname . ' ' . $firstname);
        return $name !== '' ? $name : null;
    }
}
