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

function next_tx_id(PDO $pdo) {
  $stmt = $pdo->query("SELECT COUNT(*) AS c FROM balance_transactions");
  $row = $stmt->fetch();
  $n = (int)$row['c'] + 1;
  return sprintf('AB-%02d', $n);
}

try {
  if ($method === 'GET' && $action === 'next') {
    $tid = next_tx_id($pdo);
    json(['ok' => true, 'transaction_id' => $tid]);
  }

  if ($method === 'GET' && $action === 'list') {
    $limit = isset($_GET['limit']) ? max(1, min(500, (int)$_GET['limit'])) : 100;
    $stmt = $pdo->prepare("SELECT * FROM balance_transactions ORDER BY id DESC LIMIT ?");
    $stmt->bindValue(1, $limit, PDO::PARAM_INT);
    $stmt->execute();
    $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 balance_transactions 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') {
    $transaction_id = isset($_POST['transaction_id']) ? trim($_POST['transaction_id']) : '';
    $amount = isset($_POST['amount']) ? (float)$_POST['amount'] : 0;
    $details = isset($_POST['details']) ? trim($_POST['details']) : null;
    $tx_datetime = isset($_POST['tx_datetime']) ? trim($_POST['tx_datetime']) : '';

    if (!$transaction_id) {
      $transaction_id = next_tx_id($pdo);
    }
    if ($amount <= 0) json(['ok' => false, 'error' => 'amount must be > 0'], 400);
    if (!$tx_datetime) json(['ok' => false, 'error' => 'tx_datetime required'], 400);

    $dt = date_create($tx_datetime);
    if (!$dt) json(['ok' => false, 'error' => 'invalid tx_datetime'], 400);
    $tx_datetime_fmt = $dt->format('Y-m-d H:i:s');

    $stmt = $pdo->prepare("
      INSERT INTO balance_transactions (transaction_id, amount, details, tx_datetime)
      VALUES (?, ?, ?, ?)
    ");
    $stmt->execute([$transaction_id, $amount, $details, $tx_datetime_fmt]);
    $id = (int)$pdo->lastInsertId();
    json(['ok' => true, 'id' => $id]);
  }

  if ($method === 'POST' && $action === 'update') {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $stmt = $pdo->prepare("SELECT * FROM balance_transactions WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if (!$row) json(['ok' => false, 'error' => 'Not found'], 404);
    $transaction_id = isset($_POST['transaction_id']) ? trim($_POST['transaction_id']) : $row['transaction_id'];
    $amount = isset($_POST['amount']) ? (float)$_POST['amount'] : (float)$row['amount'];
    $details = isset($_POST['details']) ? trim($_POST['details']) : $row['details'];
    $tx_datetime = isset($_POST['tx_datetime']) ? trim($_POST['tx_datetime']) : $row['tx_datetime'];
    if ($amount <= 0) json(['ok' => false, 'error' => 'amount must be > 0'], 400);
    $dt = date_create($tx_datetime);
    if (!$dt) json(['ok' => false, 'error' => 'invalid tx_datetime'], 400);
    $tx_datetime_fmt = $dt->format('Y-m-d H:i:s');
    $stmt = $pdo->prepare("
      UPDATE balance_transactions
      SET transaction_id = ?, amount = ?, details = ?, tx_datetime = ?
      WHERE id = ?
    ");
    $stmt->execute([$transaction_id, $amount, $details, $tx_datetime_fmt, $id]);
    json(['ok' => true, 'id' => $id]);
  }

  if ($method === 'POST' && $action === 'delete') {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $stmt = $pdo->prepare("DELETE FROM balance_transactions 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);
}
