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

// Handle preflight OPTIONS request
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");
    }
    
    // Get all active autohauser
    $stmt = $conn->prepare("
        SELECT 
            id,
            name,
            short_name,
            address,
            phone,
            email,
            is_active
        FROM autohaus 
        WHERE is_active = 1 
        ORDER BY name ASC
    ");
    
    $stmt->execute();
    $autohauser = $stmt->fetchAll();
    
    $formattedAutohauser = [];
    foreach ($autohauser as $row) {
        $formattedAutohauser[] = [
            'id' => intval($row['id']),
            'name' => $row['name'],
            'short_name' => $row['short_name'],
            'address' => $row['address'],
            'phone' => $row['phone'],
            'email' => $row['email'],
            'is_active' => (bool)$row['is_active']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'autohauser' => $formattedAutohauser,
        'count' => count($formattedAutohauser)
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
