<?php
/**
 * Fichier  : api/kits.php
 * Auteur   : KREMER Régis
 * Version  : 2.4.0
 * Date     : 2026-02-26
 * Description : API REST — Kits / produits composés (Lot 4)
 */
require_once dirname(__DIR__).'/config.php';
startSession(); requireAuth();

$method = $_SERVER['REQUEST_METHOD'];
if($method === 'GET') {
    requirePerm('kits.read');
} else {
    requirePerm('kits.manage');
    csrfCheck();
}

$body = json_decode(file_get_contents('php://input'), true) ?? [];

function sanitizeComponents($raw): array {
    if(!is_array($raw)) return [];
    $out = [];
    foreach($raw as $c){
        if(!is_array($c)) continue;
        $pid = (int)($c['productId'] ?? 0);
        $qty = (float)($c['qty'] ?? 0);
        $unit = (string)($c['unit'] ?? 'piece');
        if($pid <= 0 || $qty <= 0) continue;
        $out[] = ['productId'=>$pid,'qty'=>$qty,'unit'=>normalizeUnit($unit)];
    }
    return $out;
}

switch($method){
case 'GET':
    $kits = loadData('kits');
    $q = strtolower(trim($_GET['q'] ?? ''));
    if($q){
        $kits = array_filter($kits, fn($k)=>str_contains(strtolower($k['name']??''), $q) || str_contains(strtolower($k['sku']??''), $q));
    }
    jsonResponse(array_values($kits));

case 'POST':
    $name = trim($body['name'] ?? '');
    if($name==='') jsonError('Nom obligatoire.');
    $sku  = trim($body['sku'] ?? '');
    $components = sanitizeComponents($body['components'] ?? []);
    if(empty($components)) jsonError('Composants obligatoires.');

    $item = addItem('kits', [
        'name' => $name,
        'sku'  => $sku,
        'components' => $components,
        'note' => trim($body['note'] ?? ''),
        'active' => true,
        'createdBy' => (currentUser()['id'] ?? null),
    ]);
    jsonResponse($item, 201);

case 'PUT':
    $id = $body['id'] ?? null;
    if(!$id) jsonError('ID manquant.');
    $kits = loadData('kits');
    $k = findById($kits, $id);
    if(!$k) jsonError('Non trouvé.',404);

    $fields = [];
    if(isset($body['name'])) $fields['name'] = trim((string)$body['name']);
    if(array_key_exists('sku',$body)) $fields['sku'] = trim((string)$body['sku']);
    if(array_key_exists('note',$body)) $fields['note'] = trim((string)$body['note']);
    if(array_key_exists('active',$body)) $fields['active'] = (bool)$body['active'];
    if(array_key_exists('components',$body)) {
        $comp = sanitizeComponents($body['components']);
        if(empty($comp)) jsonError('Composants obligatoires.');
        $fields['components'] = $comp;
    }
    $fields['updatedBy'] = (currentUser()['id'] ?? null);

    $up = updateItem('kits', $id, $fields);
    $up ? jsonResponse($up) : jsonError('Non trouvé.',404);

case 'DELETE':
    $id = $_GET['id'] ?? null;
    if(!$id) jsonError('ID manquant.');
    deleteItem('kits', $id);
    jsonResponse(['ok'=>true]);

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