<?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");
    }
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['appointmentId'])) {
        throw new Exception('Ungültige Eingabedaten');
    }
    
    $appointmentId = $input['appointmentId'];
    $selectedTires = $input['selectedTires'] ?? [];
    $newTires = $input['newTires'] ?? [];
    $selectedServices = $input['selectedServices'] ?? [];
    
    // Get appointment data
    $stmt = $conn->prepare("
        SELECT a.*, au.name as autohaus_name, au.address as autohaus_address, au.phone as autohaus_phone
        FROM appointments a 
        LEFT JOIN autohaus au ON a.autohaus_id = au.id 
        WHERE a.id = ?
    ");
    $stmt->execute([$appointmentId]);
    $appointment = $stmt->fetch();
    
    if (!$appointment) {
        throw new Exception('Termin nicht gefunden');
    }
    
    // Generate PDF content
    $pdfContent = generateSimplePDF($appointment, $selectedTires, $newTires, $selectedServices, $conn);
    
    // Create filename
    $filename = 'angebot_' . $appointmentId . '_' . date('Y-m-d_H-i-s') . '.pdf';
    
    // Return PDF content directly
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . strlen($pdfContent));
    
    echo $pdfContent;
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

function generateSimplePDF($appointment, $selectedTires, $newTires, $selectedServices, $conn) {
    // Create a simple but robust PDF
    $pdf = "%PDF-1.4\n";
    $pdf .= "1 0 obj\n";
    $pdf .= "<<\n";
    $pdf .= "/Type /Catalog\n";
    $pdf .= "/Pages 2 0 R\n";
    $pdf .= ">>\n";
    $pdf .= "endobj\n\n";
    
    $pdf .= "2 0 obj\n";
    $pdf .= "<<\n";
    $pdf .= "/Type /Pages\n";
    $pdf .= "/Kids [3 0 R]\n";
    $pdf .= "/Count 1\n";
    $pdf .= ">>\n";
    $pdf .= "endobj\n\n";
    
    // Create content
    $pdfContent = "";
    $yPosition = 750;
    
    // Company header
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 16 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(B&E Autocentrum GmbH) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 25;
    
    // Date
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 12 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Kiel, " . date('d.m.Y') . ") Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 30;
    
    // Greeting
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 12 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Sehr geehrte Damen und Herren,) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 30;
    
    // Main text
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 12 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(die Vorbereitungen für unseren nächsten Boxenstopp laufen bereits und dabei ist uns leider aufgefallen,) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 20;
    
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 12 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(dass die bei uns eingelagerten Reifen ersetzt werden müssten.) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 30;
    
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 12 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Daher erhalten Sie mit diesem Schreiben das beigefügte Angebot.) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 40;
    
    // Selected tires section
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 14 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Auszutauschender Reifen:) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 25;
    
    if (!empty($selectedTires)) {
        foreach ($selectedTires as $tire) {
            $tireText = "- " . $tire['brand'] . " " . $tire['model'] . " (" . $tire['size'] . ") - Position: " . $tire['position'] . " - " . $tire['recommendation'];
            $pdfContent .= "BT\n";
            $pdfContent .= "/F1 12 Tf\n";
            $pdfContent .= "50 " . $yPosition . " Td\n";
            $pdfContent .= "(" . escapePDFText($tireText) . ") Tj\n";
            $pdfContent .= "ET\n";
            $yPosition -= 20;
        }
    } else {
        $pdfContent .= "BT\n";
        $pdfContent .= "/F1 12 Tf\n";
        $pdfContent .= "50 " . $yPosition . " Td\n";
        $pdfContent .= "(Keine Reifen ausgewählt) Tj\n";
        $pdfContent .= "ET\n";
        $yPosition -= 20;
    }
    
    $yPosition -= 20;
    
    // New tires section
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 14 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Neue Reifen:) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 25;
    
    if (!empty($newTires)) {
        foreach ($newTires as $tire) {
            $tireText = "- " . $tire['brand'] . " (" . $tire['size'] . ") - " . $tire['quantity'] . "x " . number_format($tire['price'], 2, ',', '.') . "€";
            $pdfContent .= "BT\n";
            $pdfContent .= "/F1 12 Tf\n";
            $pdfContent .= "50 " . $yPosition . " Td\n";
            $pdfContent .= "(" . escapePDFText($tireText) . ") Tj\n";
            $pdfContent .= "ET\n";
            $yPosition -= 20;
        }
    } else {
        $pdfContent .= "BT\n";
        $pdfContent .= "/F1 12 Tf\n";
        $pdfContent .= "50 " . $yPosition . " Td\n";
        $pdfContent .= "(Keine neuen Reifen hinzugefügt) Tj\n";
        $pdfContent .= "ET\n";
        $yPosition -= 20;
    }
    
    $yPosition -= 20;
    
    // Costs section
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 14 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Kosten inkl. Reifenmontage:) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 25;
    
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 12 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Zzgl.) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 20;
    
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 12 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Rädermontage                    49,99€) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 20;
    
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 12 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Einlagerung der Sommerreifen     85,00€) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 20;
    
    // Services
    if (!empty($selectedServices)) {
        foreach ($selectedServices as $serviceId) {
            $service = getServiceById($serviceId, $conn);
            if ($service) {
                $serviceText = str_pad($service['service_name'], 30) . number_format($service['price'], 2, ',', '.') . "€";
                $pdfContent .= "BT\n";
                $pdfContent .= "/F1 12 Tf\n";
                $pdfContent .= "50 " . $yPosition . " Td\n";
                $pdfContent .= "(" . escapePDFText($serviceText) . ") Tj\n";
                $pdfContent .= "ET\n";
                $yPosition -= 20;
            }
        }
    } else {
        $pdfContent .= "BT\n";
        $pdfContent .= "/F1 12 Tf\n";
        $pdfContent .= "50 " . $yPosition . " Td\n";
        $pdfContent .= "(Keine Services ausgewählt) Tj\n";
        $pdfContent .= "ET\n";
        $yPosition -= 20;
    }
    
    $yPosition -= 30;
    
    // Contact info
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 12 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Für Rückfragen stehen wir Ihnen gerne unter Tel: 0431/54 63 00 zur Verfügung.) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 40;
    
    // Signature
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 12 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Mit freundlichem Gruß) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 20;
    
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 12 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Deniz Uludag) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 20;
    
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 12 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(B&E Autocentrum GmbH) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 40;
    
    // Disclaimer
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 10 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(Dieses Dokument wurde maschinell erstellt und ist ohne Unterschrift gültig) Tj\n";
    $pdfContent .= "ET\n";
    
    $pdf .= "3 0 obj\n";
    $pdf .= "<<\n";
    $pdf .= "/Type /Page\n";
    $pdf .= "/Parent 2 0 R\n";
    $pdf .= "/MediaBox [0 0 612 792]\n";
    $pdf .= "/Contents 4 0 R\n";
    $pdf .= ">>\n";
    $pdf .= "endobj\n\n";
    
    $pdf .= "4 0 obj\n";
    $pdf .= "<<\n";
    $pdf .= "/Length " . strlen($pdfContent) . "\n";
    $pdf .= ">>\n";
    $pdf .= "stream\n";
    $pdf .= $pdfContent;
    $pdf .= "endstream\n";
    $pdf .= "endobj\n\n";
    
    $pdf .= "xref\n";
    $pdf .= "0 5\n";
    $pdf .= "0000000000 65535 f \n";
    $pdf .= "0000000009 00000 n \n";
    $pdf .= "0000000058 00000 n \n";
    $pdf .= "0000000115 00000 n \n";
    $pdf .= "0000000204 00000 n \n";
    $pdf .= "trailer\n";
    $pdf .= "<<\n";
    $pdf .= "/Size 5\n";
    $pdf .= "/Root 1 0 R\n";
    $pdf .= ">>\n";
    $pdf .= "startxref\n";
    $pdf .= "0\n";
    $pdf .= "%%EOF\n";
    
    return $pdf;
}

function escapePDFText($text) {
    // Ensure proper UTF-8 encoding
    $text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
    
    // Convert German characters to their Latin-1 equivalents
    $replacements = [
        'ä' => chr(228),
        'ö' => chr(246),
        'ü' => chr(252),
        'Ä' => chr(196),
        'Ö' => chr(214),
        'Ü' => chr(220),
        'ß' => chr(223),
        '€' => chr(128)
    ];
    
    foreach ($replacements as $char => $replacement) {
        $text = str_replace($char, $replacement, $text);
    }
    
    // Escape special PDF characters
    $text = str_replace(['(', ')', '\\'], ['\\(', '\\)', '\\\\'], $text);
    
    return $text;
}

function getServiceById($serviceId, $conn) {
    $stmt = $conn->prepare("SELECT service_name, price FROM autohaus_services WHERE id = ? AND is_active = 1");
    $stmt->execute([$serviceId]);
    return $stmt->fetch();
}
?>
