<?php
declare(strict_types=1);

ini_set('display_errors', '0');
error_reporting(E_ALL);

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

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

// eingeloggter User für created_by
$user      = currentUser();
$creatorId = (int)$user['id'];

try {
    // Request-Body einlesen
    $raw = file_get_contents('php://input');
    if ($raw === false) {
        throw new RuntimeException('Kein Request-Body.');
    }

    $input = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);

    $storeFile = $input['storeFile'] ?? null;
    $text      = trim((string)($input['text'] ?? ''));

    if (!$storeFile || $text === '') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'message' => 'Kein Markt oder kein Text übergeben.']);
        exit;
    }

    // gleiche Prüfung wie in articles.php
    if (!preg_match('~^[a-z0-9._-]+\.json$~i', $storeFile)) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'message' => 'Ungültiger Store-Identifikator.']);
        exit;
    }

    // Store über file finden
    $stmt = $pdo->prepare('SELECT id FROM stores WHERE file = :file LIMIT 1');
    $stmt->execute([':file' => $storeFile]);
    $store = $stmt->fetch();

    if (!$store) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'message' => 'Store nicht gefunden.']);
        exit;
    }

    $storeId = (int)$store['id'];

    // Text in Tokens zerlegen, z.B. "milch zwei flaschen"
    $normalized = mb_strtolower($text, 'UTF-8');
    $tokens = preg_split('~\s+~u', $normalized);

    $amount = 1;
    $unit   = 'Stück';
    $nameParts = [];

    $unitWords = [
        'stück'      => 'Stück',
        'stk'        => 'Stück',
        'dose'       => 'Dose(n)',
        'dosen'      => 'Dose(n)',
        'flasche'    => 'Flasche(n)',
        'flaschen'   => 'Flasche(n)',
        'packung'    => 'Packung(en)',
        'packungen'  => 'Packung(en)',
        'tüte'       => 'Tüte(n)',
        'tüten'      => 'Tüte(n)',
        'kg'         => 'Kilogramm',
        'kilogramm'  => 'Kilogramm',
        'gramm'      => 'Gramm',
        'g'          => 'Gramm'
    ];

    foreach ($tokens as $tok) {
        $tokClean = str_replace(',', '.', $tok);

        // Zahl → Menge
        if (is_numeric($tokClean)) {
            $amount = (int)$tokClean;
            if ($amount <= 0) {
                $amount = 1;
            }
            continue;
        }

        // Einheit erkennen
        if (isset($unitWords[$tok])) {
            $unit = $unitWords[$tok];
            continue;
        }

        // Rest ist Artikelnamen-Teil
        $nameParts[] = $tok;
    }

    $name = trim(ucfirst(implode(' ', $nameParts)));

    if ($name === '') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'message' => 'Konnte keinen Artikelnamen aus "' . $text . '" erkennen.']);
        exit;
    }

    // sort_order bestimmen
    $stmt = $pdo->prepare('SELECT COALESCE(MAX(sort_order) + 1, 1) AS nextSort FROM items WHERE store_id = :sid');
    $stmt->execute([':sid' => $storeId]);
    $nextSort = (int)($stmt->fetchColumn() ?: 1);

    // Artikel eintragen (Preis 0, später pflegen) + created_by
    $stmt = $pdo->prepare('
        INSERT INTO items (store_id, name, price, amount, unit, sort_order, created_by)
        VALUES (:sid, :name, :price, :amount, :unit, :sort, :created_by)
    ');

    $stmt->execute([
        ':sid'        => $storeId,
        ':name'       => $name,
        ':price'      => 0.0,
        ':amount'     => $amount,
        ':unit'       => $unit,
        ':sort'       => $nextSort,
        ':created_by' => $creatorId,
    ]);

    echo json_encode([
        'ok'      => true,
        'message' => "Hinzugefügt: {$amount} × {$name} ({$unit})"
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'ok'      => false,
        'message' => 'Serverfehler: ' . $e->getMessage()
    ]);
}
