<?php
/**
 * POST /api/set-reception-packed.php
 * Setează câte bucăți au fost împachetate dintr-un item de recepție.
 *
 * Body:
 *   - item_id    (id-ul din fbe_reception_items) — MANDATORY
 *   - packed_qty (câte bucăți împachetate, 0..qty) — MANDATORY
 *
 * `packed` (binar) se derivă: 1 dacă packed_qty >= qty (item gata), altfel 0.
 */
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);
}

$itemId = (int)($_POST['item_id'] ?? 0);
if ($itemId <= 0) {
    json_response(['ok' => false, 'error' => 'item_id lipsește'], 422);
}

$item = db_select("SELECT id, qty FROM fbe_reception_items WHERE id = ?", [$itemId])[0] ?? null;
if (!$item) {
    json_response(['ok' => false, 'error' => 'Item inexistent'], 404);
}

$target    = (int)$item['qty'];
$packedQty = (int)($_POST['packed_qty'] ?? 0);
if ($packedQty < 0) $packedQty = 0;
if ($target > 0 && $packedQty > $target) $packedQty = $target;

$packed = ($target > 0 && $packedQty >= $target) ? 1 : 0;

try {
    if ($packed) {
        db_exec("UPDATE fbe_reception_items SET packed_qty = ?, packed = 1, packed_at = CURRENT_TIMESTAMP WHERE id = ?",
            [$packedQty, $itemId]);
    } else {
        db_exec("UPDATE fbe_reception_items SET packed_qty = ?, packed = 0, packed_at = NULL WHERE id = ?",
            [$packedQty, $itemId]);
    }
} catch (Throwable $ex) {
    error_log('[set-reception-packed] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => 'Eroare DB: ' . $ex->getMessage()], 500);
}

json_response(['ok' => true, 'item_id' => $itemId, 'packed_qty' => $packedQty, 'packed' => $packed]);
