<?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 appointment ID from request
    $input = json_decode(file_get_contents('php://input'), true);
    $appointmentId = $input['appointmentId'] ?? null;
    
    if (!$appointmentId) {
        throw new Exception('Appointment ID ist erforderlich');
    }
    
    // Get Teams message ID for this appointment
    $stmt = $conn->prepare("
        SELECT teams_message_id 
        FROM offer_tracking 
        WHERE appointment_id = ? 
        AND offer_type = 'sent' 
        AND teams_notification_sent = TRUE
        ORDER BY created_at DESC 
        LIMIT 1
    ");
    
    $stmt->execute([$appointmentId]);
    $offerData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$offerData || !$offerData['teams_message_id']) {
        echo json_encode([
            'success' => false,
            'error' => 'Keine Teams-Nachricht gefunden'
        ]);
        exit;
    }
    
    // Get autohaus Teams settings
    $stmt = $conn->prepare("
        SELECT 
            ah.teams_webhook_url,
            ah.teams_channel_name,
            ah.teams_notifications_enabled
        FROM appointments a
        JOIN autohaus ah ON a.autohaus_id = ah.id
        WHERE a.id = ?
    ");
    
    $stmt->execute([$appointmentId]);
    $autohausData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$autohausData || !$autohausData['teams_notifications_enabled']) {
        echo json_encode([
            'success' => false,
            'error' => 'Teams-Benachrichtigungen nicht aktiviert'
        ]);
        exit;
    }
    
    // Get Teams reactions using Microsoft Graph API
    $reactions = getTeamsReactions($autohausData['teams_webhook_url'], $offerData['teams_message_id']);
    
    echo json_encode([
        'success' => true,
        'reactions' => $reactions,
        'message_id' => $offerData['teams_message_id']
    ]);
    
} catch (Exception $e) {
    error_log("Error in get_teams_reactions.php: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => 'Fehler beim Abrufen der Teams-Reaktionen: ' . $e->getMessage()
    ]);
}

function getTeamsReactions($webhookUrl, $messageId) {
    // Note: Teams Webhooks don't directly support getting reactions
    // We'll implement a workaround using adaptive cards with action buttons
    // and track responses through our own system
    
    return [
        'tire_ordered' => false,
        'work_completed' => false,
        'customer_notified' => false,
        'last_updated' => date('Y-m-d H:i:s')
    ];
}
?>
