<?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';

try {
    $database = new Database();
    $conn = $database->getConnection();

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

    $autohaus_id = isset($_GET['autohaus_id']) ? intval($_GET['autohaus_id']) : null;
    if (!$autohaus_id) {
        throw new Exception('Autohaus ID ist erforderlich');
    }

    // Events für das Autohaus laden
    $stmt = $conn->prepare("
        SELECT e.id, e.name, e.event_date, e.start_time, e.end_time, e.slot_duration, e.max_monteure
        FROM events e
        WHERE e.autohaus_id = ? AND e.is_active = 1
        ORDER BY e.event_date ASC
    ");
    $stmt->execute([$autohaus_id]);
    $events = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $result = [];
    foreach ($events as $event) {
        // Gesamtzahl Slots berechnen
        $start = strtotime($event['start_time']);
        $end = strtotime($event['end_time']);
        $duration = intval($event['slot_duration']);
        $max_monteure = intval($event['max_monteure']);
        $slots_per_line = ($end - $start) / ($duration * 60);
        $total_slots = intval(floor($slots_per_line) * $max_monteure);

        // Gebuchte Slots zählen
        $stmt2 = $conn->prepare("SELECT COUNT(*) FROM appointments WHERE event_id = ? AND status IN ('booked','vorbereitet')");
        $stmt2->execute([$event['id']]);
        $booked_slots = intval($stmt2->fetchColumn());

        $result[] = [
            'event_id' => $event['id'],
            'name' => $event['name'],
            'event_date' => $event['event_date'],
            'start_time' => $event['start_time'],
            'end_time' => $event['end_time'],
            'slot_duration' => $duration,
            'max_monteure' => $max_monteure,
            'total_slots' => $total_slots,
            'booked_slots' => $booked_slots
        ];
    }

    echo json_encode([
        'success' => true,
        'events' => $result,
        'count' => count($result)
    ]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>