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

require_once "../config/config.php";
global $pdo;

if (!($pdo instanceof PDO)) {
  http_response_code(500);
  echo json_encode(['ok'=>false,'error'=>'PDO nicht initialisiert']);
  exit;
}

try {
  // Filter
  $from   = $_GET['from']   ?? null; // YYYY-MM-DD
  $to     = $_GET['to']     ?? null; // YYYY-MM-DD
  $status = $_GET['status'] ?? '';   // optional

  // 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,
      user_id,
      anwesend
    FROM termine
    WHERE startzeit BETWEEN :fromTs AND :toTs
  ";

  $params = [
    ':fromTs' => $fromTs,
    ':toTs'   => $toTs,
  ];

  if ($status !== '' && is_numeric($status)) {
    $sql .= " AND status = :status ";
    $params[':status'] = (int)$status;
  }

  $sql .= " ORDER BY startzeit DESC ";

  $stmt = $pdo->prepare($sql);
  $stmt->execute($params);
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

  echo json_encode([
    'ok' => true,
    'from' => $from,
    'to' => $to,
    'count' => count($rows),
    'items' => array_map(function($r){
      return [
        'id' => (int)$r['id'],
        'startzeit' => (int)$r['startzeit'],
        'endzeit' => (int)$r['endzeit'],
        'locationtype' => (string)$r['locationtype'],
        'location' => (string)$r['location'],
        'gage' => (int)$r['gage'],
        'status' => (int)$r['status'],
        'beschreibung' => (string)($r['beschreibung'] ?? ''),
        'user_id' => (int)$r['user_id'],
        'anwesend' => $r['anwesend'], // JSON
      ];
    }, $rows),
  ], JSON_UNESCAPED_UNICODE);

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