// Résolution automatique FEFO améliorée et robuste pour chaque ligne de prescription $nomMedBrut = trim($ligne['medicament']); // Nettoyage pour isoler le nom principal (ex: extraction avant la parenthèse si présente) $termeRecherche = trim(explode('(', $nomMedBrut)[0]); $sqlRecherche = " SELECT a.id AS article_id, a.code_article, a.designation, a.forme_dosage, a.famille, a.prix_unitaire_vente, a.stock_actuel, COALESCE(ref.unite_dispensation_min, 'Unité') AS unite_dispensation_min, COALESCE(ref.coefficient_conversion, 1) AS coefficient_conversion, l.id AS lot_id, l.numero_lot, l.quantite_restante AS stock_lot, l.date_peremption FROM pharmacie_articles a INNER JOIN pharmacie_lots l ON a.id = l.article_id AND l.quantite_restante > 0 LEFT JOIN pharmacie_referentiel_medicaments ref ON a.code_article = ref.code_national OR a.designation = ref.nom_commercial WHERE a.est_actif = 1 AND (a.designation LIKE ? OR a.code_article LIKE ? OR ref.dci LIKE ?) ORDER BY l.date_peremption ASC LIMIT 1 "; $stmtSearch = $pdo->prepare($sqlRecherche); $termePattern = "%$termeRecherche%"; $stmtSearch->execute([$termePattern, $termePattern, $termePattern]); $artDispo = $stmtSearch->fetch(PDO::FETCH_ASSOC);