<?php
/**
 * Fichier  : api/analytics.php
 * Version  : 2.6.0
 * Description : API — Intelligence stock : consommation, projections, risques, dormants, KPIs
 */
require_once __DIR__.'/../config.php';

requireAuth();
requirePerm('analytics.read');

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if($method !== 'GET') jsonError('Méthode non supportée', 405);

$warehouseId = isset($_GET['warehouseId']) && $_GET['warehouseId']!=='' ? (int)$_GET['warehouseId'] : null;
$windowDays  = isset($_GET['windowDays'])  ? max(7,  (int)$_GET['windowDays'])  : 90;
$horizonDays = isset($_GET['horizonDays']) ? max(7,  (int)$_GET['horizonDays']) : 90;
$top         = isset($_GET['top'])         ? max(5,  (int)$_GET['top'])         : 20;
$dormantDays = isset($_GET['dormantDays']) ? max(30, (int)$_GET['dormantDays']) : 180;

$warehouses = loadData('warehouses');
$products   = loadData('products');

// Top consommés
$consTotals = computeConsumptionTotals($windowDays, $warehouseId);
$topRows = [];
foreach($consTotals as $k=>$qty){
    if($qty <= 0) continue;
    [$wh,$pid] = array_map('intval', explode('|', $k));
    $p = findById($products, $pid);
    if(!$p) continue;
    $topRows[] = [
        'warehouseId'  => $wh,
        'productId'    => $pid,
        'productName'  => (string)($p['name'] ?? ('#'.$pid)),
        'sku'          => (string)($p['sku'] ?? ''),
        'category'     => (string)($p['category'] ?? ''),
        'consumed'     => (float)$qty,
        'windowDays'   => $windowDays,
    ];
}
usort($topRows, fn($a,$b)=>($b['consumed'] <=> $a['consumed']));
$topRows = array_slice($topRows, 0, $top);

// Risques — retourner TOUS les produits actifs (pas seulement top N)
// Le frontend filtre et trie lui-même
$risks = computeRuptureRisks($windowDays, $horizonDays, $warehouseId);

// Dormants avec jours inactifs calculés
$dormants = computeDormantProducts($dormantDays, $warehouseId);
$now = time();
foreach($dormants as &$d){
    $ts = isset($d['lastMovementAt']) && $d['lastMovementAt']
        ? strtotime($d['lastMovementAt'])
        : 0;
    $d['inactiveDays'] = $ts > 0 ? (int)floor(($now - $ts) / 86400) : null;
}
unset($d);

// Valorisation
$valuation    = computeStockValuation($warehouseId);
$canSeePrices = hasPerm('price.read') || hasPerm('valuation.read');
if(!$canSeePrices) $valuation = ['totalValue'=>null,'byWarehouse'=>[]];

// KPIs
$kpi = [
    'windowDays'    => $windowDays,
    'horizonDays'   => $horizonDays,
    'warehouseId'   => $warehouseId,
    'stockValue'    => $valuation['totalValue'],
    'riskCount'     => count(array_filter($risks, fn($r)=>in_array($r['risk'],['attention','alerte','critique'], true))),
    'criticalCount' => count(array_filter($risks, fn($r)=>$r['risk']==='critique')),
    'alertCount'    => count(array_filter($risks, fn($r)=>in_array($r['risk'],['attention','alerte'], true))),
    'dormantCount'  => count($dormants),
    'activeProducts'=> count(array_filter($risks, fn($r)=>($r['avgDaily']??0)>0)),
];

jsonResponse([
    'kpi'          => $kpi,
    'topConsumed'  => $topRows,
    'ruptureRisks' => $risks,       // tous les produits avec consommation
    'dormants'     => $dormants,
    'valuation'    => $valuation,
    'warehouses'   => $warehouses,
], 200);
