<?php
/**
 * Fichier  : api/lots.php
 * Auteur   : KREMER Régis
 * Version  : 2.4.0
 * Date     : 2026-02-26
 * Description : API — Gestion des lots (Lot 2)
 *
 * Fonctions :
 *   - GET  list lots (agrégés depuis stock.locations)
 *   - GET  history (mouvements liés à un lot)
 *   - POST block/unblock un lot
 */
require_once __DIR__.'/../config.php';
requireAuth();

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if($method === 'GET'){
    requirePerm('lots.read');

    $history = (int)($_GET['history'] ?? 0);
    if($history === 1){
        $pid = (int)($_GET['productId'] ?? 0);
        $wid = (int)($_GET['warehouseId'] ?? 0);
        $lot = trim((string)($_GET['lotNumber'] ?? ''));
        $exp = trim((string)($_GET['expiryDate'] ?? ''));
        if(!$pid || !$wid || $lot==='') jsonError('productId, warehouseId, lotNumber requis.');
        if(!userCanAccessWarehouse($wid)) jsonError('Accès refusé à ce magasin.', 403);

        $movements = loadData('movements');
        $out = [];
        foreach($movements as $m){
            if((int)($m['productId'] ?? 0) !== $pid) continue;
            if((int)($m['warehouseId'] ?? 0) !== $wid) continue;

            $lines = [];
            if(isset($m['lots']) && is_array($m['lots']) && count($m['lots'])>0){
                $lines = $m['lots'];
            } else {
                $lines = [[
                    'lotNumber'=>(string)($m['lotNumber'] ?? ''),
                    'expiryDate'=>(string)($m['expiryDate'] ?? ''),
                    'quantity'=>(int)round((float)($m['baseQuantity'] ?? 0)),
                ]];
            }

            foreach($lines as $ln){
                $lnLot = (string)($ln['lotNumber'] ?? '');
                $lnExp = (string)($ln['expiryDate'] ?? '');
                if($lnLot !== $lot) continue;
                if($exp !== '' && $lnExp !== $exp) continue;

                $out[] = [
                    'date'=>(string)($m['date'] ?? ''),
                    'type'=>(string)($m['type'] ?? ''),
                    'quantity'=>(int)($ln['quantity'] ?? 0),
                    'unit'=>(string)($m['unit'] ?? ''),
                    'baseQuantity'=>(float)($m['baseQuantity'] ?? 0),
                    'locationId'=>(string)($ln['locationId'] ?? ($m['locationId'] ?? 'default')),
                    'locationToId'=>(string)($m['locationToId'] ?? ''),
                    'site'=>(string)($m['site'] ?? ''),
                    'operator'=>(string)($m['operator'] ?? ''),
                    'userId'=>(int)($m['userId'] ?? 0),
                    'note'=>(string)($m['note'] ?? ''),
                    'costLine'=>(isset($m['costLines']) && is_array($m['costLines'])) ? $m['costLines'] : null,
                    'movementId'=>(int)($m['id'] ?? 0),
                ];
            }
        }
        // newest first
        usort($out, fn($a,$b)=>strcmp((string)($b['date']??''),(string)($a['date']??'')));
        jsonResponse(['items'=>$out]);
    }

    // List lots
    $pid = (int)($_GET['productId'] ?? 0);
    $wid = (int)($_GET['warehouseId'] ?? 0);
    $locId = trim((string)($_GET['locationId'] ?? ''));

    $stock = loadData('stock');
    $products = loadData('products');
    $prodById = [];
    foreach($products as $p) $prodById[(string)($p['id'] ?? '')] = $p;

    $items = [];
    foreach($stock as $s){
        if($pid && (int)($s['productId'] ?? 0) !== $pid) continue;
        if($wid && (int)($s['warehouseId'] ?? 0) !== $wid) continue;
        if($wid && !userCanAccessWarehouse($wid)) continue;

        $p = $prodById[(string)($s['productId'] ?? '')] ?? null;
        if(!$p) continue;

        foreach(($s['locations'] ?? []) as $lk=>$bucket){
            $lk = getLocationKey($lk);
            if($locId!=='' && $lk!==getLocationKey($locId)) continue;
            $lots = $bucket['lots'] ?? [];
            if(!is_array($lots)) continue;
            foreach($lots as $l){
                $q = (int)($l['quantity'] ?? 0);
                if($q<=0) continue;
                $items[] = [
                    'productId'=>(int)($s['productId'] ?? 0),
                    'productName'=>(string)($p['name'] ?? ''),
                    'warehouseId'=>(int)($s['warehouseId'] ?? 0),
                    'locationId'=>$lk,
                    'lotNumber'=>(string)($l['lotNumber'] ?? ''),
                    'expiryDate'=>(string)($l['expiryDate'] ?? ''),
                    'quantity'=>$q,
                    'unitCost'=>(float)($l['unitCost'] ?? 0),
                    'blocked'=>(bool)($l['blocked'] ?? false),
                    'blockReason'=>(string)($l['blockReason'] ?? ''),
                    'blockedAt'=>(string)($l['blockedAt'] ?? ''),
                    'blockedBy'=>(string)($l['blockedBy'] ?? ''),
                    'lastMovementAt'=>(string)($l['lastMovementAt'] ?? ''),
                    'receivedAt'=>(string)($l['receivedAt'] ?? ''),
                ];
            }
        }
    }

    // Sort: product, expiry asc (empty last)
    usort($items, function($a,$b){
        if($a['productName'] !== $b['productName']) return strcmp($a['productName'],$b['productName']);
        $ea=(string)($a['expiryDate']??'');
        $eb=(string)($b['expiryDate']??'');
        if($ea==='' && $eb!=='') return 1;
        if($ea!=='' && $eb==='') return -1;
        if($ea!==$eb) return strcmp($ea,$eb);
        return strcmp((string)($a['lotNumber']??''),(string)($b['lotNumber']??''));
    });

    jsonResponse(['items'=>$items]);
}

