<?php
$seleve = null;
if (isset($_POST['eleve'])) {
    $seleve = trim($_POST['eleve']);
} elseif (isset($_POST['eleve'.$i])) {
    $seleve = trim($_POST['eleve'.$i]);
} elseif (isset($_SESSION['eleve'])) {
    $seleve = $_SESSION['eleve'];
}
if (!$seleve) {
    return;
}

$eleve_info = false;

if (preg_match('/^([^,]+),\s*([^(]+)\(([^)]+)\)$/', $seleve, $matches)) {

    $stmt = $pdo->prepare("
        SELECT *
        FROM {$prefix}_eleves
        WHERE nom = :nom
        AND prenom = :prenom
        AND division = :division
        LIMIT 1
    ");

    $stmt->execute([
        ':nom' => trim($matches[1]),
        ':prenom' => trim($matches[2]),
        ':division' => trim($matches[3])
    ]);

    $eleve_info = $stmt->fetch(PDO::FETCH_ASSOC);
}

elseif (preg_match('/^([^,]+),\s*(.+)$/', $seleve, $matches)) {

    $stmt = $pdo->prepare("
        SELECT *
        FROM {$prefix}_eleves
        WHERE nom = :nom
        AND prenom = :prenom
        AND categ = 2
        LIMIT 1
    ");

    $stmt->execute([
        ':nom' => trim($matches[1]),
        ':prenom' => trim($matches[2])
    ]);

    $eleve_info = $stmt->fetch(PDO::FETCH_ASSOC);
}

if (!$eleve_info) {

    include('elevecode_select.php');

    $_SESSION['eleves_id'] = $eleve_id ?? null;

    return;
}

$eleve_id = $eleve_info['eleves_id'];
$eleve_div = $eleve_info['division'];
$eleve_sex = $eleve_info['sexe'];
$eleve_naissance = $eleve_info['naissance'];

$_SESSION['eleves_id'] = $eleve_id;
$_SESSION['categ'] = $eleve_info['categ'];
?>
