<?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 HTML content
    $htmlContent = generateHTMLContent($appointment, $selectedTires, $newTires, $selectedServices, $conn);
    
    // Try to use wkhtmltopdf if available
    $pdfContent = generatePDFFromHTML($htmlContent);
    
    // 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 generateHTMLContent($appointment, $selectedTires, $newTires, $selectedServices, $conn) {
    $html = '<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reifenangebot</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            font-size: 12px;
            line-height: 1.4;
            margin: 20px;
            color: #000;
        }
        .header {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 20px;
        }
        .date {
            margin-bottom: 30px;
        }
        .section-title {
            font-size: 14px;
            font-weight: bold;
            margin-top: 20px;
            margin-bottom: 10px;
        }
        .tire-item {
            margin-bottom: 5px;
        }
        .disclaimer {
            font-size: 10px;
            color: #dc2626;
            margin-top: 30px;
        }
        .contact {
            margin-top: 20px;
        }
        .signature {
            margin-top: 20px;
        }
    </style>
</head>
<body>';
    
    // Company header
    $html .= '<div class="header">B&E Autocentrum GmbH</div>';
    $html .= '<div class="date">Kiel, ' . date('d.m.Y') . '</div>';
    
    // Greeting
    $html .= '<p>Sehr geehrte Damen und Herren,</p>';
    $html .= '<br>';
    
    // Main text
    $html .= '<p>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.</p>';
    $html .= '<br>';
    $html .= '<p>Daher erhalten Sie mit diesem Schreiben das beigefügte Angebot.</p>';
    $html .= '<br>';
    
    // Selected tires section
    $html .= '<div class="section-title">Auszutauschender Reifen:</div>';
    if (!empty($selectedTires)) {
        foreach ($selectedTires as $tire) {
            $tireText = '- ' . htmlspecialchars($tire['brand']) . ' ' . htmlspecialchars($tire['model']) . ' (' . htmlspecialchars($tire['size']) . ') - Position: ' . htmlspecialchars($tire['position']) . ' - ' . htmlspecialchars($tire['recommendation']);
            $html .= '<div class="tire-item">' . $tireText . '</div>';
        }
    } else {
        $html .= '<div class="tire-item">Keine Reifen ausgewählt</div>';
    }
    
    $html .= '<br>';
    
    // New tires section
    $html .= '<div class="section-title">Neue Reifen:</div>';
    if (!empty($newTires)) {
        foreach ($newTires as $tire) {
            $tireText = '- ' . htmlspecialchars($tire['brand']) . ' (' . htmlspecialchars($tire['size']) . ') - ' . $tire['quantity'] . 'x ' . number_format($tire['price'], 2, ',', '.') . '€';
            $html .= '<div class="tire-item">' . $tireText . '</div>';
        }
    } else {
        $html .= '<div class="tire-item">Keine neuen Reifen hinzugefügt</div>';
    }
    
    $html .= '<br>';
    
    // Costs section
    $html .= '<div class="section-title">Kosten inkl. Reifenmontage:</div>';
    $html .= '<div class="tire-item">Zzgl.</div>';
    $html .= '<div class="tire-item">Rädermontage                    49,99€</div>';
    $html .= '<div class="tire-item">Einlagerung der Sommerreifen     85,00€</div>';
    
    // 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, ',', '.') . '€';
                $html .= '<div class="tire-item">' . htmlspecialchars($serviceText) . '</div>';
            }
        }
    } else {
        $html .= '<div class="tire-item">Keine Services ausgewählt</div>';
    }
    
    $html .= '<br>';
    
    // Contact info
    $html .= '<div class="contact">Für Rückfragen stehen wir Ihnen gerne unter Tel: 0431/54 63 00 zur Verfügung.</div>';
    $html .= '<br>';
    
    // Signature
    $html .= '<div class="signature">Mit freundlichem Gruß<br>Deniz Uludag<br>B&E Autocentrum GmbH</div>';
    
    // Disclaimer
    $html .= '<div class="disclaimer">Dieses Dokument wurde maschinell erstellt und ist ohne Unterschrift gültig</div>';
    
    $html .= '</body></html>';
    
    return $html;
}

