<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once '../config/database.php';
$database = new Database();
$conn = $database->getConnection();

try {
    if (!$conn) {
        throw new Exception("Keine Datenbankverbindung möglich");
    }

    $event_id = isset($_GET['event_id']) ? intval($_GET['event_id']) : 0;
    $date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
    if ($event_id <= 0) {
        throw new Exception('event_id ist erforderlich');
    }

    $stmt = $conn->prepare("
        SELECT slot_time, COUNT(*) as count
        FROM appointments
        WHERE event_id = :event_id AND slot_date = :date
        GROUP BY slot_time
    ");
    $stmt->execute(['event_id' => $event_id, 'date' => $date]);
    $counts = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $counts[$row['slot_time']] = intval($row['count']);
    }

    // Immer als Objekt zurückgeben, auch wenn leer!
    echo json_encode([
        'success' => true,
        'counts' => (object)$counts
    ]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>