<?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'));
$itemType = strtolower(get_post('item_type', 'sale'));
if (!validate_item_type($itemType)) {
    respond(['success' => false, 'message' => 'Invalid item type'], 400);
}

$sku = get_post('sku');
$barcode = get_post('barcode');
$name = get_post('name');
$description = get_post('description');
$quality = get_post('quality');
$price = as_float(get_post('price', '0'));
$quantity = as_int(get_post('quantity', '0'));

if ($name === '') {
    respond(['success' => false, 'message' => 'Item name is required'], 400);
}

if ($itemType === 'other') {
    $price = 0.0;
    $quantity = 0;
    $barcode = '';
    if ($sku === '') {
        $sku = generate_item_sku('OTH');
    }
} else {
    if ($sku === '') {
        $sku = generate_item_sku('SKU');
    }
}

$conn = db();
$stmt = $conn->prepare('UPDATE items SET item_type = ?, sku = ?, barcode = NULLIF(?, ""), name = ?, description = ?, quality = NULLIF(?, ""), price = ?, quantity = ?, updated_at = NOW() WHERE id = ?');
$stmt->bind_param('ssssssdii', $itemType, $sku, $barcode, $name, $description, $quality, $price, $quantity, $itemId);
if (!$stmt->execute()) {
    respond(['success' => false, 'message' => 'Unable to update item: ' . $stmt->error], 400);
}

if ($itemType === 'other') {
    log_activity($userId, 'UPDATE_OTHER_INVENTORY', "Updated other inventory {$name} ({$sku}) quality {$quality}");
    respond(['success' => true, 'message' => 'Other inventory item updated']);
}

log_activity($userId, 'UPDATE_ITEM', "Updated sale item {$name} ({$sku}) qty {$quantity}");
respond(['success' => true, 'message' => 'Item updated']);
