<?php
/**
 * Fichier  : api/inventories.php
 * Auteur   : KREMER Régis
 * Version  : 2.3.0
 * Date     : 2026-02-26
 * Description : API REST — Gestion des inventaires physiques
 *
 * 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 (inventaire read/write).
 *                      import CSV, historique prix, bon de livraison multi-lignes
 */
require_once dirname(__DIR__).'/config.php';
require_once dirname(__DIR__).'/includes/push-helper.php';
startSession(); requireAuth();
if($_SERVER['REQUEST_METHOD'] !== 'GET') csrfCheck();
$method=$_SERVER['REQUEST_METHOD'];
$body=json_decode(file_get_contents('php://input'),true)??[];
$user = currentUser();
switch($method){
case 'GET':
    requirePerm('inventory.read');
    $inv=loadData('inventories');
    // Permission: filter by warehouses accessible to current user
    $allowedWh = getUserAllowedWarehouses();
    if($allowedWh !== null) $inv = array_values(array_filter($inv, fn($i)=>in_array((int)($i['warehouseId']??0),$allowedWh)));
    usort($inv,fn($a,$b)=>strcmp($b['date']??'',$a['date']??''));
    jsonResponse(array_values($inv));
case 'POST':
    requirePerm('inventory.write');
    $action=$body['action']??'';
    if($action==='start'){
        $wid=$body['warehouseId']??null;
        // Support multi-catégories (tableau) ET backward compat (string unique)
        $cats = null;
        if(isset($body['categories']) && is_array($body['categories']) && count($body['categories']) > 0){
            $cats = array_values(array_filter(array_map('trim', $body['categories'])));
            if(empty($cats)) $cats = null;
        } elseif(isset($body['category']) && is_string($body['category']) && trim($body['category']) !== ''){
            $cats = [trim($body['category'])];
        }
        if(!$wid) jsonError('warehouseId requis.');
        $prods=loadData('products');$stock=loadData('stock');
        // Filtrer : uniquement les produits référencés dans ce magasin (entrée stock existante)
        $prodIdsInWh = [];
        $stockQtyMap = [];
        foreach($stock as $s){
            if((string)($s['warehouseId']??'') === (string)$wid){
                $pid = (string)($s['productId']??'');
                $prodIdsInWh[$pid] = true;
                $stockQtyMap[$pid] = (int)($s['quantity']??0);
            }
        }
        // Filtrer les produits par magasin, puis par catégorie(s) si précisées
        $prods = array_filter($prods, function($p) use($prodIdsInWh, $cats){
            if(!isset($prodIdsInWh[(string)($p['id']??'')])) return false;
            if($cats !== null && !in_array(($p['category']??''), $cats, true)) return false;
            return true;
        });
        $lines=[];
        foreach($prods as $p){
            $qty = $stockQtyMap[(string)$p['id']] ?? 0;
            $lines[]=['productId'=>$p['id'],'name'=>$p['name'],'sku'=>$p['sku']??'','barcode'=>$p['barcode']??'','category'=>$p['category']??'','expected'=>$qty,'counted'=>null];
        }
        jsonResponse(['warehouseId'=>(int)$wid,'lines'=>$lines]);
    }
    if($action==='validate'){
        $wid=$body['warehouseId']??null;$lines=$body['lines']??[];
        if(!$wid) jsonError('warehouseId requis.');
        $stock=loadData('stock');$disc=0;
        foreach($lines as $line){
            if($line['counted']===null||$line['counted']==='') continue;
            $pid=(int)$line['productId'];$counted=(int)$line['counted'];$expected=(int)($line['expected']??0);$diff=$counted-$expected;
            $found=false;
            foreach($stock as &$s) if((string)($s['productId']??'')===(string)$pid&&(string)($s['warehouseId']??'')===(string)$wid){$s['quantity']=max(0,$counted);$s['updatedAt']=date('c');$found=true;break;}
            if(!$found&&$counted>0) $stock[]=['id'=>genId(),'productId'=>$pid,'warehouseId'=>(int)$wid,'quantity'=>$counted,'maxAuthorized'=>$counted,'minStock'=>null,'maxStock'=>null,'safetyStock'=>null,'lots'=>[],'lastMovementAt'=>date('c'),'createdAt'=>date('c')];
            if($diff!==0){
                $disc++;
                addItem('movements',['productId'=>$pid,'warehouseId'=>(int)$wid,'type'=>'inventory','quantity'=>abs($diff),'reason'=>'Correction inventaire ('.(($diff>0)?"+$diff":"$diff").')','site'=>'','operator'=>'Système','note'=>'','userId'=>0,'date'=>date('c')]);
            }
        }
        saveData('stock',$stock);
        $title    = trim($body['title']    ?? '');
        // Support multi-catégories (tableau) ET backward compat (string unique)
        $categories = [];
        if(isset($body['categories']) && is_array($body['categories'])){
            $categories = array_values(array_filter(array_map('trim', $body['categories'])));
        } elseif(isset($body['category']) && is_string($body['category']) && trim($body['category']) !== ''){
            $categories = [trim($body['category'])];
        }
        $category = count($categories) > 0 ? implode(', ', $categories) : '';
        $operator = $user['name'] ?? $user['username'] ?? 'Inconnu';
        $savedInv = addItem('inventories',[
            'warehouseId'  => (int)$wid,
            'title'        => $title ?: ('Inventaire du ' . date('d/m/Y')),
            'category'     => $category,
            'categories'   => $categories,
            'operator'     => $operator,
            'date'         => date('c'),
            'lines'        => $lines,
            'discrepancies'=> $disc,
            'status'       => 'validated',
        ]);
        
        // ══════════════════════════════════════════════════════════════
        // NOTIFICATION PUSH — Inventaire terminé
        // ══════════════════════════════════════════════════════════════
        $warehouses = loadData('warehouses');
        $wh = findById($warehouses, $wid);
        $whName = $wh ? $wh['name'] : 'Magasin';
        $productCount = count(array_filter($lines, fn($l) => $l['counted'] !== null && $l['counted'] !== ''));
        $currentUserId = (int)($user['id'] ?? 0);
        
        notifyInventoryComplete($whName, $productCount, $disc, $currentUserId);
        
        jsonResponse($savedInv, 201);
    }
    jsonError('Action inconnue.');
default: jsonError('Méthode non supportée.',405);
}
?>
