<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/security.php';

$id = getSafeInt('id');
$item_name = getSafeString('item_name');
$category = getSafeString('category');
$brand = getSafeString('brand');
$quantity = getSafeInt('quantity');
$min_stock = getSafeInt('min_stock');
$expiry_date = getSafeString('expiry_date');
$received_qty = getSafeInt('received_qty', getSafeInt('ppeReceivedQty'));
$receiving_date = getSafeString('receiving_date', getSafeString('ppeReceivingDate'));
$ppe_code = getSafeString('ppe_code', getSafeString('item_code', getSafeString('ppeCode')));
$storage_location = getSafeString('storage_location', getSafeString('ppeStorageLocation'));
$supplier_name = getSafeString('supplier_name', getSafeString('ppeSupplierName'));
$supplier_phone = getSafeString('supplier_phone', getSafeString('ppeSupplierPhone'));
$supplier_location = getSafeString('supplier_location', getSafeString('ppeSupplierLocation'));
$quality = getSafeString('quality', getSafeString('ppeQuality'));
$size = getSafeString('size', getSafeString('ppeSize'));
$description = getSafeString('description', getSafeString('ppeDescription'));

if (!$id || !$item_name) {
    echo json_encode(['success' => false, 'error' => 'ID and name required']);
    exit;
}

$fields = [
    'item_name' => $item_name,
    'category' => $category,
    'brand' => $brand,
    'quantity' => $quantity,
    'min_stock' => $min_stock,
    'expiry_date' => $expiry_date,
    'received_qty' => $received_qty,
    'receiving_date' => $receiving_date,
    'ppe_code' => $ppe_code,
    'storage_location' => $storage_location,
    'supplier_name' => $supplier_name,
    'supplier_phone' => $supplier_phone,
    'supplier_location' => $supplier_location,
    'quality' => $quality,
    'size' => $size,
    'description' => $description,
];

$existing = [];
$result = $mysqli->query("SHOW COLUMNS FROM ppe_inventory");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $existing[] = $row['Field'];
    }
}

$updates = [];
$types = '';
$values = [];
foreach ($fields as $field => $value) {
    if (!in_array($field, $existing, true)) {
        continue;
    }
    $updates[] = "{$field} = ?";
    if (in_array($field, ['quantity', 'min_stock', 'received_qty'], true)) {
        $types .= 'i';
        $values[] = $value === null ? 0 : (int)$value;
    } else {
        $types .= 's';
        $values[] = $value === null ? '' : $value;
    }
}

if (empty($updates)) {
    echo json_encode(['success' => false, 'error' => 'No valid fields to update']);
    exit;
}

$query = "UPDATE ppe_inventory SET " . implode(', ', $updates) . " WHERE id = ?";
$types .= 'i';
$values[] = (int)$id;

$stmt = $mysqli->prepare($query);
$stmt->bind_param($types, ...$values);
$ok = $stmt->execute();

echo json_encode(['success' => $ok]);
?>
