<?php
/**
 * Fichier  : api/ean.php
 * Auteur   : KREMER Régis
 * Version  : 2.4.0
 * Date     : 2026-02-26
 * Description : API REST — Lookup produit par EAN/code-barres (Lot 4)
 */
require_once dirname(__DIR__).'/config.php';
startSession(); requireAuth();
requirePerm('products.read');

$code = trim($_GET['code'] ?? '');
if($code==='') jsonError('Code manquant.');

$codeLower = strtolower($code);
foreach(loadData('products') as $p){
    $barcode = (string)($p['barcode'] ?? '');
    if($barcode !== '' && $barcode === $code) jsonResponse($p);
    $eans = $p['eans'] ?? [];
    if(is_string($eans)) $eans = json_decode($eans,true) ?: [];
    if(is_array($eans)){
        foreach($eans as $e){
            if((string)$e === $code) jsonResponse($p);
        }
    }
    // Some scanners include leading zeros: try normalized compare
    if($barcode !== '' && ltrim($barcode,'0') === ltrim($code,'0')) jsonResponse($p);
    if(is_array($eans)){
        foreach($eans as $e){
            if(ltrim((string)$e,'0') === ltrim($code,'0')) jsonResponse($p);
        }
    }
}
jsonError('Produit introuvable.',404);
