<?php
/**
 * Fichier  : api/search.php
 * Auteur   : KREMER Régis
 * Version  : 2.2.0
 * Date     : 2026-02-21
 * Description : API REST — Recherche globale multi-entités
 *
 * Changelog :
 *   v2.1.0 (2026-02-21) — Version initiale auditée et sécurisée
 *   v2.1.1 (2026-02-21) — Corrections sécurité (CSRF, MIME, session, migrateSuppliers)
 *   v2.2.0 (2026-02-21) — Permissions magasins, bons de commande, rapport d'écart,
 *                      import CSV, historique prix, bon de livraison multi-lignes
 */
require_once dirname(__DIR__).'/config.php';
startSession(); requireAuth();
$q=strtolower(trim($_GET['q']??''));
$lot = strtolower(trim($_GET['lot'] ?? ''));
$expiryBefore = trim($_GET['expiryBefore'] ?? '');
$expiryAfter  = trim($_GET['expiryAfter'] ?? '');
$expiredOnly  = ($_GET['expiredOnly'] ?? '') === '1';
if($q==='' && $lot==='' && $expiryBefore==='' && $expiryAfter==='' && !$expiredOnly){
    jsonResponse(['products'=>[],'warehouses'=>[],'movements'=>[]]);
}
$res=['products'=>[],'warehouses'=>[],'movements'=>[]];
if($q!==''){
    foreach(loadData('products') as $p)
        if(str_contains(strtolower($p['name']??''),$q)||str_contains(strtolower($p['sku']??''),$q)||str_contains(strtolower($p['barcode']??''),$q))
            $res['products'][]=$p;
    foreach(loadData('warehouses') as $w)
        if(str_contains(strtolower($w['name']??''),$q)||str_contains(strtolower($w['address']??''),$q))
            $res['warehouses'][]=$w;
}
$mvs=loadData('movements');usort($mvs,fn($a,$b)=>strcmp($b['date']??'',$a['date']??''));
$prods=loadData('products');
if($q!==''){
foreach(array_slice($mvs,0,200) as $m){
        $p=findById($prods,$m['productId']??0);
    if($q==='' || str_contains(strtolower($p['name']??''),$q)||str_contains(strtolower($m['reason']??''),$q)||str_contains(strtolower($m['site']??''),$q))
            {$m['_prodName']=$p['name']??'?';$m['_prodSku']=$p['sku']??'?';$res['movements'][]=$m;}
    }
}

// Advanced lot search in stock (returned in movements list as synthetic entries)
if($lot || $expiryBefore || $expiryAfter || $expiredOnly){
    $today = date('Y-m-d');
    $stock = loadData('stock');
    foreach($stock as $s){
        $lots = $s['lots'] ?? [];
        if(!is_array($lots)) continue;
        foreach($lots as $l){
            $ln = strtolower((string)($l['lotNumber']??''));
            $ed = (string)($l['expiryDate']??'');
            $qt = (int)($l['quantity']??0);
            if($qt<=0) continue;
            if($lot && !str_contains($ln,$lot)) continue;
            if($expiryBefore && $ed && $ed > $expiryBefore) continue;
            if($expiryAfter && $ed && $ed < $expiryAfter) continue;
            if($expiredOnly && (!$ed || $ed >= $today)) continue;
            $p = findById($prods,$s['productId']??0);
            $res['movements'][]=[
                'type'=>'lot',
                'date'=>($s['lastMovementAt'] ?? ''),
                'productId'=>$s['productId']??0,
                '_prodName'=>$p['name']??'?',
                '_prodSku'=>$p['sku']??'?',
                'warehouseId'=>$s['warehouseId']??0,
                'lotNumber'=>$l['lotNumber']??'',
                'expiryDate'=>$ed,
                'quantity'=>$qt,
            ];
        }
    }
}
jsonResponse($res);
?>
