<?php
if (ob_get_level() == 0) {
    ob_start();
}

// Fonction pour nettoyer le BOM et caractères invisibles
function clean_output($buffer) {
    $buffer = preg_replace('/^\x{FEFF}/u', '', $buffer);
    return ltrim($buffer ?? '', "\x00..\x1F");
}

register_shutdown_function(function() {
    $contents = ob_get_clean();
    echo clean_output($contents);
});
$_SESSION['etabchoix'] = $_COOKIE['LOGGED_ETAB'] ?? null;
require_once(dirname(__DIR__, 1) . '/config.php');
require_once(BASE_PATH . '/db/idl_connect.php');

if (!preg_match('/^[a-zA-Z0-9_]+$/', $prefix)) {
    http_response_code(400);
    exit("Préfixe invalide");
}

// normalisation
function normalize($str) {
    $str = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $str);
    return strtolower($str);
}

$suggestions = [];

$term = filter_input(INPUT_GET, 'term', FILTER_UNSAFE_RAW);
$term = is_string($term) ? trim($term) : '';

if ($term === '' || mb_strlen($term) < 1) {
    exit;
}

$mode = $_GET['mode'] ?? '';

$where = "WHERE nom LIKE :term";
$params = ['term' => $term . '%'];

if ($mode === 'eleves') {
    $where .= " AND categ = 1";
}
if ($term && strlen($term) >= 1) {

    $stmt = $pdo->prepare("
        SELECT nom, prenom, division, categ 
        FROM {$prefix}_eleves
        $where
        ORDER BY nom ASC
        LIMIT 20
    ");

    $stmt->execute($params);

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

        if ($row['categ'] == 1) {
            $eleve = $row['nom'] . ', ' . $row['prenom'] . ' (' . $row['division'] . ')';
        } else {
            $eleve = $row['nom'] . ', ' . $row['prenom'];
        }

        $suggestions[] = [
            'label' => $eleve,
            'value' => $eleve
        ];
    }
}

echo json_encode($suggestions, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
exit;
?>