<?php
// php/update_article.php – DB-Update eines Artikels (Inline-Edit)

declare(strict_types=1);
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);

require __DIR__ . '/../auth.php';
requireLogin();

header('Content-Type: application/json; charset=utf-8');

try {
    $input = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR);

    if (!isset($input['itemId'], $input['field'], $input['value'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Ungültige Anfrage']);
        exit;
    }

    $itemId = (int)$input['itemId'];
    $field  = (string)$input['field'];
    $valueRaw = $input['value'];

    $allowedFields = ['name', 'price', 'amount', 'unit'];
    if (!in_array($field, $allowedFields, true)) {
        throw new InvalidArgumentException('Unzulässiges Feld.');
    }

    // aktuellen Datensatz holen
    $stmt = $pdo->prepare('SELECT id, name, price, amount, unit FROM items WHERE id = :id');
    $stmt->execute([':id' => $itemId]);
    $current = $stmt->fetch();

    if (!$current) {
        throw new RuntimeException('Artikel nicht gefunden.');
    }

    // Wert vorbereiten
    $value = $valueRaw;
    if ($field === 'price' || $field === 'amount') {
        $normalized = str_replace(['.', ','], ['', '.'], preg_replace('~[^\d,.-]~', '', (string)$valueRaw));
        if ($normalized === '' || !is_numeric($normalized)) {
            throw new InvalidArgumentException('Zahlenwert erwartet.');
        }
        $value = (float)$normalized;
    } else {
        $value = trim((string)$valueRaw);
        if ($value === '') {
            throw new InvalidArgumentException('Wert darf nicht leer sein.');
        }
    }

    // Update
    $sql = "UPDATE items SET {$field} = :val WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':val' => $value,
        ':id'  => $itemId,
    ]);

    // neu laden
    $stmt = $pdo->prepare('SELECT id, name, price, amount, unit FROM items WHERE id = :id');
    $stmt->execute([':id' => $itemId]);
    $current = $stmt->fetch();

    if (!$current) {
        throw new RuntimeException('Artikel nach Update nicht gefunden.');
    }

    $price  = (float)$current['price'];
    $amount = (float)$current['amount'];

    $formatted = [
        'price'  => number_format($price, 2, ',', '.'),
        'amount' => rtrim(rtrim(number_format($amount, 2, ',', '.'), '0'), ','),
    ];

    echo json_encode([
        'success'   => true,
        'value'     => ($field === 'price' || $field === 'amount') ? $formatted[$field] : $current[$field],
        'current'   => [
            'price'  => $price,
            'amount' => $amount,
            'name'   => $current['name'],
            'unit'   => $current['unit'],
        ],
        'formatted' => $formatted,
    ]);
} catch (JsonException $e) {
    http_response_code(400);
    echo json_encode(['success'=>false,'message'=>'Ungültiges JSON']);
} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
