<?php
header('Content-Type: application/json');
require_once __DIR__ . '/db.php';
$pdo = db();

function json($data, $code = 200) {
  http_response_code($code);
  echo json_encode($data);
  exit;
}

$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : ($method === 'GET' ? 'list' : '');

try {
  if ($method === 'GET' && $action === 'list') {
    $stmt = $pdo->query("SELECT * FROM inventory_items ORDER BY id DESC");
    $rows = $stmt->fetchAll();
    json(['ok' => true, 'data' => $rows]);
  }

  if ($method === 'GET' && $action === 'get') {
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    $stmt = $pdo->prepare("SELECT * FROM inventory_items WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if (!$row) json(['ok' => false, 'error' => 'Not found'], 404);
    json(['ok' => true, 'data' => $row]);
  }

  if ($method === 'POST' && $action === 'create') {
    $fields = [
      'item_no','code_number','category','opening_qty','opening_rate',
      'cost','weight','unit','id_val','od','w','id1','od2','w2','notes'
    ];
    $data = [];
    foreach ($fields as $f) $data[$f] = isset($_POST[$f]) ? trim((string)$_POST[$f]) : null;
    if (!$data['item_no'] || !$data['code_number'] || !$data['category'] || !$data['opening_qty'] || !$data['opening_rate'] || !$data['cost'] || !$data['weight'] || !$data['unit']) {
      json(['ok' => false, 'error' => 'missing required fields'], 400);
    }
    $stmt = $pdo->prepare("
      INSERT INTO inventory_items (item_no, code_number, category, opening_qty, opening_rate, cost, weight, unit, id_val, od, w, id1, od2, w2, notes)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
      $data['item_no'], $data['code_number'], $data['category'],
      (float)$data['opening_qty'], (float)$data['opening_rate'], (float)$data['cost'],
      (float)$data['weight'], $data['unit'],
      $data['id_val'] !== null ? (float)$data['id_val'] : null,
      $data['od'] !== null ? (float)$data['od'] : null,
      $data['w'] !== null ? (float)$data['w'] : null,
      $data['id1'] !== null ? (float)$data['id1'] : null,
      $data['od2'] !== null ? (float)$data['od2'] : null,
      $data['w2'] !== null ? (float)$data['w2'] : null,
      $data['notes']
    ]);
    $id = (int)$pdo->lastInsertId();
    json(['ok' => true, 'id' => $id]);
  }

  if ($method === 'POST' && $action === 'update') {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    if (!$id) json(['ok' => false, 'error' => 'id required'], 400);
    $fields = [
      'item_no','code_number','category','opening_qty','opening_rate',
      'cost','weight','unit','id_val','od','w','id1','od2','w2','notes'
    ];
    $data = [];
    foreach ($fields as $f) $data[$f] = isset($_POST[$f]) ? trim((string)$_POST[$f]) : null;
    if (!$data['item_no'] || !$data['code_number'] || !$data['category'] || !$data['opening_qty'] || !$data['opening_rate'] || !$data['cost'] || !$data['weight'] || !$data['unit']) {
      json(['ok' => false, 'error' => 'missing required fields'], 400);
    }
    $stmt = $pdo->prepare("
      UPDATE inventory_items
      SET item_no=?, code_number=?, category=?, opening_qty=?, opening_rate=?, cost=?, weight=?, unit=?,
          id_val=?, od=?, w=?, id1=?, od2=?, w2=?, notes=?, updated_at=NOW()
      WHERE id=?
    ");
    $stmt->execute([
      $data['item_no'], $data['code_number'], $data['category'],
      (float)$data['opening_qty'], (float)$data['opening_rate'], (float)$data['cost'],
      (float)$data['weight'], $data['unit'],
      $data['id_val'] !== null ? (float)$data['id_val'] : null,
      $data['od'] !== null ? (float)$data['od'] : null,
      $data['w'] !== null ? (float)$data['w'] : null,
      $data['id1'] !== null ? (float)$data['id1'] : null,
      $data['od2'] !== null ? (float)$data['od2'] : null,
      $data['w2'] !== null ? (float)$data['w2'] : null,
      $data['notes'],
      $id
    ]);
    json(['ok' => true]);
  }

  if ($method === 'POST' && $action === 'delete') {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $stmt = $pdo->prepare("DELETE FROM inventory_items WHERE id = ?");
    $stmt->execute([$id]);
    json(['ok' => true]);
  }

  json(['ok' => false, 'error' => 'invalid request'], 400);
} catch (Throwable $e) {
  json(['ok' => false, 'error' => $e->getMessage()], 500);
}
