<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once '../config/database.php';

// Debug-Logging
function debugLog($message) {
    $logFile = '../logs/tire_offer_debug.log';
    $timestamp = date('Y-m-d H:i:s');
    if (!file_exists(dirname($logFile))) {
        mkdir(dirname($logFile), 0755, true);
    }
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND | LOCK_EX);
}

// Einfache PDF-Klasse ohne externe Bibliotheken
class SimplePDF {
    private $content = '';
    private $filename;
    
    public function __construct($filename) {
        $this->filename = $filename;
    }
    
    public function addHeader($title) {
        $this->content .= "<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>$title</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 20px; }
        .header { text-align: center; border-bottom: 3px solid #007bff; padding-bottom: 20px; margin-bottom: 30px; }
        .header h1 { color: #007bff; margin: 0; font-size: 28px; }
        .header .subtitle { color: #666; margin: 5px 0 0 0; font-size: 14px; }
        .section { margin-bottom: 25px; }
        .section-title { background: #f8f9fa; padding: 10px 15px; border-left: 4px solid #007bff; font-weight: bold; font-size: 16px; margin-bottom: 15px; }
        .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; }
        .info-item { padding: 10px; background: #f8f9fa; border-radius: 5px; }
        .info-label { font-weight: bold; color: #007bff; margin-bottom: 5px; }
        .tire-card { border: 1px solid #ddd; border-radius: 8px; padding: 15px; margin-bottom: 15px; background: white; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .tire-position { font-weight: bold; color: #007bff; font-size: 18px; margin-bottom: 10px; }
        .tire-details { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
        .tire-detail { margin-bottom: 8px; }
        .tire-detail strong { color: #333; }
        .footer { margin-top: 40px; padding-top: 20px; border-top: 2px solid #007bff; text-align: center; color: #666; font-size: 12px; }
        @media print { body { margin: 0; } }
    </style>
</head>
<body>
    <div class='header'>
        <h1>$title</h1>
        <div class='subtitle'>Erstellt am " . date('d.m.Y H:i') . "</div>
    </div>";
    }
    
    public function addSection($title, $content) {
        $this->content .= "
    <div class='section'>
        <div class='section-title'>$title</div>
        $content
    </div>";
    }
    
    public function addTireCard($position, $tire) {
        $conditionColor = '';
        $conditionText = $tire['condition'] ?? 'Unbekannt';
        
        switch(strtolower($conditionText)) {
            case 'keine fehler':
                $conditionColor = '#28a745';
                break;
            case 'leichte fehler':
                $conditionColor = '#ffc107';
                break;
            case 'austausch notwendig':
                $conditionColor = '#dc3545';
                break;
        }
        
        $this->content .= "
    <div class='tire-card'>
        <div class='tire-position'>Position: $position</div>
        <div class='tire-details'>
            <div class='tire-detail'><strong>Marke:</strong> " . htmlspecialchars($tire['brand'] ?? '') . "</div>
            <div class='tire-detail'><strong>Modell:</strong> " . htmlspecialchars($tire['model'] ?? '') . "</div>
            <div class='tire-detail'><strong>Größe:</strong> " . htmlspecialchars($tire['size'] ?? '') . "</div>
            <div class='tire-detail'><strong>DOT:</strong> " . htmlspecialchars($tire['dot'] ?? '') . "</div>
            <div class='tire-detail'><strong>Typ:</strong> " . htmlspecialchars($tire['type'] ?? '') . "</div>
            <div class='tire-detail'><strong>Zustand:</strong> <span style='color: $conditionColor; font-weight: bold;'>" . htmlspecialchars($conditionText) . "</span></div>
        </div>
    </div>";
    }
    
    public function addFooter($text) {
        $this->content .= "
    <div class='footer'>
        $text
    </div>
</body>
</html>";
    }
    
    public function addProfessionalLetter($customerData, $appointment, $tireData, $additionalServices, $conn) {
        // Hole aktuelle Daten
        $currentDate = date('d.m.Y');
        $currentLocation = 'Kiel'; // Kann aus Autohaus-Daten kommen
        
        // Hole Autohaus-Details
        $autohausName = $appointment['autohaus_name'] ?? 'Autohaus';
        $autohausPhone = $appointment['autohaus_phone'] ?? '';
        $contactPerson = 'Herr Uludag'; // Kann aus Autohaus-Daten kommen
        
        // Kunden-Daten
        $customerName = $customerData['name'] ?? '';
        $licensePlate = $customerData['license_plate'] ?? '';
        $vehicleModel = $customerData['vehicle_model'] ?? '[bezeichnung]';
        
        // Bestimme Reifentyp basierend auf den ausgewählten Reifen
        $tireType = 'Räder'; // Standard
        if (!empty($tireData)) {
            $firstTire = reset($tireData);
            $tireTypeSpan = $firstTire['tire_type'] ?? '';
            if (strpos(strtolower($tireTypeSpan), 'winter') !== false) {
                $tireType = 'Winterräder';
            } elseif (strpos(strtolower($tireTypeSpan), 'ganzjahr') !== false || strpos(strtolower($tireTypeSpan), 'allseason') !== false) {
                $tireType = 'Ganzjahresräder';
            } else {
                $tireType = 'Sommerräder';
            }
        }
        
        // Bestimme Anrede
        $salutation = 'Sehr geehrte Damen und Herren';
        if (strpos(strtolower($customerName), 'herr') !== false) {
            $salutation = 'Sehr geehrter Herr ' . str_replace(['Herr', 'herr'], '', $customerName);
        } elseif (strpos(strtolower($customerName), 'frau') !== false) {
            $salutation = 'Sehr geehrte Frau ' . str_replace(['Frau', 'frau'], '', $customerName);
        }
        
        // Reifen-Zustand übersetzen
        $tireConditions = [
            'good' => 'Sehr gut',
            'bad' => 'Austausch notwendig', 
            'not good' => 'Leichte Fehler'
        ];
        
        // Zusatzleistungen sammeln
        $additionalServicesText = '';
        $totalAdditionalCost = 0;
        
        if (!empty($additionalServices)) {
            $serviceIds = implode(',', array_map('intval', $additionalServices));
            $stmt = $conn->prepare("
                SELECT service_name, service_description, price, show_price 
                FROM autohaus_services 
                WHERE id IN ($serviceIds) AND is_active = 1
            ");
            $stmt->execute();
            $services = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($services as $service) {
                if ($service['show_price'] && $service['price']) {
                    $totalAdditionalCost += $service['price'];
                    $additionalServicesText .= "<div style='display: flex; justify-content: space-between; margin-bottom: 8px;'>
                        <span>" . htmlspecialchars($service['service_name']) . "</span>
                        <span>" . number_format($service['price'], 2) . " €</span>
                    </div>";
                }
            }
        }
        
        // Standard-Kosten
        $wheelMountingCost = 49.99;
        $storageCost = 85.00;
        
        $this->content = "
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>Anschreiben Reifenangebot</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            margin: 0; 
            padding: 20px; 
            line-height: 1.6;
            color: #333;
        }
        .letter-container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
        }
        .header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 40px;
        }
        .recipient {
            width: 40%;
        }
        .sender {
            width: 40%;
            text-align: right;
        }
        .subject {
            font-weight: bold;
            margin: 30px 0 20px 0;
            font-size: 16px;
        }
        .salutation {
            margin-bottom: 20px;
        }
        .content {
            margin-bottom: 30px;
        }
        .cost-breakdown {
            margin: 20px 0;
        }
        .cost-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
        }
        .contact-info {
            margin: 30px 0;
        }
        .closing {
            margin-top: 40px;
        }
        .footer {
            margin-top: 60px;
            font-size: 12px;
            color: #dc3545;
        }
        .tire-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
        }
        .tire-item {
            margin-bottom: 8px;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class='letter-container'>
        <div class='header'>
            <div class='recipient'>
                <div>$customerName</div>
            </div>
            <div class='sender'>
                <div>$currentLocation, $currentDate</div>
                <div>$contactPerson</div>
            </div>
        </div>
        
        <div class='subject'>
            eingelagerte $tireType für Ihren $vehicleModel<br>
            amtl. Kennzeichen: $licensePlate
        </div>
        
        <div class='salutation'>
            $salutation,
        </div>
        
        <div class='content'>
            <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, siehe Prüfbericht.</p>
            
            <p>Daher erhalten Sie mit diesem Schreiben das beigefügte Angebot.</p>
            
            <p>Kosten inkl. Reifenmontage (siehe Angebot im Anhang):</p>
        </div>
        
        <div class='cost-breakdown'>
            <div class='cost-item'>
                <span>Zzgl.</span>
            </div>
            <div class='cost-item'>
                <span>Rädermontage</span>
                <span>" . number_format($wheelMountingCost, 2) . " €</span>
            </div>
            <div class='cost-item'>
                <span>Einlagerung der Sommerreifen</span>
                <span>" . number_format($storageCost, 2) . " €</span>
            </div>
            $additionalServicesText
        </div>
        
        <div class='tire-info'>
            <strong>Ausgewählte Reifen:</strong><br>";
        
        // Reifen-Informationen hinzufügen
        foreach ($tireData as $position => $tire) {
            $condition = $tire['condition'] ?? 'good';
            $conditionGerman = $tireConditions[$condition] ?? 'Sehr gut';
            $tireSize = $tire['size'] ?? '';
            $tireBrand = $tire['brand'] ?? '';
            $tireModel = $tire['model'] ?? '';
            
            $this->content .= "
            <div class='tire-item'>
                <strong>$position:</strong> $tireBrand $tireModel $tireSize - Zustand: $conditionGerman
            </div>";
        }
        
        $this->content .= "
        </div>
        
        <div class='contact-info'>
            Für Rückfragen stehen wir Ihnen gerne unter Tel: $autohausPhone zur Verfügung
        </div>
        
        <div class='closing'>
            <div>Mit freundlichem Gruß</div>
            <div>$contactPerson</div>
            <div>$autohausName</div>
        </div>
        
        <div class='footer'>
            Dieses Dokument wurde maschinell erstellt und ist ohne Unterschrift gültig
        </div>
    </div>
</body>
</html>";
    }
    
    public function save() {
        return file_put_contents($this->filename, $this->content);
    }
    
    public function getContent() {
        return $this->content;
    }
}

try {
    $db = new Database();
    $conn = $db->getConnection();

    $data = json_decode(file_get_contents('php://input'), true);
    $action = $data['action'] ?? '';
    $appointmentId = $data['appointment_id'] ?? null;

    debugLog("Action: $action, Appointment ID: $appointmentId");

    // Fetch appointment data to get customer info and autohaus_id
    $stmt = $conn->prepare("
        SELECT a.*, ah.name as autohaus_name, ah.address as autohaus_address, ah.phone as autohaus_phone, ah.email as autohaus_email
        FROM appointments a
        LEFT JOIN autohaus ah ON a.autohaus_id = ah.id
        WHERE a.id = ?
    ");
    $stmt->execute([$appointmentId]);
    $appointment = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$appointment) {
        echo json_encode(['success' => false, 'error' => 'Appointment not found.']);
        exit;
    }

    $customerData = $data['customer_data'] ?? [];
    $tireData = $data['tire_data'] ?? [];
    $additionalServices = $data['additional_services'] ?? [];

    // Define paths for generated and merged PDFs
    $uploadDir = '../uploads/tire_offers/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    $customerPdfPath = $uploadDir . 'offer_customer_' . $appointmentId . '.html';
    $mergedPdfPath = $uploadDir . 'offer_merged_' . $appointmentId . '.html';
    $uploadedPdfPath = $uploadDir . 'offer_uploaded_' . $appointmentId . '.html';

    if ($action === 'generate_customer_pdf') {
        $pdf = new SimplePDF($customerPdfPath);
        
        // Professionelles Anschreiben wie im Bild
        $pdf->addProfessionalLetter($customerData, $appointment, $tireData, $additionalServices, $conn);
        
        if ($pdf->save()) {
            echo json_encode([
                'success' => true, 
                'filename' => basename($customerPdfPath), 
                'path' => $customerPdfPath,
                'url' => '../uploads/tire_offers/' . basename($customerPdfPath),
                'message' => 'Kunden-Dokument erfolgreich erstellt'
            ]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Fehler beim Speichern des Dokuments.']);
        }

    } elseif ($action === 'upload_pdf') {
        // Handle file upload
        if (isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] === UPLOAD_ERR_OK) {
            $uploadedFile = $_FILES['pdf_file'];
            $originalName = $uploadedFile['name'];
            $fileExtension = pathinfo($originalName, PATHINFO_EXTENSION);
            $uploadPath = $uploadDir . 'uploaded_' . $appointmentId . '_' . time() . '.' . $fileExtension;
            
            // Validate file type
            $allowedTypes = ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp'];
            if (!in_array(strtolower($fileExtension), $allowedTypes)) {
                echo json_encode(['success' => false, 'error' => 'Dateityp nicht unterstützt.']);
                exit;
            }
            
            // Validate file size (10MB max)
            if ($uploadedFile['size'] > 10 * 1024 * 1024) {
                echo json_encode(['success' => false, 'error' => 'Datei zu groß. Maximale Größe: 10 MB']);
                exit;
            }
            
            if (move_uploaded_file($uploadedFile['tmp_name'], $uploadPath)) {
                // If it's an image, create an HTML wrapper
                if (in_array(strtolower($fileExtension), ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp'])) {
                    $htmlPath = $uploadDir . 'uploaded_' . $appointmentId . '_' . time() . '.html';
                    $imageHtml = '
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <meta charset="UTF-8">
                        <title>Hochgeladenes Bild</title>
                        <style>
                            body { margin: 0; padding: 20px; text-align: center; font-family: Arial, sans-serif; }
                            img { max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
                            .header { margin-bottom: 20px; color: #007bff; }
                        </style>
                    </head>
                    <body>
                        <div class="header">
                            <h2>Hochgeladenes Dokument</h2>
                            <p>Originaldatei: ' . htmlspecialchars($originalName) . '</p>
                        </div>
                        <img src="' . basename($uploadPath) . '" alt="Hochgeladenes Bild">
                    </body>
                    </html>';
                    
                    file_put_contents($htmlPath, $imageHtml);
                    $uploadPath = $htmlPath;
                }
                
                echo json_encode([
                    'success' => true, 
                    'message' => 'Datei erfolgreich hochgeladen.', 
                    'path' => $uploadPath,
                    'filename' => basename($uploadPath),
                    'original_name' => $originalName
                ]);
            } else {
                echo json_encode(['success' => false, 'error' => 'Fehler beim Hochladen der Datei.']);
            }
        } else {
            echo json_encode(['success' => false, 'error' => 'Keine Datei hochgeladen.']);
        }

    } elseif ($action === 'merge_pdfs') {
        // Merge customer PDF with uploaded PDF
        $customerPdfPath = $uploadDir . 'offer_customer_' . $appointmentId . '.html';
        $mergedPdfPath = $uploadDir . 'offer_merged_' . $appointmentId . '.html';
        
        if (!file_exists($customerPdfPath)) {
            echo json_encode(['success' => false, 'error' => 'Kunden-Dokument nicht gefunden.']);
            exit;
        }
        
        // Find uploaded file
        $uploadedFiles = glob($uploadDir . 'uploaded_' . $appointmentId . '_*.html');
        $uploadedFile = !empty($uploadedFiles) ? $uploadedFiles[0] : null;
        
        $mergedContent = '';
        
        // Add uploaded content first if exists
        if ($uploadedFile && file_exists($uploadedFile)) {
            $uploadedContent = file_get_contents($uploadedFile);
            $mergedContent .= $uploadedContent . '<div style="page-break-before: always;"></div>';
        }
        
        // Add customer content
        $customerContent = file_get_contents($customerPdfPath);
        $mergedContent .= $customerContent;
        
        if (file_put_contents($mergedPdfPath, $mergedContent)) {
            echo json_encode([
                'success' => true, 
                'filename' => basename($mergedPdfPath), 
                'path' => $mergedPdfPath,
                'url' => '../uploads/tire_offers/' . basename($mergedPdfPath),
                'message' => 'Dokumente erfolgreich zusammengeführt'
            ]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Fehler beim Zusammenführen der Dokumente.']);
        }

    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid action.']);
    }

} catch (Exception $e) {
    debugLog("Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Database connection failed: ' . $e->getMessage()]);
}
?>