<?php
/**
 * POST /api/save-reception.php
 *
 * Salvează o sesiune de recepție FBE (snapshot): metadata + lista de items
 * (EAN-uri în ordinea dată, cu cantitatea înghețată la momentul generării).
 *
 * Body:
 *   - id               (opțional — dacă > 0, suprascrie sesiunea existentă)
 *   - name             (obligatoriu)
 *   - reception_number (opțional — nr. recepție)
 *   - account_id       (opțional — contextul de cont)
 *   - items            (JSON: [{ean, qty, product_id, product_name}, ...]) — obligatoriu
 */
require_once __DIR__ . '/../includes/db.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);
$name      = trim((string)($_POST['name'] ?? ''));
$recNumber = trim((string)($_POST['reception_number'] ?? '')) ?: null;
$accountId = (int)($_POST['account_id'] ?? 0) ?: null;
$itemsRaw  = $_POST['items'] ?? '';

if ($name === '') {
    json_response(['ok' => false, 'error' => 'Numele sesiunii este obligatoriu.'], 422);
}

$items = json_decode((string)$itemsRaw, true);
if (!is_array($items) || count($items) === 0) {
    json_response(['ok' => false, 'error' => 'Sesiunea nu are niciun EAN.'], 422);
}

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

    if ($id > 0) {
        $exists = db_scalar("SELECT 1 FROM fbe_receptions WHERE id = ?", [$id]);
        if (!$exists) {
            $pdo->rollBack();
            json_response(['ok' => false, 'error' => 'Sesiune inexistentă'], 404);
        }
        db_exec("UPDATE fbe_receptions SET name = ?, reception_number = ?, emag_account_id = ? WHERE id = ?",
            [$name, $recNumber, $accountId, $id]);
        db_exec("DELETE FROM fbe_reception_items WHERE reception_id = ?", [$id]);
        $savedId = $id;
    } else {
        $savedId = db_exec("INSERT INTO fbe_receptions (name, reception_number, emag_account_id) VALUES (?, ?, ?)",
            [$name, $recNumber, $accountId]);
    }

    $stmt = $pdo->prepare(
        "INSERT INTO fbe_reception_items (reception_id, position, ean, qty, product_id, product_name)
         VALUES (?, ?, ?, ?, ?, ?)"
    );
    foreach ($items as $i => $it) {
        $ean = trim((string)($it['ean'] ?? ''));
        if ($ean === '') continue;
        $qtyVal = $it['qty'] ?? null;
        $qty = ($qtyVal === null || $qtyVal === '') ? null : (int)$qtyVal;
        $pid = (int)($it['product_id'] ?? 0) ?: null;
        $pname = isset($it['product_name']) ? (string)$it['product_name'] : null;
        $stmt->execute([$savedId, $i, $ean, $qty, $pid, $pname]);
    }

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

// Returnează sesiunea salvată cu items, ca UI-ul să o adauge fără reload.
$session = db_select(
    "SELECT r.*,
            (SELECT COUNT(*) FROM fbe_reception_items WHERE reception_id = r.id) AS items_count,
            (SELECT COALESCE(SUM(qty),0) FROM fbe_reception_items WHERE reception_id = r.id) AS total_qty
     FROM fbe_receptions r WHERE r.id = ?",
    [$savedId]
)[0] ?? null;
$sessionItems = db_select(
    "SELECT ean, qty, product_id, product_name FROM fbe_reception_items
     WHERE reception_id = ? ORDER BY position ASC",
    [$savedId]
);
if ($session) $session['items'] = $sessionItems;

json_response(['ok' => true, 'session' => $session]);
