<?php
/**
 * POST /api/save-order.php
 *
 * Salvează o comandă întreagă (antet + linii) într-o singură tranzacție.
 * Liniile primite înlocuiesc complet liniile existente ale comenzii.
 *
 * Body:
 *   id            — 0 = comandă nouă
 *   supplier, order_date, delivery_date, status, currency, vat_rate, notes
 *   items         — JSON: [{goods_id, name, sku, unit, qty, unit_price}, ...]
 */
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);
}

$id           = (int)($_POST['id'] ?? 0);
$supplier     = trim((string)($_POST['supplier'] ?? '')) ?: null;
$orderDate    = trim((string)($_POST['order_date'] ?? '')) ?: date('Y-m-d');
$deliveryDate = trim((string)($_POST['delivery_date'] ?? '')) ?: null;
$status       = trim((string)($_POST['status'] ?? 'draft'));
$currency     = strtoupper(trim((string)($_POST['currency'] ?? 'RON'))) ?: 'RON';
$notes        = trim((string)($_POST['notes'] ?? '')) ?: null;
$lang         = order_lang($_POST['lang'] ?? 'ro');
$priceDec     = order_price_decimals($_POST['price_decimals'] ?? 2);

if (!array_key_exists($status, order_statuses())) $status = 'draft';
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $orderDate)) $orderDate = date('Y-m-d');
if ($deliveryDate !== null && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryDate)) $deliveryDate = null;
if (mb_strlen($currency) > 5) $currency = mb_substr($currency, 0, 5);

$vatRaw  = str_replace(',', '.', trim((string)($_POST['vat_rate'] ?? '0')));
$vatRate = is_numeric($vatRaw) ? (float)$vatRaw : 0.0;
if ($vatRate < 0)   $vatRate = 0.0;
if ($vatRate > 100) $vatRate = 100.0;

$items = json_decode((string)($_POST['items'] ?? '[]'), true);
if (!is_array($items)) {
    json_response(['ok' => false, 'error' => 'Liniile comenzii sunt invalide.'], 422);
}

// Normalizează liniile: păstrează doar cele cu denumire; qty/preț devin numerice.
$clean = [];
foreach ($items as $i => $it) {
    if (!is_array($it)) continue;
    $name = trim((string)($it['name'] ?? ''));
    if ($name === '') continue;
    if (mb_strlen($name) > 255) $name = mb_substr($name, 0, 255);

    $qty   = (float)str_replace(',', '.', (string)($it['qty'] ?? 0));
    $price = (float)str_replace(',', '.', (string)($it['unit_price'] ?? 0));

    $clean[] = [
        'goods_id'   => !empty($it['goods_id']) ? (int)$it['goods_id'] : null,
        'name'       => $name,
        'sku'        => trim((string)($it['sku'] ?? '')) ?: null,
        'unit'       => trim((string)($it['unit'] ?? 'buc')) ?: 'buc',
        'qty'        => max(0, round($qty, 3)),
        'unit_price' => max(0, round($price, $priceDec)),
        'position'   => $i,
    ];
}

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

    if ($id > 0) {
        $exists = (int)db_scalar("SELECT COUNT(*) FROM orders WHERE id = ?", [$id]);
        if ($exists === 0) {
            $pdo->rollBack();
            json_response(['ok' => false, 'error' => 'Comanda nu există.'], 404);
        }
        $stmt = $pdo->prepare(
            "UPDATE orders
                SET supplier = ?, order_date = ?, delivery_date = ?, status = ?, currency = ?,
                    vat_rate = ?, lang = ?, notes = ?, price_decimals = ?, updated_at = CURRENT_TIMESTAMP
              WHERE id = ?"
        );
        $stmt->execute([$supplier, $orderDate, $deliveryDate, $status, $currency, $vatRate, $lang, $notes, $priceDec, $id]);
    } else {
        $stmt = $pdo->prepare(
            "INSERT INTO orders (order_no, supplier, order_date, delivery_date, status, currency, vat_rate, lang, notes, price_decimals)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
        );
        $stmt->execute([order_next_no(), $supplier, $orderDate, $deliveryDate, $status, $currency, $vatRate, $lang, $notes, $priceDec]);
        $id = (int)$pdo->lastInsertId();
    }

    $pdo->prepare("DELETE FROM order_items WHERE order_id = ?")->execute([$id]);
    $ins = $pdo->prepare(
        "INSERT INTO order_items (order_id, goods_id, name, sku, unit, qty, unit_price, position)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
    );
    foreach ($clean as $it) {
        $ins->execute([$id, $it['goods_id'], $it['name'], $it['sku'], $it['unit'], $it['qty'], $it['unit_price'], $it['position']]);
    }

    $pdo->commit();
} catch (Throwable $ex) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log('[save-order] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}

$order  = order_load($id);
$totals = order_totals($order['items'] ?? [], (float)$order['vat_rate']);
json_response(['ok' => true, 'order' => $order, 'totals' => $totals]);
