<?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 JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    $autohaus_id = null;

    if ($input && isset($input['autohaus_id'])) {
        $autohaus_id = intval($input['autohaus_id']);
    } elseif (isset($_GET['autohaus_id'])) {
        $autohaus_id = intval($_GET['autohaus_id']);
    } elseif (isset($_POST['autohaus_id'])) {
        $autohaus_id = intval($_POST['autohaus_id']);
    }

    if (!$autohaus_id) {
        throw new Exception('Autohaus ID ist erforderlich');
    }
    
    
    // Get services for the autohaus
    $stmt = $conn->prepare("
        SELECT 
            id,
            service_name,
            service_description,
            price,
            show_price,
            sort_order
        FROM autohaus_services 
        WHERE autohaus_id = ? AND is_active = 1 
        ORDER BY sort_order ASC, service_name ASC
    ");
    
    $stmt->execute([$autohaus_id]);
    $services = $stmt->fetchAll();
    
    $formattedServices = [];
    foreach ($services as $row) {
        $formattedServices[] = [
            'id' => $row['id'],
            'service_name' => $row['service_name'],
            'service_description' => $row['service_description'],
            'price' => floatval($row['price']),
            'show_price' => (bool)$row['show_price'],
            'sort_order' => intval($row['sort_order'])
        ];
    }
    
    echo json_encode([
        'success' => true,
        'services' => $formattedServices,
        'count' => count($formattedServices)
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>