<br />
<b>Warning</b>:  Undefined variable $auth in <b>/home/pevo0181/public_html/pia-soft.com/cleania/routes/index.php</b> on line <b>542</b><br />
<br />
<b>Warning</b>:  Trying to access array offset on value of type null in <b>/home/pevo0181/public_html/pia-soft.com/cleania/routes/index.php</b> on line <b>542</b><br />
<?php
// ============================================================
//  POST /api/select_enfant.php
//  Body JSON: { "eleve_id": X, "telephone": "674...", "matricule": "PIA..." }
//  Vérifie que le matricule correspond à l'enfant choisi
// ============================================================
require_once __DIR__ . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonError('Méthode non autorisée', 405);

$body      = json_decode(file_get_contents('php://input'), true);
$eleve_id  = (int)($body['eleve_id']  ?? 0);
$telephone = preg_replace('/[^0-9]/', '', $body['telephone'] ?? '');
$telephone = substr($telephone, -9);
$matricule = strtoupper(trim($body['matricule'] ?? ''));

if (!$eleve_id || strlen($telephone) < 8) jsonError('Données invalides');
if (!$matricule) jsonError('Matricule requis');

$db = getDB();

// Vérifier que l'enfant appartient à ce parent ET que le matricule est correct
$stmt = $db->prepare("
    SELECT e.id, e.matricule, e.nom, e.prenom, e.sexe, e.photo,
           e.nom_parent, e.telephone_parent
    FROM eleves e
    WHERE e.id = ?
      AND e.matricule = ?
      AND e.statut = 'actif'
      AND (
          RIGHT(REGEXP_REPLACE(e.telephone_parent,  '[^0-9]', ''), 9) = ?
          OR RIGHT(REGEXP_REPLACE(e.telephone_parent2, '[^0-9]', ''), 9) = ?
      )
    LIMIT 1
");
$stmt->execute([$eleve_id, $matricule, $telephone, $telephone]);
$eleve = $stmt->fetch();

if (!$eleve) jsonError('Matricule incorrect pour cet enfant', 401);

// Inscription active
$stmt2 = $db->prepare("
    SELECT i.id as inscription_id, c.nom as classe_nom, c.cycle_nom,
           n.nom_fr as niveau_nom, a.libelle as annee_scolaire
    FROM inscriptions i
    JOIN classes c ON c.id = i.classe_id
    JOIN niveaux n ON n.id = c.niveau_id
    JOIN annees_scolaires a ON a.id = i.annee_id
    WHERE i.eleve_id = ?
    ORDER BY i.annee_id DESC LIMIT 1
");
$stmt2->execute([$eleve['id']]);
$inscription = $stmt2->fetch();

$token = jwt_encode([
    'eleve_id'       => $eleve['id'],
    'matricule'      => $eleve['matricule'],
    'telephone'      => $telephone,
    'inscription_id' => $inscription['inscription_id'] ?? null,
]);

jsonOk([
    'token' => $token,
    'eleve' => [
        'id'        => $eleve['id'],
        'matricule' => $eleve['matricule'],
        'nom'       => $eleve['nom'],
        'prenom'    => $eleve['prenom'],
        'sexe'      => $eleve['sexe'],
        'photo'     => $eleve['photo'],
        'classe'    => $inscripti