<?php
/**
 * Fichier  : api/stock.php
 * Auteur   : KREMER Régis
 * Version  : 2.3.0
 * Date     : 2026-02-26
 * Description : API REST — Consultation et mise à jour du stock par produit/magasin
 *
 * 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,
 *   v2.3.0 (2026-02-26) — Lot 1: permissions fines + emplacements internes (locations).
 *                      import CSV, historique prix, bon de livraison multi-lignes
 */
require_once dirname(__DIR__).'/config.php';
startSession(); requireAuth();
$method=$_SERVER['REQUEST_METHOD'];
$body=json_decode(file_get_contents('php://input'),true)??[];
if($method!=='GET') csrfCheck();
switch($method){
case 'GET':
    requirePerm('stock.read');
    $stock=loadData('stock');
    // Permission: filter by warehouses accessible to current user
    $allowedWh = getUserAllowedWarehouses();
    if($allowedWh !== null) $stock = array_values(array_filter($stock, fn($s)=>in_array((int)($s['warehouseId']??0),$allowedWh)));
    if(isset($_GET['productId']))   $stock=array_filter($stock,fn($s)=>(string)($s['productId']??'')===$_GET['productId']);
    if(isset($_GET['warehouseId'])) $stock=array_filter($stock,fn($s)=>(string)($s['warehouseId']??'')===$_GET['warehouseId']);
    // Advanced lot/expiry filters (fail-soft)
    $lot = trim((string)($_GET['lot'] ?? ''));
    $expiryBefore = trim((string)($_GET['expiryBefore'] ?? '')); // YYYY-MM-DD
    $expiryAfter  = trim((string)($_GET['expiryAfter'] ?? ''));
    $expiredOnly  = ($_GET['expiredOnly'] ?? '') === '1';
    if($lot || $expiryBefore || $expiryAfter || $expiredOnly){
        $today = date('Y-m-d');
        $stock = array_filter($stock, function($s) use($lot,$expiryBefore,$expiryAfter,$expiredOnly,$today){
            $lots = $s['lots'] ?? [];
            if(!is_array($lots) || count($lots)===0) return false;
            foreach($lots as $l){
                if(((int)($l['quantity']??0))<=0) continue;
                if($lot && !str_contains(strtolower($l['lotNumber']??''), strtolower($lot))) continue;
                $ed = (string)($l['expiryDate']??'');
                if($expiryBefore && $ed && $ed > $expiryBefore) continue;
                if($expiryAfter && $ed && $ed < $expiryAfter) continue;
                if($expiredOnly && (!$ed || $ed >= $today)) continue;
                return true;
            }
            return false;
        });
    }
    // Lot 1: hide lot costs if permission missing
    if(!hasPerm('price.read')){
        foreach($stock as &$s){
            if(isset($s['lots']) && is_array($s['lots'])){
                foreach($s['lots'] as &$l){ unset($l['unitCost']); }
                unset($l);
            }
            if(isset($s['locations']) && is_array($s['locations'])){
                foreach($s['locations'] as &$loc){
                    if(isset($loc['lots']) && is_array($loc['lots'])){
                        foreach($loc['lots'] as &$ll){ unset($ll['unitCost']); }
                        unset($ll);
                    }
                }
                unset($loc);
            }
        }
        unset($s);
    }
    jsonResponse(array_values($stock));
case 'POST':
    requireAdmin();
    $pid=$body['productId']??null;$wid=$body['warehouseId']??null;
    if(!$pid||!$wid) jsonError('productId+warehouseId requis.');
    $stock=loadData('stock');$found=false;
    foreach($stock as &$s){
        if((string)($s['productId']??'')===(string)$pid&&(string)($s['warehouseId']??'')===(string)$wid){
            if(isset($body['quantity'])) $s['quantity']=max(0,(int)$body['quantity']);
            if(isset($body['minStock'])) $s['minStock']=$body['minStock']!==null&&$body['minStock']!==''?(int)$body['minStock']:null;
            if(isset($body['maxStock'])) $s['maxStock']=$body['maxStock']!==null&&$body['maxStock']!==''?(int)$body['maxStock']:null;
            if(array_key_exists('safetyStock',$body)) $s['safetyStock']=$body['safetyStock']!==null&&$body['safetyStock']!==''?(int)$body['safetyStock']:null;
            if(array_key_exists('picking',$body))    $s['picking']=trim((string)$body['picking']);
            if(array_key_exists('location',$body))   $s['location']=trim((string)$body['location']);
            if(array_key_exists('rack',$body))        $s['rack']=trim((string)$body['rack']);
            if(array_key_exists('shelf',$body))       $s['shelf']=trim((string)$body['shelf']);
            if(array_key_exists('locationId',$body))  $s['locationId']=$body['locationId'] ? (int)$body['locationId'] : null;
            $s['updatedAt']=date('c');$found=true;break;
        }
    }
    if(!$found) $stock[]=([
        'id'=>genId(),
        'productId'=>(int)$pid,
        'warehouseId'=>(int)$wid,
        'quantity'=>max(0,(int)($body['quantity']??0)),
        'minStock'=>$body['minStock']??null,
        'maxStock'=>$body['maxStock']??null,
        'safetyStock'=>$body['safetyStock']??null,
        'picking'=>trim((string)($body['picking']??'')),
        'location'=>trim((string)($body['location']??'')),
        'rack'=>trim((string)($body['rack']??'')),
        'shelf'=>trim((string)($body['shelf']??'')),
        'locationId'=>isset($body['locationId'])&&$body['locationId'] ? (int)$body['locationId'] : null,
        'lots'=>[],
        'lastMovementAt'=>null,
        'createdAt'=>date('c')
    ]);
    saveData('stock',$stock);
    jsonResponse(['ok'=>true]);
default: jsonError('Méthode non supportée.',405);
}
?>
