<?php
declare(strict_types=1);

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

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

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

$name      = trim((string)($data['name'] ?? ''));
$unit      = trim((string)($data['unit'] ?? 'Stück'));
$barcode   = trim((string)($data['barcode'] ?? ''));
$storeFile = trim((string)($data['storeFile'] ?? ''));

if ($name === '' || $barcode === '' || $storeFile === '') {
    echo json_encode(['ok' => false, 'error' => 'Pflichtdaten fehlen.']);
    exit;
}

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

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

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

// Produkt anlegen
$stmt = $pdo->prepare("
    INSERT INTO products (name, default_store_id, default_unit)
    VALUES (:name, :store_id, :unit)
");
$stmt->execute([
    ':name'     => $name,
    ':store_id' => $storeId,
    ':unit'     => $unit,
]);

$productId = (int)$pdo->lastInsertId();

// Barcode speichern
$stmt = $pdo->prepare("
    INSERT INTO product_barcodes (product_id, barcode)
    VALUES (:pid, :barcode)
");
$stmt->execute([
    ':pid'     => $productId,
    ':barcode' => $barcode,
]);

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

// Item anlegen
$stmt = $pdo->prepare("
    INSERT INTO items (product_id, store_id, name, amount, unit, price, sort_order)
    VALUES (:pid, :sid, :name, 1, :unit, 0.00, :sort)
");
$stmt->execute([
    ':pid'  => $productId,
    ':sid'  => $storeId,
    ':name' => $name,
    ':unit' => $unit,
    ':sort' => $sortOrder,
]);

echo json_encode([
    'ok'    => true,
    'msg'   => "Neues Produkt angelegt und hinzugefügt: {$name}",
    'id'    => $productId,
]);
