<?php 
// --- SETTINGS BRIDGE ---
$settings_file = 'theme_settings.json';
// Load saved settings or use defaults if file is missing
$config = file_exists($settings_file) ? json_decode(file_get_contents($settings_file), true) : ['blur' => 12, 'hue' => 120];

// --- DYNAMIC PREVIEW OVERRIDE ---
$dynamic_hue = $_GET['hue'] ?? $config['hue'];
$dynamic_blur = $_GET['blur'] ?? $config['blur'];

// --- DYNAMIC LOCATION & CURRENCY DETECTION ---
function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR'];
    return $_SERVER['REMOTE_ADDR'];
}
$user_ip = getUserIP();
$ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $user_ip));

$currencySymbol = ($ipdat && isset($ipdat->geoplugin_currencySymbol)) ? $ipdat->geoplugin_currencySymbol : '$';
$countryName = ($ipdat && isset($ipdat->geoplugin_countryName)) ? $ipdat->geoplugin_countryName : 'Global';
$countryCode = ($ipdat && isset($ipdat->geoplugin_countryCode)) ? strtolower($ipdat->geoplugin_countryCode) : 'global';

// --- DYNAMIC LANGUAGE INITIALIZATION ---
$langFile = __DIR__ . "/lang/{$countryCode}.php";
if (!file_exists($langFile)) { $langFile = __DIR__ . "/lang/en.php"; }
if (file_exists($langFile)) { include($langFile); } else { $lang = []; }
function __l($key) { global $lang; return $lang[$key] ?? $key; }

// --- MAINTENANCE MODE START ---
$db = new PDO('sqlite:app_feed.db');
$stmt = $db->query("SELECT setting_value FROM app_feed_settings WHERE setting_key='system_status'");
$maintenance_status = $stmt->fetchColumn();

if ($maintenance_status === 'Maintenance') {
    die('
    <!DOCTYPE html>
    <html lang="en">
    <head><title>System Maintenance</title></head>
    <body style="background:#0f1624; color:#fff; display:flex; justify-content:center; align-items:center; height:100vh; font-family:sans-serif;">
        <div style="text-align:center;">
            <h1>System Maintenance</h1>
            <p>We are currently upgrading our systems. Please check back shortly.</p>
        </div>
    </body>
    </html>
    ');
}
// --- MAINTENANCE MODE END ---

// DYNAMIC BACKGROUND SETUP
$currentSettings = $db->query("SELECT setting_key, setting_value FROM app_feed_settings")->fetchAll(PDO::FETCH_KEY_PAIR);
$userCountry = ($countryCode === 'global') ? 'ng' : $countryCode; 
session_start();

// Fetch localized Brand Name
$localized_brand_name = $currentSettings['brand_name_' . $userCountry] ?? "ApexGlobe";

$pageType = (isset($_SESSION['phone'])) ? 'dash' : 'index';
$bgImage = $currentSettings['bg_' . $pageType . '_' . $userCountry] ?? 'https://smilitary.xyz/assets/bg/' . $pageType . '_' . $userCountry . '.png';
$bgColor = $currentSettings['bg_color_' . $userCountry] ?? '#0f1624';

// AI MANAGER LOGIC
function getAiManagerResponse($status) {
    $responses = [
        'Pending' => "Hello! I'm your Portfolio Manager. I'm currently verifying your documents. Please sit tight—I'll have you active shortly.",
        'Active' => "Welcome back! I've been monitoring your growth. Today is a great day to increase your savings stake to hit that next tier.",
        'Suspended' => "I have some difficult news. Your account has been suspended due to a compliance flag. Please contact our support team immediately to resolve this.",
        'Default' => "Hello. I am here to guide your financial journey. How can I assist you today?"
    ];
    return $responses[$status] ?? $responses['Default'];
}

// Handle Logout
if(isset($_GET['logout'])) { 
    session_destroy(); 
    header("Location: index.php"); 
    exit; 
}

// FIX: Handle Reset Link - Force immediate clear and redirect
if(isset($_GET['reset'])) {
    if (file_exists($settings_file)) unlink($settings_file);
    unset($_SESSION['show_login']);
    header("Location: index.php?r=" . time()); 
    exit;
}

// DATABASE CONNECTION
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->exec("CREATE TABLE IF NOT EXISTS comments (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, comment TEXT, tier TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)");
try { $db->exec("ALTER TABLE user_registrations ADD COLUMN phone TEXT"); } catch (Exception $e) {}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_comment']) && isset($_SESSION['user_id'])) {
    $stmt = $db->prepare("SELECT name, tier FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $stmt = $db->prepare("INSERT INTO comments (username, comment, tier) VALUES (?, ?, ?)");
    $stmt->execute([$user_data['name'], $_POST['new_comment'], $user_data['tier']]);
    exit;
}

if (isset($_GET['view']) && $_GET['view'] === 'login') {
    $_SESSION['show_login'] = true;
}

// --- CORRECTED REGISTRATION BLOCK ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['phone']) && !isset($_POST['new_comment'])) {
    $phone = $_POST['phone'];
    
    // Check if user already exists
    $stmt_find = $db->prepare("SELECT id FROM users WHERE phone = ? LIMIT 1");
    $stmt_find->execute([$phone]);
    $existing_user = $stmt_find->fetch(PDO::FETCH_ASSOC);

    if ($existing_user) {
        // User exists, log them in
        $_SESSION['user_id'] = $existing_user['id'];
    } else {
        // User does not exist, check for required registration fields
        if (isset($_POST['email']) && isset($_POST['username'])) {
            $email = $_POST['email'];
            $username = $_POST['username'];
            
            // Register them in the tracking table
            $stmt = $db->prepare("INSERT INTO user_registrations (phone, email, username, status) VALUES (:phone, :email, :username, 'Pending')");
            $stmt->execute([':phone' => $phone, ':email' => $email, ':username' => $username]);
            
            // Create their main account
            $new_user_id = 'user_' . bin2hex(random_bytes(32));
            $stmt_user = $db->prepare("INSERT INTO users (id, name, phone, balance, tier) VALUES (?, ?, ?, ?, ?)");
            $stmt_user->execute([$new_user_id, $username, $phone, 0.00, 'Bronze Tier']);
            
            $_SESSION['user_id'] = $new_user_id;
        }
    }
    
    $_SESSION['phone'] = $phone;
    unset($_SESSION['show_login']);
    
    header("Location: index.php");
    exit;
}

