<?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);
    
    if (!$input || !isset($input['offer_data'])) {
        throw new Exception('Angebotsdaten sind erforderlich');
    }
    
    $offerData = $input['offer_data'];
    $letterContent = $input['letter_content'] ?? '';
    
    // Get appointment and autohaus data
    $appointmentId = $offerData['appointmentId'];
    $stmt = $conn->prepare("
        SELECT 
            a.*,
            ah.name as autohaus_name,
            ah.address as autohaus_address,
            ah.phone as autohaus_phone,
            ah.email as autohaus_email,
            ah.email_from_name
        FROM appointments a
        JOIN autohaus ah ON a.autohaus_id = ah.id
        WHERE a.id = ?
    ");
    
    $stmt->execute([$appointmentId]);
    $appointment = $stmt->fetch();
    
    if (!$appointment) {
        throw new Exception('Termin nicht gefunden');
    }
    
    // Generate HTML content
    $htmlContent = generateOfferHTML($appointment, $offerData, $letterContent, $conn);
    
    // Save HTML to temp directory (for now, as PDF)
    $filename = 'angebot_' . $appointmentId . '_' . date('Y-m-d_H-i-s') . '.html';
    $filepath = '../temp/' . $filename;
    
    if (!is_dir('../temp')) {
        mkdir('../temp', 0755, true);
    }
    
    file_put_contents($filepath, $htmlContent);
    
    echo json_encode([
        'success' => true,
        'filename' => $filename,
        'download_url' => '../temp/' . $filename,
        'content_type' => 'text/html'
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}


function generateOfferHTML($appointment, $offerData, $letterContent, $conn) {
    // Convert HTML to plain text if needed
    $processedContent = $letterContent;
    
    // If content contains HTML, convert to plain text for PDF
    if (strpos($processedContent, '<') !== false) {
        $processedContent = strip_tags($processedContent);
        $processedContent = html_entity_decode($processedContent, ENT_QUOTES, 'UTF-8');
    }
    
    // Replace common placeholders
    $processedContent = str_replace('[haltername]', $appointment['fahrzeughalter'] ?? '[Haltername]', $processedContent);
    $processedContent = str_replace('[kundenname]', $appointment['fahrzeughalter'] ?? '[Kundenname]', $processedContent);
    $processedContent = str_replace('[reifenart]', 'Winterreifen', $processedContent);
    $processedContent = str_replace('[kennzeichen]', $appointment['kennzeichen'] ?? '[Kennzeichen]', $processedContent);
    $processedContent = str_replace('[briefanrede]', 'Sehr geehrte Damen und Herren', $processedContent);
    
    // Add new tires section
    $newTiresSection = '';
    if (!empty($offerData['newTires'])) {
        $newTiresSection = "\n\nNeue Reifen:\n";
        foreach ($offerData['newTires'] as $tire) {
            $newTiresSection .= "- {$tire['brandModel']} ({$tire['size']}) - {$tire['quantity']}x " . number_format($tire['total'], 2, ',', '.') . "€\n";
        }
    }
    
    // Add services section
    $servicesSection = '';
    $zzglServices = '';
    if (!empty($offerData['selectedServices'])) {
        $servicesSection = "\n\nZusatzleistungen:\n";
        $zzglServices = "\nZzgl.\n";
        
        // Get services from database
        $serviceIds = implode(',', array_map('intval', $offerData['selectedServices']));
        $stmt = $conn->prepare("
            SELECT service_name, price 
            FROM autohaus_services 
            WHERE id IN ($serviceIds) AND is_active = 1
        ");
        $stmt->execute();
        $services = $stmt->fetchAll();
        
        foreach ($services as $service) {
            $price = number_format($service['price'], 2, ',', '.');
            $servicesSection .= "- {$service['service_name']}: {$price}€\n";
            $zzglServices .= str_pad($service['service_name'], 30) . "{$price}€\n";
        }
    } else {
        // Default services if none selected
        $zzglServices = "\nZzgl.\nRädermontage                    49,99€\nEinlagerung der Sommerreifen     85,00€\n";
    }
    
    $processedContent .= $newTiresSection . $servicesSection . $zzglServices;
    
    // Convert to HTML with print-friendly styling
    $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Reifenangebot</title>
    <style>
        @media print {
            body { margin: 0; }
            .no-print { display: none; }
        }
        
        body {
            font-family: "Times New Roman", serif;
            line-height: 1.6;
            margin: 40px;
            color: #000;
            background: #fff;
        }
        
        .header {
            margin-bottom: 30px;
            border-bottom: 2px solid #000;
            padding-bottom: 15px;
        }
        
        .content {
            white-space: pre-line;
            font-size: 12pt;
        }
        
        .footer {
            margin-top: 30px;
            font-size: 10pt;
            color: #666;
            border-top: 1px solid #ccc;
            padding-top: 15px;
        }
        
        .tire-section {
            margin: 15px 0;
            padding: 10px;
            background: #f9f9f9;
            border-left: 4px solid #2563eb;
        }
        
        .tire-section h4 {
            margin: 0 0 10px 0;
            color: #2563eb;
            font-size: 14pt;
        }
        
        .services-section {
            margin: 15px 0;
            padding: 10px;
            background: #f0f8ff;
            border-left: 4px solid #10b981;
        }
        
        .services-section h4 {
            margin: 0 0 10px 0;
            color: #10b981;
            font-size: 14pt;
        }
        
        .price-section {
            margin: 20px 0;
            padding: 15px;
            background: #fef3c7;
            border: 2px solid #f59e0b;
            border-radius: 5px;
        }
        
        .price-line {
            display: flex;
            justify-content: space-between;
            margin: 5px 0;
        }
        
        .price-line .label {
            flex: 1;
        }
        
        .price-line .amount {
            font-weight: bold;
            text-align: right;
        }
    </style>
</head>
<body>
    <div class="header">
        <strong>' . ($appointment['autohaus_name'] ?? 'B&E Autocentrum GmbH') . '</strong><br>
        ' . ($appointment['autohaus_address'] ?? '') . '<br>
        Tel: ' . ($appointment['autohaus_phone'] ?? '0431/54 63 00') . '
    </div>
    
    <div class="content">' . $processedContent . '</div>
    
    <div class="footer">
        Dieses Dokument wurde maschinell erstellt und ist ohne Unterschrift gültig
    </div>
</body>
</html>';
    
    return $html;
}
?>
