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

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');

$dataDir = '../data/';
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['storeFile'], $input['index'], $input['newName'], $input['newPrice'], $input['newAmount'], $input['newUnit'])) {
    echo json_encode(['error' => 'Ungültige Anfrage']);
    exit;
}

$storeFile = basename($input['storeFile']);
$index = (int) $input['index'];
$newName = trim($input['newName']);
$newPrice = (float) $input['newPrice'];
$newAmount = (float) $input['newAmount'];
$newUnit = trim($input['newUnit']);

$filePath = $dataDir . $storeFile;

if (!file_exists($filePath)) {
    echo json_encode(['error' => 'Datei nicht gefunden']);
    exit;
}

$articles = json_decode(file_get_contents($filePath), true) ?? [];

if (!isset($articles[$index])) {
    echo json_encode(['error' => 'Artikel nicht gefunden']);
    exit;
}

// Aktualisierung der Artikeldaten
$articles[$index]['name'] = $newName;
$articles[$index]['price'] = $newPrice;
$articles[$index]['amount'] = $newAmount;
$articles[$index]['unit'] = $newUnit;

// Datei mit neuen Werten speichern
file_put_contents($filePath, json_encode($articles, JSON_PRETTY_PRINT));

echo json_encode([
    'success' => true, 
    'newName' => $newName, 
    'newPrice' => number_format($newPrice, 2, ',', '.'), 
    'newAmount' => $newAmount, 
    'newUnit' => $newUnit
]);
exit;
