<?php
/**
 * Test-E-Mail mit echten Termindaten senden
 */

// Alle Ausgaben vor JSON unterdrücken
ob_start();

// PHP-Warnings und Errors unterdrücken
error_reporting(0);
ini_set('display_errors', 0);

header('Content-Type: application/json');
require_once '../config/database.php';
require_once '../api/email_notifications.php';

session_start();

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    echo json_encode(['success' => false, 'error' => 'Nicht angemeldet']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

if (!$input || $input['action'] !== 'test_real_email') {
    echo json_encode(['success' => false, 'error' => 'Ungültige Anfrage']);
    exit;
}

try {
    $db = new Database();
    $conn = $db->getConnection();
    
    // Hole den ersten wartenden Termin
    $stmt = $conn->prepare("
        SELECT a.*, e.name as event_name, e.event_date as event_date 
        FROM appointments a 
        LEFT JOIN events e ON a.event_id = e.id 
        WHERE a.status = 'pending' 
        ORDER BY a.created_at DESC 
        LIMIT 1
    ");
    $stmt->execute();
    $appointment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$appointment) {
        echo json_encode(['success' => false, 'error' => 'Kein wartender Termin gefunden. Bitte erstellen Sie zuerst eine Terminanfrage.']);
        exit;
    }
    
    // Teste E-Mail-Benachrichtigung
    $emailNotifications = new EmailNotifications();
    $result = $emailNotifications->sendAppointmentNotification($appointment['id'], 'approved');
    
    // Alle Ausgaben vor JSON löschen
    ob_clean();
    
    if ($result['success']) {
        echo json_encode([
            'success' => true, 
            'message' => 'Test-E-Mail erfolgreich gesendet an ' . $appointment['email'],
            'appointment_id' => $appointment['id'],
            'customer_email' => $appointment['email']
        ]);
    } else {
        echo json_encode([
            'success' => false, 
            'error' => $result['error'],
            'appointment_id' => $appointment['id'],
            'customer_email' => $appointment['email']
        ]);
    }
    
} catch (Exception $e) {
    // Alle Ausgaben vor JSON löschen
    ob_clean();
    
    echo json_encode([
        'success' => false, 
        'error' => 'Fehler: ' . $e->getMessage()
    ]);
}
?>
