<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: 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");
    }

    $appointmentId = $_GET['appointmentId'] ?? null;

    if (!$appointmentId) {
        throw new Exception('Termin-ID ist erforderlich');
    }

    // Get customer selection
    $stmt = $conn->prepare("
        SELECT 
            cs.*,
            a.customer_name,
            a.license_plate as kennzeichen,
            ah.name as autohaus_name
        FROM customer_selections cs
        JOIN appointments a ON cs.appointment_id = a.id
        JOIN autohaus ah ON a.autohaus_id = ah.id
        WHERE cs.appointment_id = ?
        ORDER BY cs.created_at DESC
        LIMIT 1
    ");

    $stmt->execute([$appointmentId]);
    $selection = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$selection) {
        echo json_encode([
            'success' => true,
            'selection' => null,
            'message' => 'Keine Kundenauswahl gefunden'
        ]);
        exit;
    }

    // Get offer data to map tire and service IDs to names
    $stmt = $conn->prepare("
        SELECT offer_data 
        FROM offer_tracking 
        WHERE appointment_id = ? AND offer_type = 'sent'
        ORDER BY created_at DESC 
        LIMIT 1
    ");
    
    $stmt->execute([$appointmentId]);
    $offerData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $offer = null;
    if ($offerData) {
        $offer = json_decode($offerData['offer_data'], true);
    }

    // Map tire selection to readable names
    $tireSelection = json_decode($selection['tire_selection'], true) ?? [];
    $mappedTireSelection = [];
    
    if ($offer && isset($offer['selectedTires'])) {
        foreach ($tireSelection as $tireIndex) {
            if (isset($offer['selectedTires'][$tireIndex])) {
                $tire = $offer['selectedTires'][$tireIndex];
                $mappedTireSelection[] = ($tire['brand'] ?? '') . ' ' . ($tire['model'] ?? '') . ' (' . ($tire['position'] ?? '') . ')';
            }
        }
    }
    
    if ($offer && isset($offer['newTires'])) {
        foreach ($tireSelection as $tireIndex) {
            if (strpos($tireIndex, 'new_') === 0) {
                $newIndex = str_replace('new_', '', $tireIndex);
                if (isset($offer['newTires'][$newIndex])) {
                    $tire = $offer['newTires'][$newIndex];
                    $mappedTireSelection[] = 'NEU: ' . ($tire['brand'] ?? '') . ' ' . ($tire['model'] ?? '') . ' (' . ($tire['size'] ?? '') . ')';
                }
            }
        }
    }

    // Map service selection to readable names
    $serviceSelection = json_decode($selection['service_selection'], true) ?? [];
    $mappedServiceSelection = [];
    
    if (!empty($serviceSelection)) {
        $placeholders = str_repeat('?,', count($serviceSelection) - 1) . '?';
        $stmt = $conn->prepare("
            SELECT service_name, price 
            FROM autohaus_services 
            WHERE id IN ($placeholders) AND is_active = 1
        ");
        $stmt->execute($serviceSelection);
        $services = $stmt->fetchAll();
        
        foreach ($services as $service) {
            $mappedServiceSelection[] = $service['service_name'] . ' (' . number_format($service['price'], 2, ',', '.') . ' €)';
        }
    }

    // Update selection with mapped data
    $selection['tire_selection'] = json_encode($mappedTireSelection);
    $selection['service_selection'] = json_encode($mappedServiceSelection);

    echo json_encode([
        'success' => true,
        'selection' => $selection
    ]);

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