<?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
    $appointmentId = $_GET['appointmentId'] ?? $_POST['appointmentId'] ?? null;
    
    if (!$appointmentId) {
        throw new Exception('Termin-ID ist erforderlich');
    }
    
    // Get SMTP data for the appointment's autohaus
    $stmt = $conn->prepare("
        SELECT 
            a.autohaus_id,
            au.email_smtp_host,
            au.email_smtp_port,
            au.email_smtp_username,
            au.email_smtp_password,
            au.email_smtp_encryption,
            au.email_from_name,
            au.name as autohaus_name
        FROM appointments a 
        LEFT JOIN autohaus au ON a.autohaus_id = au.id 
        WHERE a.id = ?
    ");
    
    $stmt->execute([$appointmentId]);
    $smtpData = $stmt->fetch();
    
    if (!$smtpData) {
        throw new Exception('Termin oder Autohaus nicht gefunden');
    }
    
    // Remove sensitive data from response
    unset($smtpData['email_smtp_password']);
    
    echo json_encode([
        'success' => true,
        'smtpData' => $smtpData
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
