<?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'));

$conn = db();
$stmt = $conn->prepare('SELECT id, name, sku, item_type FROM items WHERE id = ? LIMIT 1');
$stmt->bind_param('i', $itemId);
$stmt->execute();
$item = $stmt->get_result()->fetch_assoc();
if (!$item) {
    respond(['success' => false, 'message' => 'Item not found'], 404);
}

$check = $conn->prepare('SELECT COUNT(*) AS total FROM sale_items WHERE item_id = ?');
$check->bind_param('i', $itemId);
$check->execute();
$usage = (int)(($check->get_result()->fetch_assoc()['total'] ?? 0));
if ($usage > 0) {
    respond([
        'success' => false,
        'message' => 'Cannot delete this item because it is already used in sales history. Edit it instead, or keep it for records.'
    ], 409);
}

$del = $conn->prepare('DELETE FROM items WHERE id = ?');
$del->bind_param('i', $itemId);
if (!$del->execute()) {
    respond(['success' => false, 'message' => 'Unable to delete item: ' . $del->error], 500);
}
if ($del->affected_rows < 1) {
    respond(['success' => false, 'message' => 'Item was not deleted'], 409);
}

$action = (($item['item_type'] ?? 'sale') === 'other') ? 'DELETE_OTHER_INVENTORY' : 'DELETE_ITEM';
$label = trim((string)($item['sku'] ?? ''));
$details = $label !== ''
    ? "Deleted {$item['name']} ({$label})"
    : "Deleted {$item['name']}";
log_activity($userId, $action, $details);
respond(['success' => true, 'message' => 'Item deleted']);