$is_approved = false;
$error_message = ""; 
$current_user_status = 'Pending';
if (isset($_SESSION['phone'])) {
    if ($_SESSION['phone'] === 'test') {
        $is_approved = true;
        $current_user_status = 'Active';
    } else {
        $stmt = $db->prepare("SELECT status FROM user_registrations WHERE phone = :phone ORDER BY rowid DESC LIMIT 1");
        $stmt->execute([':phone' => $_SESSION['phone']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user && $user['status'] === 'Active') {
            $is_approved = true;
            $current_user_status = 'Active';
        } elseif ($user && $user['status'] === 'Suspended') {
            $error_message = "Your account has been suspended.";
            $current_user_status = 'Suspended';
        } elseif (!$user) {
            $error_message = "Number not registered.";
        } else {
            $error_message = "Account status is: " . $user['status'];
            $current_user_status = $user['status'];
        }
    }
}
$ai_message = getAiManagerResponse($current_user_status);
?>

<!DOCTYPE html>
<html lang="en" class="has-gamified-tiers">
<head>
<meta charset="UTF-8">
<style>
    :root {
        /* Theme Implementation - Loaded from JSON */
        --blur: <?php echo $dynamic_blur; ?>px;
        --hue: <?php echo $dynamic_hue; ?>;
        --bg-image: url('<?php echo $bgImage; ?>?v=<?php echo time(); ?>');
    }
    body {
        background-image: var(--bg-image) !important;
        background-size: cover !important;
        background-position: center !important;
        background-repeat: no-repeat !important;
        background-attachment: fixed !important;
        min-height: 100vh;
        margin: 0;
        /* Theme Filter using the dynamic Hue */
        filter: hue-rotate(calc(var(--hue) * 1deg));
    }
    /* Centered Plastic/Frosted Branding Style */
    .brand-container {
        display: flex;
        justify-content: center;
        margin-bottom: 15px;
    }
    .brand-display {
        display: inline-block;
        background: rgba(255, 255, 255, 0.08);
        backdrop-filter: blur(var(--blur));
        border: 1px solid rgba(255, 255, 255, 0.15);
        padding: 6px 16px;
        border-radius: 50px;
        font-size: 0.85rem;
        font-weight: 600;
        color: #e2e8f0;
        letter-spacing: 1px;
        text-transform: uppercase;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2);
    }
</style>
</head>
<body>

<div class="ai-manager-bubble">
    <div class="manager-avatar">🤖</div>
    <div class="manager-text">
        <strong>Your Manager:</strong>
        <p id="managerDisplay"><?php echo $ai_message; ?></p>
    </div>
</div>

