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

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

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

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

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

