<?php
/**
 * Fichier  : api/alerts.php
 * Auteur   : KREMER Régis
 * Version  : 2.2.0
 * Date     : 2026-02-21
 * Description : API REST — Gestion des alertes de stock (min, max, sécurité, péremption)
 *
 * 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':
    $alerts=loadData('alerts');
    // Permission: filter by warehouses accessible to current user
    $allowedWh = getUserAllowedWarehouses();
    if($allowedWh !== null) $alerts = array_filter($alerts,fn($a)=>in_array((int)($a['warehouseId']??0),$allowedWh));
    $wid=$_GET['warehouseId']??'';
    if($wid) $alerts=array_filter($alerts,fn($a)=>(string)($a['warehouseId']??'')===$wid);
    $stock=loadData('stock');
    $products=loadData('products');
    $today = date('Y-m-d');
    foreach($alerts as &$a){
        $a['currentQty']=0;
        $a['triggered']=false;
        $a['details']=[];
        $aType = $a['type']??'min';
        foreach($stock as $s){
            if((string)($s['productId']??'')===(string)($a['productId']??'') && (string)($s['warehouseId']??'')===(string)($a['warehouseId']??'')){
                $a['currentQty']=(int)($s['quantity']??0);
                $lots = is_array($s['lots']??null) ? ($s['lots']??[]) : [];
                // min/max/safety
                if($aType==='min' && $a['currentQty']<=(int)($a['threshold']??0)) $a['triggered']=true;
                if($aType==='max' && $a['currentQty']>=(int)($a['threshold']??0)) $a['triggered']=true;
                if($aType==='safety'){
                    $thr = $a['threshold'] ?? null;
                    if($thr===null || $thr===''){
                        // fallback to stock safetyStock or product safetyStock
                        $thr = $s['safetyStock'] ?? null;
                        if($thr===null || $thr===''){
                            $p=findById($products,$a['productId']??0);
                            $thr = $p['safetyStock'] ?? null;
                        }
                    }
                    $thr = (int)($thr ?? 0);
                    $a['threshold'] = $thr;
                    if($thr>0 && $a['currentQty']<=$thr) $a['triggered']=true;
                }

                // expiry alerts
                if(in_array($aType,['expiry7','expiry30'],true)){
                    $days = $aType==='expiry7' ? 7 : 30;
                    $limit = date('Y-m-d', strtotime("+$days days"));
                    $expiring=[];
                    foreach($lots as $l){
                        $ed=(string)($l['expiryDate']??'');
                        $q=(int)($l['quantity']??0);
                        if($q<=0 || !$ed) continue;
                        if($ed >= $today && $ed <= $limit){
                            $expiring[]=['lotNumber'=>$l['lotNumber']??'', 'expiryDate'=>$ed, 'quantity'=>$q];
                        }
                    }
                    if(count($expiring)>0){
                        $a['triggered']=true;
                        $a['details']=['expiringLots'=>$expiring,'days'=>$days];
                    }
                }

                // immobilized stock (> 6 months without movement)
                if($aType==='immobilized'){
                    $days = (int)($a['threshold'] ?? 180);
                    $cutoff = date('c', strtotime("-$days days"));
                    $lm = $s['lastMovementAt'] ?? null;
                    if($a['currentQty']>0 && $lm && $lm < $cutoff){
                        $a['triggered']=true;
                        $a['details']=['days'=>$days,'lastMovementAt'=>$lm];
                    }
                }
                break;
            }
        }
    }
    jsonResponse(array_values($alerts));
case 'POST':
    $pid=$body['productId']??null;$wid=$body['warehouseId']??null;
    $type=in_array($body['type']??'',['min','max','safety','expiry7','expiry30','immobilized'],true)?$body['type']:'min';
    $thr=(int)($body['threshold']??0);
    if(!$pid||!$wid) jsonError('productId+warehouseId requis.');
    foreach(loadData('alerts') as $a)
        if((string)($a['productId']??'')===(string)$pid&&(string)($a['warehouseId']??'')===(string)$wid&&($a['type']??'')===$type)
            jsonError('Alerte déjà définie.');
    jsonResponse(addItem('alerts',['productId'=>(int)$pid,'warehouseId'=>(int)$wid,'type'=>$type,'threshold'=>$thr]),201);
case 'PUT':
    $id=$body['id']??null;
    if(!$id) jsonError('ID manquant.');
    $fields=[];
    if(isset($body['threshold'])) $fields['threshold']=(int)$body['threshold'];
    if(isset($body['type']))      $fields['type']=in_array($body['type'],['min','max','safety','expiry7','expiry30','immobilized'],true)?$body['type']:'min';
    $up=updateItem('alerts',$id,$fields);
    $up?jsonResponse($up):jsonError('Non trouvé.',404);
case 'DELETE':
    $id=$body['id']??$_GET['id']??null;
    if(!$id) jsonError('ID manquant.');
    deleteItem('alerts',$id);
    jsonResponse(['ok'=>true]);
default: jsonError('Méthode non supportée.',405);
}
?>
