<?php
declare(strict_types=1);
require_once __DIR__ . '/../helpers.php';
require_post();
$userId = as_int(get_post('user_id'));
require_write_user($userId);
$itemId = as_int(get_post('item_id'));
$delta = as_int(get_post('delta_quantity', '0'));
$reason = get_post('reason', 'Manual stock adjustment');
if ($delta === 0) {
    respond(['success' => false, 'message' => 'Quantity change must not be zero'], 400);
}

$conn = db();
$conn->begin_transaction();
try {
    $stmt = $conn->prepare('SELECT name, sku, item_type, quantity FROM items WHERE id = ? FOR UPDATE');
    $stmt->bind_param('i', $itemId);
    $stmt->execute();
    $item = $stmt->get_result()->fetch_assoc();
    if (!$item) {
        throw new Exception('Item not found');
    }
    if (($item['item_type'] ?? 'sale') !== 'sale') {
        throw new Exception('Quantity adjustment is only allowed for sale/POS items');
    }
    $newQty = (int)$item['quantity'] + $delta;
    if ($newQty < 0) {
        throw new Exception('Insufficient stock');
    }
    $upd = $conn->prepare('UPDATE items SET quantity = ?, updated_at = NOW() WHERE id = ?');
    $upd->bind_param('ii', $newQty, $itemId);
    $upd->execute();
    $conn->commit();
    log_activity($userId, 'ADJUST_STOCK', "{$reason}: {$item['name']} ({$item['sku']}) change {$delta}, new qty {$newQty}");
    respond(['success' => true, 'message' => 'Stock updated']);
} catch (Throwable $e) {
    $conn->rollback();
    respond(['success' => false, 'message' => $e->getMessage()], 400);
}