if($method === 'POST'){
    requirePerm('lots.manage');
    csrfCheck();

    $body = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $pid = (int)($body['productId'] ?? 0);
    $wid = (int)($body['warehouseId'] ?? 0);
    $locId = getLocationKey((string)($body['locationId'] ?? 'default'));
    $lot = trim((string)($body['lotNumber'] ?? ''));
    $exp = trim((string)($body['expiryDate'] ?? ''));
    $blocked = (bool)($body['blocked'] ?? true);
    $reason = trim((string)($body['reason'] ?? ''));

    if(!$pid || !$wid || $lot==='') jsonError('productId, warehouseId, lotNumber requis.');
    if(!userCanAccessWarehouse($wid)) jsonError('Accès refusé à ce magasin.', 403);

    $user = currentUser();

    $stock = loadData('stock');
    $updated = false;
    foreach($stock as &$s){
        if((int)($s['productId'] ?? 0) !== $pid) continue;
        if((int)($s['warehouseId'] ?? 0) !== $wid) continue;
        if(!isset($s['locations']) || !is_array($s['locations'])) $s['locations']=['default'=>['quantity'=>(int)($s['quantity']??0),'lots'=>$s['lots']??[]]];
        if(!isset($s['locations'][$locId])) $s['locations'][$locId] = ['quantity'=>0,'lots'=>[]];
        if(!isset($s['locations'][$locId]['lots']) || !is_array($s['locations'][$locId]['lots'])) $s['locations'][$locId]['lots']=[];

        foreach($s['locations'][$locId]['lots'] as &$l){
            if((string)($l['lotNumber']??'')===$lot && ($exp==='' || (string)($l['expiryDate']??'')===$exp)){
                $l['blocked'] = $blocked;
                if($blocked){
                    $l['blockReason'] = $reason;
                    $l['blockedAt'] = date('c');
                    $l['blockedBy'] = (string)($user['name'] ?? '');
                } else {
                    $l['blockReason'] = '';
                    $l['blockedAt'] = '';
                    $l['blockedBy'] = '';
                }
                $updated = true;
                break;
            }
        }
        unset($l);

        // refresh aggregated
        $total=0; $locLots=[];
        foreach(($s['locations'] ?? []) as $loc){
            $total += (int)($loc['quantity'] ?? 0);
            $locLots[] = $loc['lots'] ?? [];
        }
        $s['quantity'] = $total;
        $s['lots'] = mergeLots($locLots);

        break;
    }
    unset($s);

    if(!$updated) jsonError('Lot introuvable (vérifiez emplacement/lot/expiry).', 404);

    saveData('stock',$stock);
    jsonResponse(['ok'=>true]);
}

jsonError('Méthode non supportée',405);