function generatePDFFromHTML($htmlContent) {
    // Try wkhtmltopdf first
    if (function_exists('shell_exec') && !empty(shell_exec('which wkhtmltopdf'))) {
        return generateWithWkhtmltopdf($htmlContent);
    }
    
    // Try mPDF if available
    if (class_exists('Mpdf\Mpdf')) {
        return generateWithMpdf($htmlContent);
    }
    
    // Fallback to simple HTML-to-text conversion
    return generateSimplePDF($htmlContent);
}

function generateWithWkhtmltopdf($htmlContent) {
    $tempHtmlFile = tempnam(sys_get_temp_dir(), 'offer_') . '.html';
    $tempPdfFile = tempnam(sys_get_temp_dir(), 'offer_') . '.pdf';
    
    file_put_contents($tempHtmlFile, $htmlContent);
    
    $command = "wkhtmltopdf --encoding UTF-8 --page-size A4 --margin-top 20mm --margin-bottom 20mm --margin-left 20mm --margin-right 20mm '$tempHtmlFile' '$tempPdfFile'";
    
    $output = shell_exec($command);
    
    if (file_exists($tempPdfFile)) {
        $pdfContent = file_get_contents($tempPdfFile);
        unlink($tempHtmlFile);
        unlink($tempPdfFile);
        return $pdfContent;
    }
    
    // Cleanup on failure
    if (file_exists($tempHtmlFile)) unlink($tempHtmlFile);
    if (file_exists($tempPdfFile)) unlink($tempPdfFile);
    
    throw new Exception('wkhtmltopdf conversion failed');
}

function generateWithMpdf($htmlContent) {
    $mpdf = new \Mpdf\Mpdf([
        'mode' => 'utf-8',
        'format' => 'A4',
        'margin_left' => 20,
        'margin_right' => 20,
        'margin_top' => 20,
        'margin_bottom' => 20
    ]);
    
    $mpdf->WriteHTML($htmlContent);
    return $mpdf->Output('', 'S');
}

function generateSimplePDF($htmlContent) {
    // Convert HTML to plain text with basic formatting
    $text = strip_tags($htmlContent);
    $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
    
    // Split into lines
    $lines = explode("\n", $text);
    
    // Create simple 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";
    
    // Create content
    $pdfContent = "";
    $yPosition = 750;
    
    foreach ($lines as $line) {
        $line = trim($line);
        if (empty($line)) {
            $yPosition -= 10;
            continue;
        }
        
        // Handle special formatting
        if (strpos($line, 'B&E Autocentrum GmbH') !== false) {
            $pdfContent .= "BT\n";
            $pdfContent .= "/F1 16 Tf\n";
            $pdfContent .= "50 " . $yPosition . " Td\n";
            $pdfContent .= "(" . escapePDFText($line) . ") Tj\n";
            $pdfContent .= "ET\n";
            $yPosition -= 25;
        } elseif (strpos($line, 'Auszutauschender Reifen:') !== false || 
                  strpos($line, 'Neue Reifen:') !== false || 
                  strpos($line, 'Kosten inkl. Reifenmontage:') !== false) {
            $pdfContent .= "BT\n";
            $pdfContent .= "/F1 14 Tf\n";
            $pdfContent .= "50 " . $yPosition . " Td\n";
            $pdfContent .= "(" . escapePDFText($line) . ") Tj\n";
            $pdfContent .= "ET\n";
            $yPosition -= 20;
        } elseif (strpos($line, 'Dieses Dokument wurde maschinell erstellt') !== false) {
            $pdfContent .= "BT\n";
            $pdfContent .= "/F1 10 Tf\n";
            $pdfContent .= "50 " . $yPosition . " Td\n";
            $pdfContent .= "(" . escapePDFText($line) . ") Tj\n";
            $pdfContent .= "ET\n";
            $yPosition -= 15;
        } else {
            $pdfContent .= "BT\n";
            $pdfContent .= "/F1 12 Tf\n";
            $pdfContent .= "50 " . $yPosition . " Td\n";
            $pdfContent .= "(" . escapePDFText($line) . ") Tj\n";
            $pdfContent .= "ET\n";
            $yPosition -= 15;
        }
        
        if ($yPosition < 50) break; // Prevent overflow
    }
    
    $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');
    
    // 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();
}
?>
