<?php
/**
 * Fichier  : api/warehouses.php
 * Auteur   : KREMER Régis
 * Version  : 2.2.0
 * Date     : 2026-02-21
 * Description : API REST — CRUD des magasins
 *
 * 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();
$method=$_SERVER['REQUEST_METHOD'];
$body=json_decode(file_get_contents('php://input'),true)??[];
if($method!=='GET') { requireAdmin(); csrfCheck(); }
switch($method){
case 'GET':
    $whs = loadData('warehouses');
    // Permission: non-admin users only see their allowed warehouses
    $allowedWh = getUserAllowedWarehouses();
    if($allowedWh !== null) $whs = array_values(array_filter($whs, fn($w)=>in_array((int)($w['id']??0),$allowedWh)));
    jsonResponse($whs);
case 'POST':
    $name=trim($body['name']??'');
    if($name==='') jsonError('Nom obligatoire.');
    jsonResponse(addItem('warehouses',['name'=>$name,'address'=>trim($body['address']??''),'color'=>$body['color']??'#00b4d8']),201);
case 'PUT':
    $id=$body['id']??null;
    if(!$id) jsonError('ID manquant.');
    $up=updateItem('warehouses',$id,['name'=>trim($body['name']??''),'address'=>trim($body['address']??''),'color'=>$body['color']??'#00b4d8']);
    $up?jsonResponse($up):jsonError('Non trouvé.',404);
case 'DELETE':
    $id=$body['id']??$_GET['id']??null;
    if(!$id) jsonError('ID manquant.');
    $s=array_filter(loadData('stock'),fn($x)=>(string)($x['warehouseId']??'')!==(string)$id); saveData('stock',array_values($s));
    $m=array_filter(loadData('movements'),fn($x)=>(string)($x['warehouseId']??'')!==(string)$id); saveData('movements',array_values($m));
    $a=array_filter(loadData('alerts'),fn($x)=>(string)($x['warehouseId']??'')!==(string)$id); saveData('alerts',array_values($a));
    deleteItem('warehouses',$id);
    jsonResponse(['ok'=>true]);
default: jsonError('Méthode non supportée.',405);
}
?>