<div class="container">
    <?php 
    if (!isset($_SESSION['phone'])): 
        if (isset($_SESSION['show_login'])): ?>
            <div class="brand-container">
                <div class="brand-display">
                    <?php echo htmlspecialchars($localized_brand_name); ?>
                </div>
            </div>
            <h2><?php echo __l('login_title'); ?></h2>
            <?php if (!$is_approved && !empty($error_message)): ?>
                <div class="error-notification" style="color: #ff4d4d; margin-bottom: 15px; font-weight: bold; font-size: 14px; text-align: center;">
                    <?php echo $error_message; ?>
                </div>
            <?php endif; ?>
            <form method="POST">
                <div class="form-group">
                    <label><?php echo __l('phone_label'); ?></label>
                    <input type="text" name="phone" placeholder="+123..." required>
                </div>
                <button type="submit"><?php echo __l('login_btn'); ?></button>
                <p style="text-align:center; margin-top:20px;"><a href="index.php?reset=1" style="color:#9ca3af; text-decoration:none; font-size:12px;">Back to Registration</a></p>
            </form>
        <?php else: ?>
            <div class="brand-container">
                <div class="brand-display">
                    <?php echo htmlspecialchars($localized_brand_name); ?>
                </div>
            </div>
            <h2><?php echo __l('reg_title'); ?></h2>
            <form method="POST">
                <div class="form-group">
                    <label>Username</label>
                    <input type="text" name="username" placeholder="Choose a display name" required>
                </div>
                <div class="form-group">
                    <label><?php echo __l('phone_label'); ?></label>
                    <input type="text" name="phone" placeholder="+44..." required>
                </div>
                <div class="form-group">
                    <label>Enter Email Address</label>
                    <input type="email" name="email" placeholder="name@example.com" required>
                </div>
                <div style="margin: 20px 0; font-size: 13px; color: #9ca3af; text-align: center;">
                    <input type="checkbox" id="terms" name="terms" required>
                    <label for="terms"> I agree to the <a href="terms.php" target="_blank" style="color: #10b981; text-decoration: underline;">Terms and Conditions</a></label>
                </div>
                <button type="submit"><?php echo __l('reg_btn'); ?></button>
                <p style="text-align:center; margin-top:20px; font-size:13px; color:#9ca3af;">
                    Already registered? <a href="?view=login" style="color:#10b981; text-decoration:none;">Click here to Login</a>
                </p>
            </form>
        <?php endif; 
    elseif (!$is_approved): ?>
        <h2><?php echo __l('wait_approval'); ?></h2>
        <p style="text-align: center; color: #9ca3af;">
            <?php echo !empty($error_message) ? $error_message : "Your registration is currently being reviewed by an administrator."; ?>
        </p>
        <div style="margin-top: 20px;">
            <a href="?logout=1" style="color: #10b981; text-decoration: none; font-weight: bold; display: block; text-align: center;"><?php echo __l('logout'); ?></a>
        </div>
    <?php else: ?>
        <button class="burger-menu" id="burgerToggle" aria-label="Toggle Navigation">
            <span></span>
            <span></span>
            <span></span>
        </button>

        <div class="mobile-nav-panel" id="navPanel">
            <a href="cdashboard.php">Dashboard</a>
            <a href="#" class="nav-item" data-target="perks">Tier Perks</a>
            <a href="transaction_history.php">Transaction History</a>
            <a href="terms.php" class="nav-item">Terms of Service</a>
            <a href="?logout=1" class="nav-item"><?php echo __l('logout'); ?></a>
        </div>

<div class="monitor-card">
    <div style="color: #10b981; font-weight: bold; margin-bottom: 15px;">SYSTEM MONITOR</div>
    
    <div class="sync-circle">
        <div class="percentage-text" id="live-percent">0%</div>
    </div>
    
    <div class="tier-label" id="tier-status">INITIALIZING...</div>
</div>

<script>
    (function() {
        let count = 0;
        const displayValue = document.getElementById('live-value'); 
        const tLabel = document.getElementById('tier-status');

        setInterval(() => {
            count = (count + 25) % 2501; 
            if(displayValue) displayValue.innerText = count.toLocaleString();
            
            if (count <= 50) {
                tLabel.innerText = "BRONZE TIER";
            } else if (count <= 500) {
                tLabel.innerText = "SILVER TIER";
            } else if (count <= 2500) {
                tLabel.innerText = "GOLD TIER";
            } else {
                tLabel.innerText = "PLATINUM TIER (UNLIMITED)";
                tLabel.className = "tier-label color-platinum";
            }
        }, 100);

        let percent = 0;
        const pText = document.getElementById('live-percent');

        setInterval(() => {
            percent = (percent + 1) % 101;
            pText.innerText = percent + "%";
            
            if (percent < 33) {
                tLabel.innerText = "BRONZE TIER";
                tLabel.className = "tier-label color-bronze";
            } else if (percent < 66) {
                tLabel.innerText = "SILVER TIER";
                tLabel.className = "tier-label color-silver";
            } else if (percent < 90) {
                tLabel.innerText = "GOLD TIER";
                tLabel.className = "tier-label color-gold";
            } else {
                tLabel.innerText = "PLATINUM TIER";
                tLabel.className = "tier-label color-platinum";
            }
        }, 100);
    })();
