<?php
require_once 'db.php';
header('Content-Type: application/json');
$pdo = db();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? 'list';

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

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

  if ($method === 'POST' && $action === 'create') {
    $name = trim($_POST['name'] ?? '');
    if (!$name) json_out(['ok' => false, 'error' => 'name required'], 400);
    $stmt = $pdo->prepare("INSERT INTO shipment_vias (name) VALUES (?)");
    try {
      $stmt->execute([$name]);
    } catch (Throwable $e) {
      json_out(['ok' => false, 'error' => 'duplicate or invalid'], 400);
    }
    json_out(['ok' => true, 'id' => (int)$pdo->lastInsertId(), 'name' => $name]);
  }

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

