<?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);
    $appointmentId = $input['appointmentId'] ?? null;
    $teamsMessageId = $input['teamsMessageId'] ?? null;
    
    if (!$appointmentId) {
        throw new Exception('Appointment ID ist erforderlich');
    }
    
    // Mark Teams notification as sent for the latest sent offer
    $stmt = $conn->prepare("
        UPDATE offer_tracking 
        SET teams_notification_sent = TRUE, teams_message_id = ?
        WHERE appointment_id = ? 
        AND offer_type = 'sent' 
        AND teams_notification_sent = FALSE
        ORDER BY created_at DESC 
        LIMIT 1
    ");
    
    $stmt->execute([$teamsMessageId, $appointmentId]);
    $affectedRows = $stmt->rowCount();
    
    if ($affectedRows > 0) {
        echo json_encode([
            'success' => true,
            'message' => 'Teams-Status erfolgreich aktualisiert',
            'affected_rows' => $affectedRows
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'error' => 'Kein Angebot gefunden oder bereits als gesendet markiert'
        ]);
    }
    
} catch (Exception $e) {
    error_log("Error in mark_teams_notification_sent.php: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => 'Fehler beim Aktualisieren des Teams-Status: ' . $e->getMessage()
    ]);
}
?>