</script>
        
        <div id="dashboard" class="page-content active">
            <h2>Level Up Your Savings</h2>
            <div class="tier-dashboard">
                <div class="tier-status">
                    <span class="current-badge" id="tierBadge">Bronze Tier</span>
                    <span class="next-tier-hint" id="tierHint">Deposit to earn Level Up</span>
                </div>
                <div class="progress-track">
                    <div class="progress-bar-fill" id="progressBar"></div>
                </div>
                <div class="perks-preview">
                    <span class="perk-chip active" id="perk1">2% APY Base</span>
                    <span class="perk-chip" id="perk2">⚡ 4% APY</span>
                    <span class="perk-chip" id="perk3">💎 6.5% APY</span>
                    <span class="perk-chip" id="perk4">👑 9% VIP APY</span>
                </div>

                <div class="withdrawal-limits-grid">
                    <div class="withdrawal-row" id="withdrawalRow">
                        <span class="withdrawal-label">Withdrawal Allowance:</span>
                        <span class="withdrawal-value" id="withdrawalValue"><?php echo $currencySymbol; ?>50.00 Max</span>
                    </div>
                    <div class="withdrawal-row" id="statusBenefitRow">
                        <span class="withdrawal-label">Profile Security Rank:</span>
                        <span class="withdrawal-value" id="statusBenefitValue">Standard Tier Access</span>
                    </div>
                </div>
            </div>

            <div class="ai-chat-section">
                <span class="ai-chat-header">Manager AI Chat</span>
                <div class="command-bar">
                    <button class="cmd-btn" onclick="document.getElementById('aiChatInput').value='status'; document.getElementById('sendAiBtn').click();">Status</button>
                    <button class="cmd-btn" onclick="document.getElementById('aiChatInput').value='summary'; document.getElementById('sendAiBtn').click();">Summary</button>
                    <button class="cmd-btn" onclick="document.getElementById('aiChatInput').value='help'; document.getElementById('sendAiBtn').click();">Help</button>
                </div>
                <div class="comment-input-row">
                    <input type="text" id="aiChatInput" placeholder="Ask manager about status...">
                    <button type="button" class="btn-send-comment" id="sendAiBtn">Ask</button>
                </div>
            </div>

            <div class="comments-section-container">
                <div class="comments-list-box" id="commentsBox">
                    <?php
                    $comments = $db->query("SELECT * FROM comments ORDER BY id DESC LIMIT 5");
                    foreach ($comments as $row) {
                        $initials = strtoupper(substr($row['username'], 0, 2));
                        echo "<div class='comment-card'>
                                          <div class='avatar-circle'>$initials</div>
                                          <div class='comment-content'>
                                              <div class='comment-header'>
                                                  {$row['username']}
                                                  <span class='tier-tag'>" . strtoupper(str_replace(' ', '_', $row['tier'])) . " UNLOCKED</span>
                                              </div>
                                              <div style='font-style:italic;'>\"{$row['comment']}\"</div>
                                          </div>
                                      </div>";
                    }
                    ?>
                </div>
                <div class="comment-input-row">
                    <input type="text" id="newCommentTxt" placeholder="Write a public application comment...">
                    <button type="button" class="btn-send-comment" id="submitCommentBtn">Send</button>
                </div>
                <script>
                document.getElementById('submitCommentBtn').onclick = function() {
                    let comment = document.getElementById('newCommentTxt').value;
                    if(comment) {
                        fetch('', { method: 'POST', body: 'new_comment=' + encodeURIComponent(comment), headers: {'Content-Type': 'application/x-www-form-urlencoded'} })
                        .then(() => location.reload());
                    }
                };
                </script>
            </div>

            <form action="process_payment.php" method="POST">
                <div class="form-group">
                    <label>Amount to Deposit (<?php echo $currencySymbol; ?>)</label>
                    <input type="number" id="amountInput" name="amount" min="1" placeholder="Enter amount" required>
                </div>
                <div class="form-group">
                    <label>Payment Method</label>
                    <select name="method">
                        <option value="momo">Mobile Money</option>
                        <option value="card">Credit / Debit Card</option>
                        <option value="crypto">Bitcoin / USDT</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Payment Schedule</label>
                    <select name="frequency">
                        <option value="daily">Daily Track</option>
                        <option value="weekly">Weekly Track</option>
                        <option value="monthly">Monthly Track</option>
                    </select>
                </div>
                <button type="submit">Pay via Global Mobile Gateway</button>
            </form>
        </div>

        <div id="perks" class="page-content">
            <h2>Tier Perks</h2>
            <div style="background: rgba(10, 15, 26, 0.6); padding: 20px; border-radius: 16px; border: 1px solid rgba(255,255,255,0.05);">
                <p><strong>Bronze:</strong> 2% APY, <?php echo $currencySymbol; ?>50 Limit</p>
                <p><strong>Silver:</strong> 4% APY, <?php echo $currencySymbol; ?>500 Limit</p>
                <p><strong>Gold:</strong> 6.5% APY, <?php echo $currencySymbol; ?>2,500 Limit</p>
                <p><strong>Platinum:</strong> 9% APY, Unlimited Access</p>
            </div>
        </div>

        <div id="history" class="page-content">
            <h2>Transaction History</h2>
            <div style="background: rgba(10, 15, 26, 0.6); padding: 20px; border-radius: 16px; text-align: center; color: #9ca3af;">
                <p>No transactions found.</p>
            </div>
        </div>
    <?php endif; ?>
