<?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 using TCPDF
    $pdfContent = generatePDFWithTCPDF($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 generatePDFWithTCPDF($appointment, $selectedTires, $newTires, $selectedServices, $conn) {
    // For now, always use the improved manual PDF generation
    // TCPDF can be added later if needed
    return generateImprovedPDF($appointment, $selectedTires, $newTires, $selectedServices, $conn);
}

function generateWithTCPDF($appointment, $selectedTires, $newTires, $selectedServices, $conn) {
    // Create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    
    // Set document information
    $pdf->SetCreator('B&E Autocentrum');
    $pdf->SetAuthor('B&E Autocentrum');
    $pdf->SetTitle('Reifenangebot');
    $pdf->SetSubject('Reifenangebot');
    
    // Set margins
    $pdf->SetMargins(20, 20, 20);
    $pdf->SetHeaderMargin(10);
    $pdf->SetFooterMargin(10);
    
    // Add a page
    $pdf->AddPage();
    
    // Set font
    $pdf->SetFont('helvetica', '', 12);
    
    // Company header
    $pdf->SetFont('helvetica', 'B', 16);
    $pdf->Cell(0, 10, 'B&E Autocentrum GmbH', 0, 1, 'L');
    
    $pdf->SetFont('helvetica', '', 12);
    $pdf->Cell(0, 10, 'Kiel, ' . date('d.m.Y'), 0, 1, 'L');
    $pdf->Ln(10);
    
    // Greeting
    $pdf->Cell(0, 10, 'Sehr geehrte Damen und Herren,', 0, 1, 'L');
    $pdf->Ln(5);
    
    // Main text
    $pdf->MultiCell(0, 6, '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.', 0, 'L');
    $pdf->Ln(5);
    $pdf->MultiCell(0, 6, 'Daher erhalten Sie mit diesem Schreiben das beigefügte Angebot.', 0, 'L');
    $pdf->Ln(10);
    
    // Selected tires section
    $pdf->SetFont('helvetica', 'B', 14);
    $pdf->Cell(0, 10, 'Auszutauschender Reifen:', 0, 1, 'L');
    $pdf->SetFont('helvetica', '', 12);
    
    if (!empty($selectedTires)) {
        foreach ($selectedTires as $tire) {
            $tireText = '- ' . $tire['brand'] . ' ' . $tire['model'] . ' (' . $tire['size'] . ') - Position: ' . $tire['position'] . ' - ' . $tire['recommendation'];
            $pdf->Cell(0, 6, $tireText, 0, 1, 'L');
        }
    } else {
        $pdf->Cell(0, 6, 'Keine Reifen ausgewählt', 0, 1, 'L');
    }
    
    $pdf->Ln(10);
    
    // New tires section
    $pdf->SetFont('helvetica', 'B', 14);
    $pdf->Cell(0, 10, 'Neue Reifen:', 0, 1, 'L');
    $pdf->SetFont('helvetica', '', 12);
    
    if (!empty($newTires)) {
        foreach ($newTires as $tire) {
            $tireText = '- ' . $tire['brand'] . ' (' . $tire['size'] . ') - ' . $tire['quantity'] . 'x ' . number_format($tire['price'], 2, ',', '.') . '€';
            $pdf->Cell(0, 6, $tireText, 0, 1, 'L');
        }
    } else {
        $pdf->Cell(0, 6, 'Keine neuen Reifen hinzugefügt', 0, 1, 'L');
    }
    
    $pdf->Ln(10);
    
    // Costs section
    $pdf->SetFont('helvetica', 'B', 14);
    $pdf->Cell(0, 10, 'Kosten inkl. Reifenmontage:', 0, 1, 'L');
    $pdf->SetFont('helvetica', '', 12);
    
    $pdf->Cell(0, 6, 'Zzgl.', 0, 1, 'L');
    $pdf->Cell(0, 6, 'Rädermontage                    49,99€', 0, 1, 'L');
    $pdf->Cell(0, 6, 'Einlagerung der Sommerreifen     85,00€', 0, 1, 'L');
    
    // 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, ',', '.') . '€';
                $pdf->Cell(0, 6, $serviceText, 0, 1, 'L');
            }
        }
    } else {
        $pdf->Cell(0, 6, 'Keine Services ausgewählt', 0, 1, 'L');
    }
    
    $pdf->Ln(15);
    
    // Contact info
    $pdf->MultiCell(0, 6, 'Für Rückfragen stehen wir Ihnen gerne unter Tel: 0431/54 63 00 zur Verfügung.', 0, 'L');
    $pdf->Ln(15);
    
    // Signature
    $pdf->Cell(0, 6, 'Mit freundlichem Gruß', 0, 1, 'L');
    $pdf->Cell(0, 6, 'Deniz Uludag', 0, 1, 'L');
    $pdf->Cell(0, 6, 'B&E Autocentrum GmbH', 0, 1, 'L');
    $pdf->Ln(15);
    
    // Disclaimer
    $pdf->SetFont('helvetica', '', 10);
    $pdf->SetTextColor(220, 38, 38); // Red color
    $pdf->Cell(0, 6, 'Dieses Dokument wurde maschinell erstellt und ist ohne Unterschrift gültig', 0, 1, 'L');
    
    // Output PDF
    return $pdf->Output('', 'S');
}

function generateImprovedPDF($appointment, $selectedTires, $newTires, $selectedServices, $conn) {
    // Create PDF with proper UTF-8 encoding
    $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 with proper UTF-8 handling
    $pdfContent = "";
    $yPosition = 750;
    
    // 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 .= "(" . escapePDFText($paragraph) . ") Tj\n";
        $pdfContent .= "ET\n";
        $yPosition -= 30;
    }
    
    $yPosition -= 20;
    
    // 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 (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 escapePDFText($text) {
    // Ensure proper UTF-8 encoding
    $text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
    
    // Convert to ISO-8859-1 for PDF compatibility
    $text = mb_convert_encoding($text, 'ISO-8859-1', 'UTF-8');
    
    // Replace common German characters with their ISO-8859-1 equivalents
    $replacements = [
        'ä' => chr(228), // ä
        'ö' => chr(246), // ö
        'ü' => chr(252), // ü
        'Ä' => chr(196), // Ä
        'Ö' => chr(214), // Ö
        'Ü' => chr(220), // Ü
        'ß' => chr(223), // ß
        '€' => chr(128)  // € (if supported)
    ];
    
    // Convert back to UTF-8 for display
    $text = mb_convert_encoding($text, 'UTF-8', 'ISO-8859-1');
    
    // 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();
}
?>
