<?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, Access-Control-Allow-Headers, Authorization, X-Requested-With');

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'] ?? [];
    $offerContent = $input['offerContent'] ?? '';
    
    if (!$appointmentId) {
        throw new Exception('Termin ID ist erforderlich');
    }
    
    // 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 = generatePDFContent($appointment, $selectedTires, $newTires, $selectedServices, $offerContent);
    
    // Save PDF to temp directory
    $filename = 'angebot_' . $appointmentId . '_' . date('Y-m-d_H-i-s') . '.pdf';
    $filepath = '../temp/' . $filename;
    
    if (!is_dir('../temp')) {
        mkdir('../temp', 0755, true);
    }
    
    // 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 generatePDFContent($appointment, $selectedTires, $newTires, $selectedServices, $offerContent) {
    // Create PDF directly from data - no HTML conversion needed!
    return createProfessionalPDF($appointment, $selectedTires, $newTires, $selectedServices);
}

function createProfessionalPDF($appointment, $selectedTires, $newTires, $selectedServices) {
    // Create a professional PDF structure directly from data
    $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 PDF content directly from data
    $pdfContent = "";
    $yPosition = 750; // Start from top
    
    // Company header (larger font)
    $pdfContent .= "BT\n";
    $pdfContent .= "/F1 16 Tf\n";
    $pdfContent .= "50 " . $yPosition . " Td\n";
    $pdfContent .= "(B&E Autocentrum GmbH) Tj\n";
    $pdfContent .= "ET\n";
    $yPosition -= 20;
    
    // 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 paragraphs
    $paragraphs = [
        "die Vorbereitungen für unseren nächsten Boxenstopp laufen bereits und dabei ist uns leider aufgefallen, dass die bei uns eingelagerten Reifen ersetzt werden müssten.",
        "Daher erhalten Sie mit diesem Schreiben das beigefügte Angebot."
    ];
    
    foreach ($paragraphs as $paragraph) {
        $pdfContent .= "BT\n";
        $pdfContent .= "/F1 12 Tf\n";
        $pdfContent .= "50 " . $yPosition . " Td\n";
        $pdfContent .= "(" . addslashes($paragraph) . ") Tj\n";
        $pdfContent .= "ET\n";
        $yPosition -= 30;
    }
    
    $yPosition -= 20; // Extra space
    
    // 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 .= "(" . addslashes($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; // Extra space
    
    // 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 .= "(" . addslashes($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; // Extra space
    
    // 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);
            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 .= "(" . addslashes($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; // Extra space
    
    // 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 (smaller font)
    $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 getServiceById($serviceId) {
    global $conn;
    $stmt = $conn->prepare("SELECT service_name, price FROM autohaus_services WHERE id = ? AND is_active = 1");
    $stmt->execute([$serviceId]);
    return $stmt->fetch();
}

function generatePDFWithWkhtmltopdf($offerContent, $appointment) {
    // Create temporary HTML file
    $htmlFile = tempnam(sys_get_temp_dir(), 'offer_') . '.html';
    $pdfFile = tempnam(sys_get_temp_dir(), 'offer_') . '.pdf';
    
    // Create complete HTML document
    $html = createCompleteHTMLDocument($offerContent, $appointment);
    
    // Write HTML to file
    file_put_contents($htmlFile, $html);
    
    // Convert HTML to PDF using wkhtmltopdf
    $command = "wkhtmltopdf --page-size A4 --margin-top 2cm --margin-bottom 2cm --margin-left 2cm --margin-right 2cm --encoding UTF-8 '$htmlFile' '$pdfFile'";
    $output = shell_exec($command);
    
    // Read PDF content
    $pdfContent = file_get_contents($pdfFile);
    
    // Clean up temporary files
    unlink($htmlFile);
    unlink($pdfFile);
    
    return $pdfContent;
}

function generatePDFSimple($offerContent, $appointment) {
    // Fallback: Create a simple PDF that matches the preview structure
    $content = createStructuredContent($offerContent);
    return createSimplePDF($content, $appointment);
}

function createStructuredContent($offerContent) {
    // Parse the HTML content and create structured text
    $content = $offerContent;
    
    // Convert HTML to structured text
    $content = html_entity_decode($content, ENT_QUOTES, 'UTF-8');
    
    // Handle line breaks
    $content = str_replace('<br>', "\n", $content);
    $content = str_replace('<br/>', "\n", $content);
    $content = str_replace('<br />', "\n", $content);
    
    // Handle paragraphs
    $content = str_replace('</p>', "\n\n", $content);
    $content = str_replace('<p>', "", $content);
    
    // Remove formatting tags
    $content = str_replace('<strong>', "", $content);
    $content = str_replace('</strong>', "", $content);
    $content = str_replace('<span style="font-size: 0.8em; color: #dc2626;">', "", $content);
    $content = str_replace('</span>', "", $content);
    
    // Remove any remaining HTML tags
    $content = strip_tags($content);
    
    // Clean up multiple line breaks
    $content = preg_replace('/\n{3,}/', "\n\n", $content);
    
    // UTF-8 encoding
    $content = mb_convert_encoding($content, 'UTF-8', 'UTF-8');
    
    return $content;
}

function createCompleteHTMLDocument($offerContent, $appointment) {
    // Create a complete HTML document with proper CSS for PDF generation
    $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Reifenangebot</title>
    <style>
        @page {
            margin: 2cm;
            size: A4;
        }
        
        body {
            font-family: Arial, sans-serif;
            font-size: 12px;
            line-height: 1.4;
            color: #000;
            margin: 0;
            padding: 0;
        }
        
        .company-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .date {
            margin-bottom: 20px;
        }
        
        .greeting {
            margin-bottom: 15px;
        }
        
        .paragraph {
            margin-bottom: 15px;
            text-align: justify;
        }
        
        .section-title {
            font-size: 14px;
            font-weight: bold;
            margin: 20px 0 10px 0;
        }
        
        .tire-item {
            margin: 5px 0;
            padding-left: 20px;
        }
        
        .costs-section {
            margin: 15px 0;
        }
        
        .cost-item {
            margin: 3px 0;
            font-family: monospace;
        }
        
        .contact {
            margin: 20px 0;
        }
        
        .signature {
            margin: 20px 0;
        }
        
        .disclaimer {
            font-size: 10px;
            color: #dc2626;
            margin-top: 20px;
        }
        
        .line-break {
            margin: 10px 0;
        }
    </style>
</head>
<body>
    ' . $offerContent . '
</body>
</html>';
    
    return $html;
}

function convertHTMLToPDF($html) {
    // Simple HTML to PDF conversion using basic PDF structure
    // This creates a PDF that preserves the HTML formatting
    
    // Clean up HTML for PDF generation
    $html = str_replace('<br>', '<br/>', $html);
    $html = str_replace('<br/>', '<br/>', $html);
    
    // Create PDF structure
    $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";
    
    // Convert HTML content to PDF text
    $pdfContent = convertHTMLContentToPDF($html);
    
    $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 convertHTMLContentToPDF($html) {
    // Extract content between body tags
    preg_match('/<body[^>]*>(.*?)<\/body>/s', $html, $matches);
    $content = isset($matches[1]) ? $matches[1] : $html;
    
    // Convert HTML to plain text while preserving structure
    $content = html_entity_decode($content, ENT_QUOTES, 'UTF-8');
    
    // Handle different HTML elements
    $content = str_replace('<br/>', "\n", $content);
    $content = str_replace('<br>', "\n", $content);
    $content = str_replace('</p>', "\n\n", $content);
    $content = str_replace('<p>', "", $content);
    $content = str_replace('<strong>', "", $content);
    $content = str_replace('</strong>', "", $content);
    $content = str_replace('<span style="font-size: 0.8em; color: #dc2626;">', "", $content);
    $content = str_replace('</span>', "", $content);
    
    // Remove any remaining HTML tags
    $content = strip_tags($content);
    
    // Clean up multiple line breaks
    $content = preg_replace('/\n{3,}/', "\n\n", $content);
    
    // Convert to PDF format
    $lines = explode("\n", $content);
    $pdfContent = "";
    $yPosition = 750; // Start from top
    
    foreach ($lines as $line) {
        if (trim($line) === '') {
            $yPosition -= 12; // Standard gap for empty lines
            continue;
        }
        
        // Determine font size based on content
        $fontSize = 12;
        if (strpos($line, 'B&E Autocentrum GmbH') !== false) {
            $fontSize = 16;
        } elseif (strpos($line, 'Auszutauschender Reifen:') !== false || 
                  strpos($line, 'Neue Reifen:') !== false || 
                  strpos($line, 'Kosten inkl. Reifenmontage:') !== false) {
            $fontSize = 14;
        } elseif (strpos($line, 'Dieses Dokument wurde maschinell erstellt') !== false) {
            $fontSize = 10;
        }
        
        $pdfContent .= "BT\n";
        $pdfContent .= "/F1 {$fontSize} Tf\n";
        $pdfContent .= "50 " . $yPosition . " Td\n";
        
        // Escape special characters for PDF
        $escapedLine = str_replace(['(', ')', '\\'], ['\\(', '\\)', '\\\\'], $line);
        $pdfContent .= "({$escapedLine}) Tj\n";
        $pdfContent .= "ET\n";
        
        $yPosition -= ($fontSize + 6); // Move down based on font size
    }
    
    return $pdfContent;
}

function createSimplePDF($content, $appointment) {
    // Create a properly formatted PDF with correct line spacing
    $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";
    
    // Convert content to PDF format with proper line spacing
    $lines = explode("\n", $content);
    $pdfContent = "";
    $yPosition = 750; // Start from top
    
    foreach ($lines as $index => $line) {
        // Handle empty lines
        if (trim($line) === '') {
            $yPosition -= 12; // Standard gap for empty lines
            continue;
        }
        
        // Determine font size and formatting based on content
        $fontSize = 12;
        $isBold = false;
        
        if (strpos($line, 'B&E Autocentrum GmbH') !== false) {
            $fontSize = 16;
            $isBold = true;
        } elseif (strpos($line, 'Auszutauschender Reifen:') !== false || 
                  strpos($line, 'Neue Reifen:') !== false || 
                  strpos($line, 'Kosten inkl. Reifenmontage:') !== false) {
            $fontSize = 14;
            $isBold = true;
        } elseif (strpos($line, 'Dieses Dokument wurde maschinell erstellt') !== false) {
            $fontSize = 10;
        }
        
        $pdfContent .= "BT\n";
        $pdfContent .= "/F1 {$fontSize} Tf\n";
        $pdfContent .= "50 " . $yPosition . " Td\n";
        
        // Escape special characters for PDF
        $escapedLine = str_replace(['(', ')', '\\'], ['\\(', '\\)', '\\\\'], $line);
        $pdfContent .= "({$escapedLine}) Tj\n";
        $pdfContent .= "ET\n";
        
        $yPosition -= ($fontSize + 6); // Move down based on font size
    }
    
    $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;
}
?>