</div>
</body>
</html>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const commentsBox = document.getElementById('commentsBox');
        const newCommentTxt = document.getElementById('newCommentTxt');
        const submitCommentBtn = document.getElementById('submitCommentBtn');

        function appendCommentElement(name, flag, tier, text) {
            if(!commentsBox) return;
            const wrapper = document.createElement('div');
            wrapper.className = 'testimonial-ticker';
            wrapper.style.marginBottom = '8px';
            wrapper.style.opacity = '0';
            wrapper.style.transition = 'opacity 0.4s ease';
            wrapper.innerHTML = `
                <div class="testimonial-avatar">${flag}</div>
                <div class="testimonial-content">
                    <p class="testimonial-user"><span>${name}</span> <span class="testimonial-badge">${tier}</span></p>
                    <p class="testimonial-text">"${text}"</p>
                </div>
            `;
            commentsBox.appendChild(wrapper);
            commentsBox.scrollTop = commentsBox.scrollHeight;
            setTimeout(() => wrapper.style.opacity = '1', 50);
        }

        function loadLiveCommentsFeed() {
            if(!commentsBox) return;
            fetch('get_comments.php')
                .then(response => response.json())
                .then(data => {
                    commentsBox.innerHTML = '';
                    if(data && data.length > 0) {
                        data.forEach(r => appendCommentElement(r.name, r.flag, r.tier, r.txt));
                    } else {
                        appendCommentElement("System Info", "📢", "Live Feed", "No live user statements published yet. Be the first!");
                    }
                })
                .catch(err => {
                    commentsBox.innerHTML = '';
                    appendCommentElement("Kwame O.", "🇰🇪", "Silver Unlocked", "Just loaded via MoMo SIM. Fast setup and my interest tier jumped immediately!");
                });
        }

        if(commentsBox) {
            loadLiveCommentsFeed();
            submitCommentBtn.addEventListener('click', function() {
                const commentVal = newCommentTxt.value.trim();
                if(commentVal !== "") {
                    const currentTier = document.getElementById('tierBadge').innerText;
                    const payload = { name: "Anonymous User", flag: "📱", tier: currentTier + " Active", txt: commentVal };
                    appendCommentElement(payload.name, payload.flag, payload.tier, payload.txt);
                    newCommentTxt.value = "";
                    fetch('save_comment.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) })
                    .then(res => res.json())
                    .then(status => loadLiveCommentsFeed())
                    .catch(err => console.error("Data submission endpoint unavailable:", err));
                }
            });
            newCommentTxt.addEventListener('keydown', function(e) { if (e.key === 'Enter') { e.preventDefault(); submitCommentBtn.click(); } });
        }
    });
</script>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // --- Initialization & State ---
        let globalAiUserName = localStorage.getItem('userNickname') || "friend";
        const burgerToggle = document.getElementById('burgerToggle');
        const navPanel = document.getElementById('navPanel');
        const navItems = document.querySelectorAll('.nav-item');
        const pageContents = document.querySelectorAll('.page-content');
        const amountInput = document.querySelector('input[name="amount"]') || document.getElementById('amountInput');
        const aiChatInput = document.getElementById('aiChatInput');
        const sendAiBtn = document.getElementById('sendAiBtn');
        const managerDisplay = document.getElementById('managerDisplay');

        // AI Welcome Message
        setTimeout(() => {
            if (managerDisplay) managerDisplay.innerText = `Hello ${globalAiUserName}! I am your Financial Concierge. You can ask me for your 'Status', 'Summary', or even just say 'Hi' to get started.`;
        }, 1500);

        // --- Shared Command Processor (AI) ---
        function getAiResponse(input) {
            const lower = input.toLowerCase();
            const val = parseFloat(amountInput?.value) || 0;
            const currentTier = document.getElementById('tierBadge')?.innerText || "Bronze";
            const tierEmoji = (currentTier.includes("Platinum")) ? "👑" : (currentTier.includes("Gold")) ? "⭐" : (currentTier.includes("Silver")) ? "✨" : "🥉";

            if (lower.includes("my name is")) {
                const parts = lower.split("my name is");
                if (parts.length > 1) {
                    const name = parts.trim();
                    globalAiUserName = name.charAt(0).toUpperCase() + name.slice(1);
                    localStorage.setItem('userNickname', globalAiUserName);
                    return `Nice to meet you, ${globalAiUserName}! I've updated your profile. How can I help you today?`;
                }
            } else if (lower.includes("name") || lower.includes("who are you")) {
                return `I am your AI Banking Assistant, ${globalAiUserName}. I'm here to ensure you reach your financial goals!`;
            } else if (lower.includes("hi") || lower.includes("hello")) {
                return `Hi ${globalAiUserName}! How can I help with your account today? ${tierEmoji}`;
            } else if (lower.includes("status")) {
                return `Your account status is currently active. You're currently at the ${currentTier} level, ${globalAiUserName}! ${tierEmoji} Keep pushing forward!`;
            } else if (lower.includes("summary") || lower.includes("overview")) {
                const nextStep = val < 5000 ? `You are $${(5000 - val).toFixed(2)} away from Platinum.` : "You have reached the maximum tier!";
                return `Summary for ${globalAiUserName}: Status: ${currentTier} ${tierEmoji}. Balance: $${val.toFixed(2)}. Goal: ${nextStep}`;
            }
            return `I'm listening, ${globalAiUserName}. How can I assist you with your finances today?`;
        }

        // --- Navigation Logic ---
        if (burgerToggle) {
            burgerToggle.addEventListener('click', () => {
                burgerToggle.classList.toggle('open');
                navPanel.classList.toggle('active');
            });
        }

        document.querySelectorAll('.nav-item').forEach(link => {
            link.addEventListener('click', (e) => {
                let targetId = link.getAttribute('data-target');
                if (targetId) {
                    e.preventDefault();
                    burgerToggle?.classList.remove('open');
                    navPanel?.classList.remove('active');
                    
                    document.querySelectorAll('.page-content').forEach(p => p.classList.remove('active'));
                    
                    // Force find the target
                    let targetPage = document.getElementById(targetId) || document.getElementById('Dashboard') || document.getElementById('dashboard');
                    if (targetPage) {
                        targetPage.classList.add('active');
                    }
                }
            });
        });

        // --- Dashboard Update Logic ---
        function updateDashboard() {
            if (!amountInput) return;
            const val = parseFloat(amountInput.value) || 0;
            const badge = document.getElementById('tierBadge');
            const hint = document.getElementById('tierHint');
            const bar = document.getElementById('progressBar');
            const withdrawalValue = document.getElementById('withdrawalValue');

            if (!badge) return;

            if (val < 500) {
                badge.innerText = "Bronze Tier";
                hint.innerText = `$${500 - val} to reach Silver`;
                bar.style.width = (val / 500 * 25) + "%";
                withdrawalValue.innerText = "5% Annual Yield";
            } else if (val >= 500 && val < 2000) {
                badge.innerText = "Silver Tier";
                hint.innerText = `$${2000 - val} to reach Gold`;
                bar.style.width = "50%";
                withdrawalValue.innerText = "8% Annual Yield";
            } else if (val >= 2000 && val < 5000) {
                badge.innerText = "Gold Tier";
                hint.innerText = `$${5000 - val} to reach Platinum`;
                bar.style.width = "75%";
                withdrawalValue.innerText = "12% Annual Yield";
            } else {
                badge.innerText = "Platinum VIP";
                hint.innerText = "Max Level Achieved! 👑";
                bar.style.width = "100%";
                withdrawalValue.innerText = "18% Annual Yield";
            }
        }

        // --- Event Listeners ---
        sendAiBtn?.addEventListener('click', () => {
            if (aiChatInput.value.trim()) {
                managerDisplay.innerText = getAiResponse(aiChatInput.value);
                aiChatInput.value = '';
            }
        });

        amountInput?.addEventListener('input', updateDashboard);
        updateDashboard();
    });
