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

try {
  $from = $_GET['from'] ?? date('Y-m-01');
  $to   = $_GET['to'] ?? date('Y-m-t');

  $stmt = $pdo->prepare("
    SELECT id, date, category, title, amount_eur, method, notes
    FROM finance_expenses
    WHERE date BETWEEN :from AND :to
    ORDER BY date DESC, id DESC
  ");
  $stmt->execute([':from' => $from, ':to' => $to]);
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

  $sum = 0;
  foreach ($rows as $r) $sum += (int)$r['amount_eur'];

  echo json_encode(['ok'=>true,'from'=>$from,'to'=>$to,'sum_eur'=>$sum,'items'=>$rows], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
  http_response_code(400);
  echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
}
