<?php
/**
 * Detaillierte Test-E-Mail für Termin-Benachrichtigungen
 */

// 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']) {
    ob_clean();
    echo json_encode(['success' => false, 'error' => 'Nicht angemeldet']);
    exit;
}

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

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

try {
    $db = new Database();
    $conn = $db->getConnection();
    
    // Hole den ersten wartenden Termin mit allen Details
    $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) {
        ob_clean();
        echo json_encode(['success' => false, 'error' => 'Kein wartender Termin gefunden. Bitte erstellen Sie zuerst eine Terminanfrage.']);
        exit;
    }
    
    // Debug: Log Termin-Details
    error_log("=== TERMIN-E-MAIL DEBUG ===");
    error_log("Termin-ID: " . $appointment['id']);
    error_log("Kunde: " . $appointment['customer_name']);
    error_log("E-Mail: " . $appointment['email']);
    error_log("Event: " . $appointment['event_name']);
    error_log("Datum: " . $appointment['event_date']);
    error_log("Status: " . $appointment['status']);
    
    // Prüfe E-Mail-Benachrichtigungen-Einstellung
    $stmt = $conn->prepare("SELECT setting_value FROM settings WHERE setting_key = 'email_notifications_enabled'");
    $stmt->execute();
    $emailEnabled = $stmt->fetchColumn();
    error_log("E-Mail-Benachrichtigungen aktiviert: " . ($emailEnabled ? 'Ja' : 'Nein'));
    
    // Teste E-Mail-Benachrichtigung
    $emailNotifications = new EmailNotifications();
    
    // Debug: Teste verschiedene Aktionen
    $actions = ['approved', 'rejected', 'rescheduled'];
    $results = [];
    
    foreach ($actions as $action) {
        error_log("Teste Aktion: " . $action);
        $result = $emailNotifications->sendAppointmentNotification($appointment['id'], $action);
        $results[$action] = $result;
        error_log("Ergebnis für $action: " . json_encode($result));
    }
    
    // Alle Ausgaben vor JSON löschen
    ob_clean();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Detaillierte Tests abgeschlossen',
        'appointment' => [
            'id' => $appointment['id'],
            'customer_name' => $appointment['customer_name'],
            'email' => $appointment['email'],
            'event_name' => $appointment['event_name'],
            'status' => $appointment['status']
        ],
        'email_enabled' => $emailEnabled,
        'test_results' => $results,
        'debug_log' => 'Detaillierte Logs in PHP-Fehlerprotokoll und logs/appointment_email_debug.log'
    ]);
    
} catch (Exception $e) {
    // Alle Ausgaben vor JSON löschen
    ob_clean();
    
    error_log("TERMIN-E-MAIL FEHLER: " . $e->getMessage());
    
    echo json_encode([
        'success' => false, 
        'error' => 'Fehler: ' . $e->getMessage()
    ]);
}
?>
