<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, 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");
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['autohaus_id'])) {
        throw new Exception('Autohaus ID ist erforderlich');
    }
    
    $autohausId = $input['autohaus_id'];
    
    // Hole Autohaus-Daten mit Teams-Einstellungen
    $stmt = $conn->prepare("
        SELECT 
            name as autohaus_name,
            teams_webhook_url,
            teams_channel_name,
            teams_notifications_enabled
        FROM autohaus 
        WHERE id = ?
    ");
    
    $stmt->execute([$autohausId]);
    $autohaus = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$autohaus) {
        throw new Exception('Autohaus nicht gefunden');
    }
    
    if (!$autohaus['teams_notifications_enabled'] || empty($autohaus['teams_webhook_url'])) {
        throw new Exception('Teams-Benachrichtigungen sind nicht konfiguriert');
    }
    
    // Erstelle Test-Nachricht
    $testMessage = [
        "@type" => "MessageCard",
        "@context" => "http://schema.org/extensions",
        "themeColor" => "0078D4",
        "summary" => "Test-Nachricht - Teams Integration",
        "sections" => [
            [
                "activityTitle" => "🧪 Teams-Integration Test",
                "activitySubtitle" => "Autohaus: **{$autohaus['autohaus_name']}**",
                "activityImage" => "https://img.icons8.com/color/48/000000/microsoft-teams.png",
                "facts" => [
                    [
                        "name" => "📅 Zeit",
                        "value" => date('d.m.Y H:i:s')
                    ],
                    [
                        "name" => "🏢 Autohaus",
                        "value" => $autohaus['autohaus_name']
                    ],
                    [
                        "name" => "📢 Channel",
                        "value" => $autohaus['teams_channel_name'] ?: 'Standard'
                    ],
                    [
                        "name" => "✅ Status",
                        "value" => "Integration funktioniert!"
                    ]
                ],
                "markdown" => true
            ],
            [
                "title" => "🎉 Test erfolgreich!",
                "text" => "Die Teams-Integration ist korrekt konfiguriert und funktioniert einwandfrei.\n\n**Nächste Schritte:**\n• Teams-Benachrichtigungen sind jetzt aktiv\n• Bei angenommenen Angeboten werden automatisch Nachrichten gesendet\n• Alle relevanten Informationen werden übertragen",
                "markdown" => true
            ]
        ],
        "potentialAction" => [
            [
                "@type" => "OpenUri",
                "name" => "📋 Admin-Dashboard öffnen",
                "targets" => [
                    [
                        "os" => "default",
                        "uri" => getBaseUrl() . "/admin/settings.php"
                    ]
                ]
            ]
        ]
    ];
    
    // Sende an Teams
    $result = sendToTeams($autohaus['teams_webhook_url'], $testMessage);
    
    if ($result['success']) {
        echo json_encode([
            'success' => true,
            'message' => 'Teams-Test erfolgreich gesendet',
            'channel' => $autohaus['teams_channel_name'] ?: 'Standard'
        ]);
    } else {
        throw new Exception('Teams-Fehler: ' . $result['error']);
    }
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

function sendToTeams($webhookUrl, $message) {
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $webhookUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return ['success' => false, 'error' => $error];
    }
    
    if ($httpCode >= 200 && $httpCode < 300) {
        return ['success' => true, 'response' => $response];
    } else {
        return ['success' => false, 'error' => "HTTP $httpCode: $response"];
    }
}

function getBaseUrl() {
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    
    if (strpos($host, ':') !== false) {
        return $protocol . '://' . $host;
    }
    
    $port = $_SERVER['SERVER_PORT'] ?? '';
    $port = ($port && $port != '80' && $port != '443') ? ':' . $port : '';
    return $protocol . '://' . $host . $port;
}
?>