</script>


<style>
    /* --- CUSTOM TRANSLATOR STYLES --- */
    #google_translate_element { margin: 15px auto; text-align: center; }
    .goog-te-gadget-simple { background-color: #0f1624 !important; border: 1px solid #10b981 !important; border-radius: 8px !important; padding: 5px !important; }
    .goog-te-gadget-simple .goog-te-menu-value { color: #fff !important; }
    .goog-te-menu-value span { color: #fff !important; }

    /* --- COMMENTS UI IMPLEMENTATION --- */
    .comments-section-container { margin-bottom: 24px; }
    .comments-list-box { max-height: 140px; overflow-y: auto; margin-bottom: 12px; padding-right: 4px; }
    .comments-list-box::-webkit-scrollbar { width: 4px; }
    .comments-list-box::-webkit-scrollbar-track { background: rgba(255,255,255,0.02); }
    .comments-list-box::-webkit-scrollbar-thumb { background: rgba(16, 185, 129, 0.3); border-radius: 4px; }
    .comment-input-row { display: flex; gap: 8px; }
    .comment-input-row input { padding: 10px 14px; font-size: 13px; border-radius: 10px; }
    .btn-send-comment { width: auto; margin-top: 0; padding: 0 16px; border-radius: 10px; font-size: 14px; display: flex; align-items: center; justify-content: center; }
    .testimonial-ticker { background: linear-gradient(135deg, rgba(16, 185, 129, 0.06) 0%, rgba(5, 150, 105, 0.01) 100%); border: 1px dashed rgba(16, 185, 129, 0.25); border-radius: 16px; padding: 14px 16px; margin-bottom: 24px; display: flex; align-items: center; gap: 12px; transition: all 0.4s ease; }
    .testimonial-avatar { width: 36px; height: 36px; border-radius: 50%; background: #1e293b; border: 2px solid #10b981; display: flex; align-items: center; justify-content: center; font-size: 16px; flex-shrink: 0; box-shadow: 0 0 10px rgba(16, 185, 129, 0.2); }
    .testimonial-content { flex-grow: 1; }
    .testimonial-user { font-size: 12px; font-weight: 700; color: #ffffff; margin: 0 0 2px 0; display: flex; justify-content: space-between; }
    .testimonial-badge { color: #34d399; font-size: 10px; font-weight: 800; text-transform: uppercase; }
    .testimonial-text { font-size: 12px; color: #9ca3af; margin: 0; line-height: 1.4; font-style: italic; }

    /* --- PHP WARNING ISOLATION INTERCEPTOR --- */
    font[size="1"], font[color="#ff0000"], pre, xmp, .php-error, br[clear="all"] {
        display: none !important; opacity: 0 !important; visibility: hidden !important; height: 0 !important; margin: 0 !important; padding: 0 !important;
    }

    /* --- PREMIUM GAMIFIED FINTECH UI IMPLEMENTATION --- */
    @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap');
    :root {
        --bg-image: url('<?php echo $bgImage; ?>');
    }
    body { 
        font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif; 
        background-image: var(--bg-image) !important; 
        background-size: cover; 
        background-position: center; 
        background-repeat: no-repeat; 
        background-attachment: fixed; 
        padding: 40px 20px; 
        margin: 0; 
        min-height: 100vh; 
        display: flex; 
        justify-content: center; 
        align-items: center; 
        color: #f3f4f6; 
        box-sizing: border-box; 
        transition: background 0.8s ease; 
    }
    .container { width: 100%; max-width: 440px; background: linear-gradient(145deg, rgba(26, 34, 50, 0.7) 0%, rgba(15, 22, 36, 0.9) 100%); padding: 32px; border-radius: 24px; box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.1); backdrop-filter: blur(12px); border: 1px solid rgba(255, 255, 255, 0.05); box-sizing: border-box; position: relative; overflow: hidden; }
    .container::before { content: ''; position: absolute; top: -50px; right: -50px; width: 150px; height: 150px; background: radial-gradient(circle, rgba(16, 185, 129, 0.25) 0%, rgba(16, 185, 129, 0) 70%); border-radius: 50%; pointer-events: none; }
    h2 { font-size: 26px; font-weight: 800; margin-top: 0; margin-bottom: 24px; background: linear-gradient(135deg, #ffffff 30%, #a7f3d0 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; letter-spacing: -0.5px; display: flex; align-items: center; gap: 10px; padding-right: 40px; }
    h2::before { content: '⚡'; -webkit-text-fill-color: initial; font-size: 24px; }
    .tier-dashboard { background: rgba(10, 15, 26, 0.6); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 16px; padding: 18px; margin-bottom: 24px; }
    .tier-status { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
    .current-badge { font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 1px; padding: 5px 12px; border-radius: 20px; background: linear-gradient(135deg, #cd7f32 0%, #a0522d 100%); color: #fff; box-shadow: 0 2px 8px rgba(205, 127, 50, 0.3); transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); }
    .next-tier-hint { font-size: 12px; color: #9ca3af; font-weight: 500; transition: all 0.3s ease; }
    .progress-track { height: 8px; background: rgba(255, 255, 255, 0.08); border-radius: 4px; overflow: hidden; margin-bottom: 16px; }
    .progress-bar-fill { width: 0%; height: 100%; background: linear-gradient(90deg, #10b981, #34d399); border-radius: 4px; transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: 0 0 8px rgba(16, 185, 129, 0.6); }
    .perks-preview { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; }
    .perks-preview span, .perk-chip { font-size: 11px; font-weight: 600; background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.06); padding: 8px; border-radius: 8px; color: #6b7280; text-align: center; transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); }
    .perks-preview span.active, .perk-chip.active { background: rgba(16, 185, 129, 0.12); border-color: rgba(16, 185, 129, 0.3); color: #a7f3d0; box-shadow: 0 2px 8px rgba(16, 185, 129, 0.05); }
    .withdrawal-limits-grid { margin-top: 14px; padding-top: 14px; border-top: 1px dashed rgba(255, 255, 255, 0.08); display: flex; flex-direction: column; gap: 8px; }
    .withdrawal-row { display: flex; justify-content: space-between; align-items: center; font-size: 12px; background: rgba(0, 0, 0, 0.15); padding: 8px 12px; border-radius: 10px; border: 1px solid rgba(255, 255, 255, 0.02); transition: all 0.3s ease; }
    .withdrawal-row.highlighted-benefit { border-color: rgba(56, 189, 248, 0.3); background: rgba(56, 189, 248, 0.06); }
    .withdrawal-label { color: #8a94a6; font-weight: 500; }
    .withdrawal-value { font-weight: 700; color: #e5e7eb; }
    .withdrawal-row.highlighted-benefit .withdrawal-label { color: #38bdf8; }
    .withdrawal-row.highlighted-benefit .withdrawal-value { color: #ffffff; text-shadow: 0 0 8px rgba(56, 189, 248, 0.4); }
    .command-bar { display: flex; gap: 8px; margin-bottom: 8px; flex-wrap: wrap; }
    .cmd-btn { background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: #10b981; padding: 4px 10px; border-radius: 6px; font-size: 11px; cursor: pointer; transition: 0.2s; }
    .cmd-btn:hover { background: rgba(16, 185, 129, 0.2); }
    .ai-chat-section { background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 16px; padding: 14px; margin-bottom: 24px; }
    .ai-chat-header { font-size: 12px; color: #10b981; font-weight: 700; margin-bottom: 8px; display: block; }
    .form-group { margin-bottom: 22px; position: relative; }
    label { display: block; margin-bottom: 8px; font-weight: 600; font-size: 13px; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.75px; }
    input, select { width: 100%; padding: 14px 16px; background: rgba(10, 15, 26, 0.75); border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 12px; box-sizing: border-box; color: #ffffff; font-size: 15px; font-family: inherit; font-weight: 500; transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: inset 0 2px 4px rgba(0,0,0,0.2); }
    input::placeholder { color: #4b5563; }
    input:focus, select:focus { outline: none; border-color: #10b981; background: rgba(10, 15, 26, 0.95); box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.15), inset 0 2px 4px rgba(0,0,0,0.2); }
    button { width: 100%; padding: 16px; background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: #ffffff; border: none; border-radius: 14px; font-size: 16px; font-weight: 700; cursor: pointer; transition: all 0.2s ease; box-shadow: 0 4px 14px rgba(16, 185, 129, 0.4), inset 0 1px 0 rgba(255,255,255,0.2); margin-top: 8px; text-shadow: 0 1px 2px rgba(0,0,0,0.15); }
    button:hover { background: linear-gradient(135deg, #059669 0%, #047857 100%); transform: translateY(-1px); box-shadow: 0 6px 20px rgba(16, 185, 129, 0.5); }
    .burger-menu { position: absolute; top: 32px; right: 32px; display: flex; flex-direction: column; justify-content: space-between; width: 24px; height: 18px; background: transparent; border: none; cursor: pointer; padding: 0; z-index: 10; }
    .burger-menu span { width: 24px; height: 2px; background-color: #ffffff; border-radius: 2px; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); transform-origin: left center; }
    .burger-menu.open span:nth-child(1) { transform: rotate(45deg); position: relative; top: -1px; }
    .burger-menu.open span:nth-child(2) { width: 0%; opacity: 0; }
    .burger-menu.open span:nth-child(3) { transform: rotate(-45deg); position: relative; top: 1px; }
    .mobile-nav-panel { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(145deg, #0f1624 0%, #080b11 100%); z-index: 5; display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 24px; transform: translateY(-100%); transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1); border-radius: 24px; }
    .mobile-nav-panel.active { transform: translateY(0); }
    .page-content { display: none; }
    .page-content.active { display: block; }
    @keyframes pulseGlow { 0% { box-shadow: 0 0 0 0 rgba(52, 211, 153, 0.7); } 70% { box-shadow: 0 0 0 12px rgba(52, 211, 153, 0); } 100% { box-shadow: 0 0 0 0 rgba(52, 211, 153, 0); } }
    @keyframes pulseSim { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.1); } }
    @keyframes rotateAccess { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    @keyframes cycleTierColors { 0% { width: 0%; background: #cd7f32; } 33% { width: 33%; background: #cd7f32; } 34% { width: 34%; background: #c0c0c0; } 66% { width: 66%; background: #c0c0c0; } 67% { width: 67%; background: #ffd700; } 100% { width: 100%; background: #ffd700; } }
    @keyframes tierTextFade { 0%, 33% { content: "BRONZE - LEVEL 1"; } 34%, 66% { content: "SILVER - LEVEL 2"; } 67%, 100% { content: "GOLD - LEVEL 3"; } }
    @keyframes floatMonitor { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-20px); } }
    @keyframes pulseManager { 0%, 100% { box-shadow: 0 0 10px #10b981; } 50% { box-shadow: 0 0 30px #10b981; } }
    @keyframes float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-15px); } }
    @keyframes rotate { 100% { transform: rotate(360deg); } }
    @keyframes bounceRobot { 0%, 100% { transform: translateY(0) scale(1); } 50% { transform: translateY(-8px) scale(1.05); } }
    @keyframes colorShift { 0% { filter: hue-rotate(0deg); } 50% { filter: hue-rotate(180deg); } 100% { filter: hue-rotate(360deg); } }
    .ai-manager-bubble { position: fixed; bottom: 30px; right: 30px; background: rgba(10, 15, 26, 0.9); border: 1px solid #10b981; padding: 5px 15px; border-radius: 50px; display: flex; align-items: center; gap: 8px; max-width: 300px; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3); z-index: 9999; animation: pulseManager 1.5s infinite; cursor: pointer; backdrop-filter: blur(5px); }
    .manager-avatar { animation: colorShift 5s infinite linear, bounceRobot 1.5s infinite ease-in-out; display: inline-block; font-size: 20px; }
    .manager-text { font-size: 13px; color: #e5e7eb; }
    .monitor-card { background: rgba(10, 15, 26, 0.4); border: 1px solid #10b981; padding: 25px; border-radius: 16px; width: 260px; text-align: center; color: white; box-shadow: 0 0 20px rgba(16, 185, 129, 0.2); margin: 20px auto; backdrop-filter: blur(10px); }
    .sync-circle { position: relative; width: 100px; height: 100px; border-radius: 50%; border: 4px solid rgba(255, 255, 255, 0.1); border-top: 4px solid #10b981; margin: 20px auto; animation: spin 2s linear infinite, pulse-glow 2s ease-in-out infinite; display: flex; align-items: center; justify-content: center; }
    .percentage-text { font-size: 1.2rem; font-weight: 800; color: #10b981; }
    .tier-label { font-size: 0.9rem; font-weight: bold; color: #e5e7eb; margin-top: 10px; text-transform: uppercase; letter-spacing: 1px; }
    @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    .color-bronze { color: #cd7f32; }
    .color-silver { color: #c0c0c0; }
    .color-gold { color: #ffd700; }
    a { color: #ffffff !important; text-decoration: none; }
    a:hover { color: #10b981 !important; }
    @keyframes pulse-glow { 0% { box-shadow: 0 0 5px rgba(16, 185, 129, 0.2); } 50% { box-shadow: 0 0 25px rgba(16, 185, 129, 0.7); } 100% { box-shadow: 0 0 5px rgba(16, 185, 129, 0.2); } }
</style>




</body>
</html>

