<?php
/**
 * Fichier  : api/locations.php
 * Auteur   : KREMER Régis
 * Version  : 2.3.0
 * Date     : 2026-02-26
 * Description : API REST — Emplacements internes (Lot 1) : zones + codes (A1, Rack 2, etc.)
 *
 * Changelog :
 *   v2.3.0 (2026-02-26) — Création (CRUD) des emplacements internes par magasin.
 */
require_once dirname(__DIR__).'/config.php';
startSession(); requireAuth();
requirePerm('locations.manage'); // admin has this via '*'=>true

$method = $_SERVER['REQUEST_METHOD'];
$body = json_decode(file_get_contents('php://input'), true) ?? [];
if($method !== 'GET') csrfCheck();

function loadLocations(): array {
    if(!file_exists(LOCATIONS_FILE)) file_put_contents(LOCATIONS_FILE, json_encode([], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
    $raw = @file_get_contents(LOCATIONS_FILE);
    $data = json_decode($raw ?: '', true);
    return is_array($data) ? $data : [];
}
function saveLocations(array $rows): void {
    file_put_contents(LOCATIONS_FILE, json_encode(array_values($rows), JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
}

switch($method){
case 'GET':
    $rows = loadLocations();
    // Optional filters
    if(isset($_GET['warehouseId'])){
        $wid = (int)($_GET['warehouseId'] ?? 0);
        $rows = array_values(array_filter($rows, fn($r)=>(int)($r['warehouseId']??0)===$wid));
    }
    jsonResponse($rows);

case 'POST':
    $wid = (int)($body['warehouseId'] ?? 0);
    $code = trim((string)($body['code'] ?? ''));
    $label = trim((string)($body['label'] ?? ''));
    $zone = trim((string)($body['zone'] ?? ''));
    if(!$wid) jsonError('warehouseId requis.');
    if(!userCanAccessWarehouse($wid)) jsonError('Accès refusé à ce magasin.', 403);
    if($code==='') jsonError('Code requis (ex: A1, Rack 2).');

    $rows = loadLocations();
    // Uniqueness within warehouse
    foreach($rows as $r){
        if((int)($r['warehouseId']??0)===$wid && strtolower((string)($r['code']??''))===strtolower($code)){
            jsonError('Code déjà utilisé pour ce magasin.');
        }
    }

    $rows[] = [
        'id' => genId(),
        'warehouseId' => $wid,
        'code' => $code,
        'label' => $label,
        'zone' => $zone,
        'active' => true,
        'createdAt' => date('c')
    ];
    saveLocations($rows);
    jsonResponse(['ok'=>true]);

case 'PUT':
    $id = (string)($body['id'] ?? '');
    if($id==='') jsonError('id requis.');
    $rows = loadLocations();
    $found=false;
    foreach($rows as &$r){
        if((string)($r['id']??'')===$id){
            $wid = (int)($body['warehouseId'] ?? ($r['warehouseId'] ?? 0));
            if(!$wid) jsonError('warehouseId requis.');
            if(!userCanAccessWarehouse($wid)) jsonError('Accès refusé à ce magasin.', 403);

            $code = trim((string)($body['code'] ?? ($r['code'] ?? '')));
            if($code==='') jsonError('Code requis.');
            // uniqueness check
            foreach($rows as $o){
                if((string)($o['id']??'')!==$id && (int)($o['warehouseId']??0)===$wid && strtolower((string)($o['code']??''))===strtolower($code)){
                    jsonError('Code déjà utilisé pour ce magasin.');
                }
            }
            $r['warehouseId'] = $wid;
            $r['code'] = $code;
            $r['label'] = trim((string)($body['label'] ?? ($r['label'] ?? '')));
            $r['zone'] = trim((string)($body['zone'] ?? ($r['zone'] ?? '')));
            if(isset($body['active'])) $r['active'] = (bool)$body['active'];
            $r['updatedAt'] = date('c');
            $found=true;
            break;
        }
    }
    unset($r);
    if(!$found) jsonError('Emplacement introuvable.',404);
    saveLocations($rows);
    jsonResponse(['ok'=>true]);

case 'DELETE':
    $id = (string)($body['id'] ?? '');
    if($id==='') jsonError('id requis.');
    $rows = loadLocations();
    $before = count($rows);
    $rows = array_values(array_filter($rows, fn($r)=>(string)($r['id']??'')!==$id));
    if(count($rows)===$before) jsonError('Emplacement introuvable.',404);
    saveLocations($rows);
    jsonResponse(['ok'=>true]);

default:
    jsonError('Méthode non supportée.',405);
}
?>