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

try {
  $id = (int)($_GET['id'] ?? 0);
  if ($id <= 0) throw new RuntimeException('id fehlt');

  $st = $pdo->prepare("SELECT * FROM invoices WHERE id=:id");
  $st->execute([':id'=>$id]);
  $inv = $st->fetch(PDO::FETCH_ASSOC);
  if (!$inv) throw new RuntimeException('Rechnung nicht gefunden');

  $it = $pdo->prepare("SELECT * FROM invoice_items WHERE invoice_id=:id ORDER BY pos ASC, id ASC");
  $it->execute([':id'=>$id]);
  $items = $it->fetchAll(PDO::FETCH_ASSOC);

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