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

try {
  // TODO: Statuswert anpassen:
  // Beispiel: 2 = erledigt/abgeschlossen
  $STATUS_DONE = 2;

  $from = $_GET['from'] ?? null; // YYYY-MM-DD
  $to   = $_GET['to'] ?? null;

  // Default: aktueller Monat
  if (!$from || !$to) {
    $from = date('Y-m-01');
    $to   = date('Y-m-t');
  }

  $fromTs = strtotime($from . ' 00:00:00');
  $toTs   = strtotime($to . ' 23:59:59');

  $sql = "
    SELECT
      id,
      startzeit,
      endzeit,
      locationtype,
      location,
      gage,
      status,
      beschreibung
    FROM termine
    WHERE startzeit BETWEEN :fromTs AND :toTs
      AND status = :done
      AND gage > 0
    ORDER BY startzeit DESC
  ";

  $stmt = $pdo->prepare($sql);
  $stmt->execute([
    ':fromTs' => $fromTs,
    ':toTs'   => $toTs,
    ':done'   => $STATUS_DONE,
  ]);

  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

  echo json_encode([
    'ok' => true,
    'from' => $from,
    'to' => $to,
    'sum_eur' => $sum,
    'items' => array_map(function($r){
      return [
        'id' => (int)$r['id'],
        'date' => date('Y-m-d', (int)$r['startzeit']),
        'time' => date('H:i', (int)$r['startzeit']) . '–' . date('H:i', (int)$r['endzeit']),
        'location' => trim(($r['locationtype'] ?? '') . ' ' . ($r['location'] ?? '')),
        'gage' => (int)$r['gage'],
        'desc' => (string)($r['beschreibung'] ?? ''),
      ];
    }, $rows),
  ], JSON_UNESCAPED_UNICODE);

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