<?php
// unit/unitinventory.php
// Atomic replace of a unit's inventory: delete all existing, then insert posted items.

// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../config.php'; // gives $link (mysqli)

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  echo json_encode(['ok' => false, 'message' => 'Method not allowed.']);
  exit;
}

// Pull & validate input
$uid = isset($_POST['uid']) ? (int)$_POST['uid'] : 0;
$inventory = $_POST['inventory'] ?? [];

// If inventory might come as JSON string, decode it
if (!is_array($inventory) && is_string($inventory)) {
  $decoded = json_decode($inventory, true);
  if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
    $inventory = $decoded;
  }
}

if ($uid <= 0 || !is_array($inventory)) {
  http_response_code(400);
  echo json_encode(['ok' => false, 'message' => 'Invalid unit ID or inventory payload.']);
  exit;
}

// Normalize + validate items, also deduplicate by normalized name
// (trim, collapse spaces, lowercased key).
$clean = [];
foreach ($inventory as $item) {
  $name = isset($item['item_name']) ? trim((string)$item['item_name']) : '';
  $qty  = isset($item['item_quantity']) ? (int)$item['item_quantity'] : 0;

  if ($name === '' || $qty <= 0) {
    // skip invalid rows silently; the UI already prevents empty/zero rows
    continue;
  }

  // collapse multiple spaces inside name
  $name = preg_replace('/\s+/u', ' ', $name);
  // optional: limit max length (adjust to your schema)
  if (mb_strlen($name, 'UTF-8') > 255) {
    $name = mb_substr($name, 0, 255, 'UTF-8');
  }

  $key = mb_strtolower(trim($name), 'UTF-8');
  if (!isset($clean[$key])) {
    $clean[$key] = ['item_name' => $name, 'item_quantity' => $qty];
  } else {
    // combine duplicate names by summing quantities
    $clean[$key]['item_quantity'] += $qty;
  }
}

mysqli_begin_transaction($link);

try {
  // Delete existing inventory for the unit
  if (!$del = $link->prepare("DELETE FROM units_inventory WHERE uid = ?")) {
    throw new Exception('Prepare delete failed: ' . $link->error);
  }
  $del->bind_param('i', $uid);
  if (!$del->execute()) {
    throw new Exception('Delete failed: ' . $del->error);
  }
  $deleted = $del->affected_rows;
  $del->close();

  // Insert new items (if any)
  $inserted = 0;
  if (count($clean) > 0) {
    if (!$ins = $link->prepare("INSERT INTO units_inventory (uid, item_name, item_quantity) VALUES (?,?,?)")) {
      throw new Exception('Prepare insert failed: ' . $link->error);
    }
    foreach ($clean as $row) {
      $name = $row['item_name'];
      $qty  = (int)$row['item_quantity'];
      $ins->bind_param('isi', $uid, $name, $qty);
      if (!$ins->execute()) {
        throw new Exception('Insert failed for "' . $name . '": ' . $ins->error);
      }
      $inserted += $ins->affected_rows;
    }
    $ins->close();
  }

  mysqli_commit($link);

  echo json_encode([
    'ok'       => true,
    'message'  => 'Inventory saved successfully.',
    'deleted'  => $deleted,
    'inserted' => $inserted
  ]);
  exit;

} catch (Throwable $e) {
  mysqli_rollback($link);
  http_response_code(500);
  echo json_encode([
    'ok'      => false,
    'message' => 'Failed to save inventory.',
    'error'   => $e->getMessage()
  ]);
  exit;
}
