<?php
require_once "../config/config.php";
header('Content-Type: application/json; charset=utf-8');

try {
  if ($_SERVER['REQUEST_METHOD'] !== 'POST') throw new RuntimeException('Method not allowed');

  $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
  $date = trim($_POST['date'] ?? '');
  $category = trim($_POST['category'] ?? '');
  $title = trim($_POST['title'] ?? '');
  $amount = (int)($_POST['amount_eur'] ?? 0);
  $method = trim($_POST['method'] ?? 'bank');
  $notes = trim($_POST['notes'] ?? '');

  if (!$date || !$category || !$title) throw new RuntimeException('Pflichtfelder fehlen');
  if ($amount <= 0) throw new RuntimeException('Betrag muss > 0 sein');

  $allowedMethods = ['cash','bank','paypal','card','other'];
  if (!in_array($method, $allowedMethods, true)) $method = 'bank';

  if ($id > 0) {
    $stmt = $pdo->prepare("
      UPDATE finance_expenses
      SET date=:date, category=:category, title=:title, amount_eur=:amount, method=:method, notes=:notes
      WHERE id=:id
    ");
    $stmt->execute([
      ':date'=>$date, ':category'=>$category, ':title'=>$title, ':amount'=>$amount, ':method'=>$method, ':notes'=>$notes, ':id'=>$id
    ]);
  } else {
    $stmt = $pdo->prepare("
      INSERT INTO finance_expenses (date, category, title, amount_eur, method, notes)
      VALUES (:date,:category,:title,:amount,:method,:notes)
    ");
    $stmt->execute([
      ':date'=>$date, ':category'=>$category, ':title'=>$title, ':amount'=>$amount, ':method'=>$method, ':notes'=>$notes
    ]);
    $id = (int)$pdo->lastInsertId();
  }

  echo json_encode(['ok'=>true,'id'=>$id], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
  http_response_code(400);
  echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
}
