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

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

  $stmt = $pdo->prepare("
    SELECT id, invoice_no, invoice_date, service_date, due_date, status,
           customer_name, amount_net_eur, termine_id, pdf_path
    FROM invoices
    WHERE invoice_date BETWEEN :from AND :to
    ORDER BY invoice_date DESC, id DESC
  ");
  $stmt->execute([':from'=>$from, ':to'=>$to]);
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

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