<?php
/**
 * POST /api/add-goods-to-order.php
 *
 * Adaugă o marfă din catalog pe o comandă existentă, direct din pagina Marfă.
 * Dacă marfa e deja pe comandă, doar crește cantitatea.
 *
 * Body: order_id, goods_id, qty (implicit 1)
 */
require_once __DIR__ . '/../includes/orders.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['ok' => false, 'error' => 'Doar POST'], 405);
}
if (!csrf_check($_POST['csrf_token'] ?? null)) {
    json_response(['ok' => false, 'error' => 'CSRF invalid'], 403);
}

$orderId = (int)($_POST['order_id'] ?? 0);
$goodsId = (int)($_POST['goods_id'] ?? 0);

$qtyRaw = str_replace(',', '.', trim((string)($_POST['qty'] ?? '1')));
$qty    = is_numeric($qtyRaw) ? round((float)$qtyRaw, 3) : 1.0;
if ($qty <= 0) $qty = 1.0;

if ($orderId <= 0) json_response(['ok' => false, 'error' => 'Alege o comandă.'], 422);
if ($goodsId <= 0) json_response(['ok' => false, 'error' => 'Marfă lipsă.'], 422);

$pdo = db();
try {
    $pdo->beginTransaction();

    $order = db_select("SELECT id, order_no FROM orders WHERE id = ?", [$orderId]);
    if (!$order) {
        $pdo->rollBack();
        json_response(['ok' => false, 'error' => 'Comanda nu există.'], 404);
    }
    $goods = db_select("SELECT * FROM goods WHERE id = ?", [$goodsId]);
    if (!$goods) {
        $pdo->rollBack();
        json_response(['ok' => false, 'error' => 'Marfa nu există.'], 404);
    }
    $g = $goods[0];

    $line = db_select(
        "SELECT id, qty FROM order_items WHERE order_id = ? AND goods_id = ? ORDER BY position, id LIMIT 1",
        [$orderId, $goodsId]
    );

    $created = !$line;
    if ($line) {
        $newQty = round((float)$line[0]['qty'] + $qty, 3);
        $pdo->prepare("UPDATE order_items SET qty = ? WHERE id = ?")->execute([$newQty, $line[0]['id']]);
    } else {
        $newQty = $qty;
        $pos = (int)db_scalar("SELECT COALESCE(MAX(position), -1) + 1 FROM order_items WHERE order_id = ?", [$orderId]);
        $pdo->prepare(
            "INSERT INTO order_items (order_id, goods_id, name, sku, unit, qty, unit_price, position)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
        )->execute([
            $orderId, $goodsId, $g['name'], $g['sku'], $g['unit'] ?: 'buc',
            $qty, $g['default_price'] !== null ? (float)$g['default_price'] : 0, $pos
        ]);
    }

    $pdo->prepare("UPDATE orders SET updated_at = CURRENT_TIMESTAMP WHERE id = ?")->execute([$orderId]);
    $pdo->commit();

    json_response([
        'ok'       => true,
        'created'  => $created,          // linie nouă vs. cantitate crescută pe una existentă
        'order_no' => $order[0]['order_no'],
        'name'     => $g['name'],
        'qty'      => $newQty,
        'unit'     => $g['unit'] ?: 'buc',
        'lines'    => (int)db_scalar("SELECT COUNT(*) FROM order_items WHERE order_id = ?", [$orderId]),
    ]);
} catch (Throwable $ex) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log('[add-goods-to-order] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
