<?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';

// Include TCPDF
require_once '../vendor/tcpdf/tcpdf.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 professional PDF with TCPDF
    $pdfContent = generateProfessionalPDF($appointment, $selectedTires, $newTires, $selectedServices, $conn);
    
    // Create filename - use same format as frontend
    $customerName = $appointment['customer_name'] ?? 'Kunde';
    $filename = 'Angebot_' . $customerName . '_' . date('Y-m-d') . '.pdf';
    $filename = preg_replace('/[^a-zA-Z0-9._-]/', '_', $filename); // Sichere Dateinamen
    
    // Create uploads directory if it doesn't exist
    $uploadDir = '../uploads/offers/';
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // Save PDF to file
    $filepath = $uploadDir . $filename;
    file_put_contents($filepath, $pdfContent);
    
    // Return PDF content directly for download
    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 generateProfessionalPDF($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 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();
}
?>
