<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

require_once "include/db.php";
mysqli_set_charset($conn, "utf8mb4");

$userId = intval($_SESSION['user_id']);

// Fetch User Data
$sql = "SELECT * FROM users WHERE id = $userId LIMIT 1";
$result = mysqli_query($conn, $sql);
$currentUser = ($result && mysqli_num_rows($result) > 0) ? mysqli_fetch_assoc($result) : null;

if (!$currentUser) {
    header("Location: ../login.php");
    exit;
}

$dbTheme = $_SESSION['theme'] ?? ($currentUser['theme'] ?? '#3b82f6');
$balance = (float)($currentUser['balance'] ?? 0.00);

// ==========================================
// FETCH AI TRADING BOTS FROM DATABASE
// ==========================================
$bots = [];
$botsQuery = mysqli_query($conn, "SELECT `id`, `name`, `description`, `price`, `monthly_return`, `win_rate`, 
                                   `risk_level`, `trades_per_day`, `ai_model`, `status`, `icon`, `gradient`,
                                   `features`, `min_balance`, `total_users`, `created_at`
                                   FROM `ai_trading_bots` 
                                   WHERE `status` = 'active' 
                                   ORDER BY `price` DESC");

if ($botsQuery && mysqli_num_rows($botsQuery) > 0) {
    while ($row = mysqli_fetch_assoc($botsQuery)) {
        $bots[] = [
            'id' => (int)$row['id'],
            'name' => $row['name'],
            'description' => $row['description'],
            'price' => (float)$row['price'],
            'monthly_return' => (float)$row['monthly_return'],
            'win_rate' => (int)$row['win_rate'],
            'risk_level' => $row['risk_level'],
            'trades_per_day' => (int)$row['trades_per_day'],
            'ai_model' => $row['ai_model'],
            'status' => $row['status'],
            'icon' => $row['icon'] ?? 'bot',
            'gradient' => $row['gradient'] ?? 'from-blue-500 to-purple-600',
            'features' => json_decode($row['features'] ?? '[]', true),
            'min_balance' => (float)$row['min_balance'],
            'total_users' => (int)$row['total_users'],
            'created_at' => $row['created_at']
        ];
    }
}

// ==========================================
// FETCH USER'S ACTIVE BOT SUBSCRIPTIONS
// ==========================================
$myBots = [];
$myBotsQuery = mysqli_query($conn, "SELECT bs.`id` as subscription_id, bs.`activated_at`, bs.`status` as sub_status,
                                      bs.`allocated_balance`, bs.`total_profit`, bs.`total_trades`, bs.`win_count`,
                                      bs.`last_trade_at`, bs.`is_running`, bs.`config_json`,
                                      ab.`id`, ab.`name`, ab.`description`, ab.`price`, ab.`monthly_return`, 
                                      ab.`win_rate`, ab.`risk_level`, ab.`trades_per_day`, ab.`ai_model`, 
                                      ab.`icon`, ab.`gradient`, ab.`features`, ab.`min_balance`
                                      FROM `bot_subscriptions` bs
                                      JOIN `ai_trading_bots` ab ON bs.`bot_id` = ab.`id`
                                      WHERE bs.`user_id` = $userId AND bs.`status` = 'active'
                                      ORDER BY bs.`activated_at` DESC");

if ($myBotsQuery) {
    while ($row = mysqli_fetch_assoc($myBotsQuery)) {
        $myBots[] = [
            'subscription_id' => (int)$row['subscription_id'],
            'id' => (int)$row['id'],
            'name' => $row['name'],
            'description' => $row['description'],
            'price' => (float)$row['price'],
            'monthly_return' => (float)$row['monthly_return'],
            'win_rate' => (int)$row['win_rate'],
            'risk_level' => $row['risk_level'],
            'trades_per_day' => (int)$row['trades_per_day'],
            'ai_model' => $row['ai_model'],
            'icon' => $row['icon'],
            'gradient' => $row['gradient'],
            'features' => json_decode($row['features'] ?? '[]', true),
            'min_balance' => (float)$row['min_balance'],
            'activated_at' => $row['activated_at'],
            'sub_status' => $row['sub_status'],
            'allocated_balance' => (float)$row['allocated_balance'],
            'total_profit' => (float)$row['total_profit'],
            'total_trades' => (int)$row['total_trades'],
            'win_count' => (int)$row['win_count'],
            'last_trade_at' => $row['last_trade_at'],
            'is_running' => (int)$row['is_running'],
            'config_json' => json_decode($row['config_json'] ?? '{}', true)
        ];
    }
}

// ==========================================
// HANDLE BOT PURCHASE ACTION
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'purchase_bot') {
    ini_set('display_errors', 0);
    header('Content-Type: application/json');
    ob_start();

    try {
        $botId = intval($_POST['bot_id'] ?? 0);
        $allocatedBalance = floatval($_POST['allocated_balance'] ?? 0);

        if ($botId <= 0) {
            throw new Exception('Invalid bot selected.');
        }

        if ($allocatedBalance <= 0) {
            throw new Exception('Please enter a valid allocation amount.');
        }

        // Fetch bot details
        $botStmt = mysqli_prepare($conn, "SELECT `id`, `name`, `price`, `min_balance`, `monthly_return`, `win_rate`, 
                                          `risk_level`, `trades_per_day`, `ai_model`, `icon`, `gradient`, `features` 
                                          FROM `ai_trading_bots` WHERE `id` = ? AND `status` = 'active'");
        if (!$botStmt) throw new Exception("Prepare failed: " . mysqli_error($conn));
        
        mysqli_stmt_bind_param($botStmt, "i", $botId);
        mysqli_stmt_execute($botStmt);
        mysqli_stmt_store_result($botStmt);
        
        if (mysqli_stmt_num_rows($botStmt) === 0) {
            mysqli_stmt_close($botStmt);
            throw new Exception('Bot not found or unavailable.');
        }
        
        mysqli_stmt_bind_result($botStmt, $bId, $bName, $bPrice, $bMinBalance, $bReturn, $bWinRate,
                                $bRisk, $bTrades, $bModel, $bIcon, $bGradient, $bFeatures);
        mysqli_stmt_fetch($botStmt);
        mysqli_stmt_close($botStmt);

        // Check minimum balance requirement
        if ($allocatedBalance < $bMinBalance) {
            throw new Exception('Minimum allocation for this bot is $' . number_format($bMinBalance, 2));
        }

        // Check user balance (price + allocated balance)
        $totalRequired = $bPrice + $allocatedBalance;
        if ($balance < $totalRequired) {
            throw new Exception('Insufficient balance. You need $' . number_format($totalRequired, 2) . 
                              ' (Bot: $' . number_format($bPrice, 2) . ' + Allocation: $' . number_format($allocatedBalance, 2) . ')');
        }

        // Check if already subscribed
        $checkStmt = mysqli_prepare($conn, "SELECT `id` FROM `bot_subscriptions` WHERE `user_id` = ? AND `bot_id` = ? AND `status` = 'active'");
        if (!$checkStmt) throw new Exception("Prepare failed: " . mysqli_error($conn));
        
        mysqli_stmt_bind_param($checkStmt, "ii", $userId, $botId);
        mysqli_stmt_execute($checkStmt);
        mysqli_stmt_store_result($checkStmt);
        
        if (mysqli_stmt_num_rows($checkStmt) > 0) {
            mysqli_stmt_close($checkStmt);
            throw new Exception('You already own this bot.');
        }
        mysqli_stmt_close($checkStmt);

        // Begin transaction
        mysqli_begin_transaction($conn);

        try {
            // Deduct balance
            $newBalance = $balance - $totalRequired;
            $updateBalance = mysqli_prepare($conn, "UPDATE `users` SET `balance` = ? WHERE `id` = ?");
            mysqli_stmt_bind_param($updateBalance, "di", $newBalance, $userId);
            if (!mysqli_stmt_execute($updateBalance)) {
                throw new Exception("Balance update failed: " . mysqli_stmt_error($updateBalance));
            }
            mysqli_stmt_close($updateBalance);

            // Insert subscription
            $configJson = json_encode(['allocated_balance' => $allocatedBalance, 'auto_compound' => false, 'stop_loss' => 5.0]);
            $insertStmt = mysqli_prepare($conn, "INSERT INTO `bot_subscriptions` 
                (`user_id`, `bot_id`, `allocated_balance`, `status`, `activated_at`, `is_running`, `config_json`) 
                VALUES (?, ?, ?, 'active', NOW(), 1, ?)");
            mysqli_stmt_bind_param($insertStmt, "iids", $userId, $botId, $allocatedBalance, $configJson);
            
            if (!mysqli_stmt_execute($insertStmt)) {
                throw new Exception("Subscription failed: " . mysqli_stmt_error($insertStmt));
            }
            
            $subscriptionId = mysqli_insert_id($conn);
            mysqli_stmt_close($insertStmt);

            // Update bot user count
            mysqli_query($conn, "UPDATE `ai_trading_bots` SET `total_users` = `total_users` + 1 WHERE `id` = " . intval($botId));

            mysqli_commit($conn);

            ob_end_clean();
            echo json_encode([
                'success' => true,
                'message' => 'Successfully purchased ' . $bName . '!',
                'subscription_id' => $subscriptionId,
                'new_balance' => $newBalance,
                'bot' => [
                    'id' => $bId,
                    'name' => $bName,
                    'price' => (float)$bPrice,
                    'monthly_return' => (float)$bReturn,
                    'win_rate' => (int)$bWinRate,
                    'risk_level' => $bRisk,
                    'trades_per_day' => (int)$bTrades,
                    'ai_model' => $bModel,
                    'icon' => $bIcon,
                    'gradient' => $bGradient,
                    'features' => json_decode($bFeatures ?? '[]', true),
                    'min_balance' => (float)$bMinBalance,
                    'allocated_balance' => $allocatedBalance,
                    'total_profit' => 0.00,
                    'total_trades' => 0,
                    'win_count' => 0,
                    'is_running' => 1,
                    'activated_at' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (Exception $e) {
            mysqli_rollback($conn);
            throw $e;
        }

    } catch (Throwable $e) {
        ob_end_clean();
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ]);
    }
    exit;
}

// ==========================================
// HANDLE BOT CONTROL (START/STOP)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'toggle_bot') {
    ini_set('display_errors', 0);
    header('Content-Type: application/json');
    ob_start();

    try {
        $subscriptionId = intval($_POST['subscription_id'] ?? 0);
        $shouldRun = intval($_POST['should_run'] ?? 0);

        $toggleStmt = mysqli_prepare($conn, "UPDATE `bot_subscriptions` SET `is_running` = ? WHERE `id` = ? AND `user_id` = ?");
        if (!$toggleStmt) throw new Exception("Prepare failed: " . mysqli_error($conn));
        
        mysqli_stmt_bind_param($toggleStmt, "iii", $shouldRun, $subscriptionId, $userId);
        
        if (!mysqli_stmt_execute($toggleStmt)) {
            throw new Exception("Update failed: " . mysqli_stmt_error($toggleStmt));
        }
        
        mysqli_stmt_close($toggleStmt);

        ob_end_clean();
        echo json_encode([
            'success' => true,
            'message' => $shouldRun ? 'Bot activated' : 'Bot paused',
            'is_running' => $shouldRun
        ]);

    } catch (Throwable $e) {
        ob_end_clean();
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ]);
    }
    exit;
}
?>

<?php include "include/header.php"?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>

<style>
    :root {
        --primary-theme: <?php echo htmlspecialchars($dbTheme, ENT_QUOTES, 'UTF-8'); ?>;
        --primary-rgb: <?php 
            $hex = ltrim($dbTheme, '#');
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));
            echo "$r, $g, $b";
        ?>;
        --neon-glow: 0 0 20px rgba(var(--primary-rgb), 0.5), 0 0 40px rgba(var(--primary-rgb), 0.3);
    }
    
    .text-theme { color: var(--primary-theme) !important; }
    .bg-theme { background-color: var(--primary-theme) !important; }
    .border-theme { border-color: var(--primary-theme) !important; }
    
    .glass-card {
        background: rgba(255, 255, 255, 0.7);
        backdrop-filter: blur(16px);
        border: 1px solid rgba(0, 0, 0, 0.05);
    }
    .dark .glass-card {
        background: rgba(15, 23, 42, 0.6);
        border: 1px solid rgba(255, 255, 255, 0.05);
    }

    /* AI Neural Network Background */
    .ai-bg {
        position: fixed;
        top: 0; left: 0; width: 100%; height: 100%;
        pointer-events: none;
        z-index: 0;
        opacity: 0.4;
    }
    .dark .ai-bg { opacity: 0.2; }
    
    /* Bot Card Styles */
    .bot-card {
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .bot-card:hover {
        transform: translateY(-6px);
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
    }
    .bot-card.owned {
        border: 2px solid var(--primary-theme);
        box-shadow: var(--neon-glow);
    }
    .bot-card.owned::after {
        content: '✓ ACTIVE';
        position: absolute;
        top: 14px;
        right: -30px;
        width: 130px;
        background: var(--primary-theme);
        color: white;
        text-align: center;
        font-size: 9px;
        font-weight: 900;
        text-transform: uppercase;
        letter-spacing: 0.08em;
        padding: 5px 0;
        transform: rotate(45deg);
        box-shadow: 0 2px 10px rgba(var(--primary-rgb), 0.4);
    }
    
    /* AI Brain Pulse Animation */
    @keyframes brainPulse {
        0%, 100% { transform: scale(1); opacity: 0.8; filter: drop-shadow(0 0 5px rgba(var(--primary-rgb), 0.5)); }
        50% { transform: scale(1.05); opacity: 1; filter: drop-shadow(0 0 20px rgba(var(--primary-rgb), 0.8)); }
    }
    .ai-brain {
        animation: brainPulse 2s ease-in-out infinite;
    }
    
    /* Trading Animation */
    @keyframes tradePulse {
        0% { transform: scale(0.95); opacity: 0; }
        50% { transform: scale(1.05); opacity: 1; }
        100% { transform: scale(1); opacity: 0.8; }
    }
    .trade-anim {
        animation: tradePulse 0.6s ease-out;
    }
    
    /* Scanning Line Effect */
    @keyframes scanLine {
        0% { top: 0%; opacity: 0; }
        10% { opacity: 1; }
        90% { opacity: 1; }
        100% { top: 100%; opacity: 0; }
    }
    .scan-line {
        position: absolute;
        left: 0;
        width: 100%;
        height: 2px;
        background: linear-gradient(90deg, transparent, var(--primary-theme), transparent);
        box-shadow: 0 0 10px var(--primary-theme);
        animation: scanLine 3s linear infinite;
        pointer-events: none;
    }
    
    /* Matrix Rain Effect for Trading Terminal */
    @keyframes matrixDrop {
        0% { transform: translateY(-100%); opacity: 1; }
        100% { transform: translateY(100vh); opacity: 0; }
    }
    .matrix-char {
        position: absolute;
        color: var(--primary-theme);
        font-family: 'Courier New', monospace;
        font-size: 12px;
        font-weight: bold;
        opacity: 0.6;
        animation: matrixDrop linear infinite;
    }
    
    /* Spinning Loader */
    @keyframes aiSpin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    .ai-spinner {
        animation: aiSpin 1s linear infinite;
    }
    
    /* Neural Connection Lines */
    .neural-line {
        stroke: rgba(var(--primary-rgb), 0.3);
        stroke-width: 1;
        animation: neuralPulse 2s ease-in-out infinite;
    }
    @keyframes neuralPulse {
        0%, 100% { stroke-opacity: 0.2; }
        50% { stroke-opacity: 0.6; }
    }
    
    /* Progress Ring */
    .progress-ring-circle {
        transition: stroke-dashoffset 0.5s ease;
        transform: rotate(-90deg);
        transform-origin: 50% 50%;
    }
    
    /* Risk Level Badges */
    .risk-low { background: rgba(16, 185, 129, 0.1); color: #10b981; }
    .risk-moderate { background: rgba(245, 158, 11, 0.1); color: #f59e0b; }
    .risk-high { background: rgba(244, 63, 94, 0.1); color: #f43f5e; }
    
    /* Modal Styles */
    .modal-overlay {
        background: rgba(0, 0, 0, 0.7);
        backdrop-filter: blur(8px);
    }
    
    /* Terminal Window */
    .terminal-window {
        background: #0a0e1a;
        border: 1px solid rgba(var(--primary-rgb), 0.3);
        font-family: 'Courier New', monospace;
    }
    .terminal-header {
        background: rgba(var(--primary-rgb), 0.1);
        border-bottom: 1px solid rgba(var(--primary-rgb), 0.2);
    }
    .terminal-line {
        animation: typeLine 0.3s ease-out forwards;
        opacity: 0;
    }
    @keyframes typeLine {
        to { opacity: 1; }
    }
    
    /* Glow Button */
    .glow-btn {
        position: relative;
        overflow: hidden;
        transition: all 0.3s ease;
    }
    .glow-btn::before {
        content: '';
        position: absolute;
        top: 50%; left: 50%;
        width: 0; height: 0;
        background: rgba(255,255,255,0.2);
        border-radius: 50%;
        transform: translate(-50%, -50%);
        transition: width 0.6s, height 0.6s;
    }
    .glow-btn:hover::before {
        width: 300px; height: 300px;
    }
    .glow-btn:hover {
        box-shadow: var(--neon-glow);
        transform: translateY(-2px);
    }
    
    /* Floating Particles */
    @keyframes float {
        0%, 100% { transform: translateY(0) translateX(0); }
        25% { transform: translateY(-20px) translateX(10px); }
        50% { transform: translateY(-10px) translateX(-10px); }
        75% { transform: translateY(-30px) translateX(5px); }
    }
    .float-particle {
        animation: float 6s ease-in-out infinite;
    }
    
    /* Stat Counter Animation */
    @keyframes countUp {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .stat-appear {
        animation: countUp 0.5s ease-out forwards;
    }
    
    /* Toggle Switch */
    .ai-toggle {
        width: 52px;
        height: 28px;
        background: #334155;
        border-radius: 14px;
        position: relative;
        cursor: pointer;
        transition: background 0.3s;
    }
    .ai-toggle.active {
        background: var(--primary-theme);
    }
    .ai-toggle::after {
        content: '';
        position: absolute;
        width: 22px; height: 22px;
        background: white;
        border-radius: 50%;
        top: 3px; left: 3px;
        transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    }
    .ai-toggle.active::after {
        transform: translateX(24px);
    }
    
    .search-input {
        transition: all 0.3s ease;
        background: rgba(255,255,255,0.1);
        border: 1px solid rgba(255,255,255,0.1);
    }
    .search-input:focus {
        border-color: var(--primary-theme);
        box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.15), var(--neon-glow);
        outline: none;
    }
</style>

<!-- AI Neural Background SVG -->
<svg class="ai-bg" viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMid slice">
    <defs>
        <radialGradient id="neuralGrad" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stop-color="rgba(var(--primary-rgb), 0.1)"/>
            <stop offset="100%" stop-color="transparent"/>
        </radialGradient>
    </defs>
    <g id="neural-network"></g>
</svg>

<?php include "include/nav.php"?>

<div class="flex min-h-screen bg-slate-50 dark:bg-[#050810] transition-colors duration-300 relative"
     x-data='{
        bots: <?= json_encode($bots, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
        myBots: <?= json_encode($myBots, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
        balance: <?= $balance ?>,
        searchQuery: "",
        selectedRisk: "all",
        sortBy: "price",
        isSubmitting: false,
        showPurchaseModal: false,
        showBotModal: false,
        showTradingTerminal: false,
        selectedBot: null,
        purchaseAmount: "",
        activeTerminalBot: null,
        terminalLogs: [],
        isTrading: false,
        tradingProgress: 0,
        
        get filteredBots() {
            let filtered = this.bots;
            
            if (this.searchQuery) {
                const q = this.searchQuery.toLowerCase();
                filtered = filtered.filter(b => b.name.toLowerCase().includes(q) || 
                                               b.ai_model.toLowerCase().includes(q) ||
                                               b.description.toLowerCase().includes(q));
            }
            
            if (this.selectedRisk !== "all") {
                filtered = filtered.filter(b => b.risk_level === this.selectedRisk);
            }
            
            if (this.sortBy === "price") {
                filtered = [...filtered].sort((a, b) => b.price - a.price);
            } else if (this.sortBy === "return") {
                filtered = [...filtered].sort((a, b) => b.monthly_return - a.monthly_return);
            } else if (this.sortBy === "win_rate") {
                filtered = [...filtered].sort((a, b) => b.win_rate - a.win_rate);
            } else if (this.sortBy === "popular") {
                filtered = [...filtered].sort((a, b) => b.total_users - a.total_users);
            }
            
            return filtered;
        },
        
        isOwned(botId) {
            return this.myBots.some(b => b.id === botId);
        },
        
        getOwnedBot(botId) {
            return this.myBots.find(b => b.id === botId);
        },
        
        get totalBotProfit() {
            return this.myBots.reduce((sum, b) => sum + b.total_profit, 0);
        },
        
        get activeBotCount() {
            return this.myBots.filter(b => b.is_running).length;
        },
        
        get totalTradesExecuted() {
            return this.myBots.reduce((sum, b) => sum + b.total_trades, 0);
        },
        
        async purchaseBot() {
            if (!this.selectedBot || !this.purchaseAmount) return;
            
            const amount = parseFloat(this.purchaseAmount);
            if (isNaN(amount) || amount <= 0) {
                Swal.fire({ icon: "error", title: "Invalid Amount", text: "Please enter a valid allocation amount.", confirmButtonColor: "var(--primary-theme)" });
                return;
            }
            
            if (amount < this.selectedBot.min_balance) {
                Swal.fire({ icon: "error", title: "Minimum Required", text: "Minimum allocation is $" + this.selectedBot.min_balance.toFixed(2), confirmButtonColor: "var(--primary-theme)" });
                return;
            }
            
            const totalNeeded = this.selectedBot.price + amount;
            if (totalNeeded > this.balance) {
                Swal.fire({ icon: "error", title: "Insufficient Balance", text: "You need $" + totalNeeded.toFixed(2) + " total.", confirmButtonColor: "var(--primary-theme)" });
                return;
            }
            
            this.isSubmitting = true;
            
            const params = new URLSearchParams();
            params.append("action", "purchase_bot");
            params.append("bot_id", this.selectedBot.id);
            params.append("allocated_balance", amount);
            
            try {
                const response = await fetch("AItradingBot.php", { 
                    method: "POST", 
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: params.toString() 
                });
                const data = await response.json();
                
                if (data.success) {
                    Swal.fire({ 
                        icon: "success", 
                        title: "Bot Activated!", 
                        text: data.message, 
                        confirmButtonColor: "var(--primary-theme)",
                        timer: 3000,
                        showConfirmButton: false
                    });
                    
                    this.balance = data.new_balance;
                    this.myBots.unshift(data.bot);
                    this.showPurchaseModal = false;
                    this.purchaseAmount = "";
                    
                } else {
                    Swal.fire({ icon: "error", title: "Purchase Failed", text: data.message, confirmButtonColor: "var(--primary-theme)" });
                }
            } catch (error) {
                console.error("Purchase error:", error);
                Swal.fire({ icon: "error", title: "Error", text: "Something went wrong. Please try again.", confirmButtonColor: "var(--primary-theme)" });
            } finally {
                this.isSubmitting = false;
            }
        },
        
        async toggleBot(subscriptionId, currentStatus) {
            const newStatus = currentStatus ? 0 : 1;
            
            const params = new URLSearchParams();
            params.append("action", "toggle_bot");
            params.append("subscription_id", subscriptionId);
            params.append("should_run", newStatus);
            
            try {
                const response = await fetch("AItradingBot.php", { 
                    method: "POST", 
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: params.toString() 
                });
                const data = await response.json();
                
                if (data.success) {
                    const bot = this.myBots.find(b => b.subscription_id === subscriptionId);
                    if (bot) bot.is_running = newStatus;
                    
                    Swal.fire({ 
                        icon: "success", 
                        title: data.message, 
                        timer: 1500,
                        showConfirmButton: false
                    });
                }
            } catch (error) {
                console.error("Toggle error:", error);
            }
        },
        
        openTradingTerminal(bot) {
            this.activeTerminalBot = bot;
            this.showTradingTerminal = true;
            this.terminalLogs = [];
            this.isTrading = true;
            this.tradingProgress = 0;
            this.simulateTrading();
        },
        
        simulateTrading() {
            const actions = [
                "Initializing neural network...",
                "Loading market data feeds...",
                "Analyzing BTC/USDT 1H pattern...",
                "RSI indicator: 62.4 - Neutral zone",
                "MACD crossover detected - Bullish signal",
                "Scanning order book depth...",
                "Liquidity analysis complete",
                "Risk assessment: LOW (2.1%)",
                "Executing BUY order: 0.15 BTC @ $67,245",
                "Order filled - Position opened",
                "Setting stop-loss: $65,800",
                "Setting take-profit: $69,100",
                "Monitoring position...",
                "Price movement: +0.8% in favor",
                "Partial profit secured: +$142.50",
                "Trailing stop activated",
                "Market volatility increasing...",
                "Adjusting position size...",
                "New signal detected: ETH/USDT",
                "Analyzing correlation matrix...",
                "Diversifying portfolio...",
                "Trade cycle complete. Profit: +$287.40"
            ];
            
            let i = 0;
            const interval = setInterval(() => {
                if (i >= actions.length) {
                    clearInterval(interval);
                    this.isTrading = false;
                    this.tradingProgress = 100;
                    return;
                }
                
                const timestamp = new Date().toLocaleTimeString();
                this.terminalLogs.unshift({ time: timestamp, message: actions[i], type: actions[i].includes("Profit") ? "profit" : actions[i].includes("BUY") || actions[i].includes("SELL") ? "trade" : "info" });
                this.tradingProgress = Math.min((i / actions.length) * 100, 95);
                i++;
            }, 800);
        },
        
        openBotModal(bot) {
            this.selectedBot = bot;
            this.showBotModal = true;
        },
        
        openPurchaseModal(bot) {
            this.selectedBot = bot;
            this.purchaseAmount = bot.min_balance.toString();
            this.showPurchaseModal = true;
        },
        
        formatPrice(price) {
            return price.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        },
        
        getRiskClass(risk) {
            return "risk-" + risk;
        },
        
        getWinRateColor(rate) {
            if (rate >= 85) return "text-emerald-400";
            if (rate >= 70) return "text-amber-400";
            return "text-rose-400";
        }
     }'>
  
  <?php include "include/sidebar.php"?>
  
  <main class="flex-1 min-w-0 md:ml-72 pb-24 md:pb-8 relative z-10">
    <div class="max-w-screen-2xl mx-auto px-4 sm:px-6 py-8">

      <!-- Header -->
      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
          <h1 class="text-4xl font-black text-slate-900 dark:text-white tracking-tight flex items-center gap-3">
            <span class="ai-brain">
                <svg class="w-10 h-10 text-theme" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.455 2.456L21.75 6l-1.036.259a3.375 3.375 0 00-2.455 2.456zM16.894 20.567L16.5 21.75l-.394-1.183a2.25 2.25 0 00-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 001.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 001.423 1.423l1.183.394-1.183.394a2.25 2.25 0 00-1.423 1.423z"/>
                </svg>
            </span>
            AI Trading <span class="text-theme">Bots</span>
          </h1>
          <p class="text-sm text-slate-500 dark:text-slate-400 mt-2">Autonomous neural networks that trade 24/7 on your behalf.</p>
        </div>
        <div class="flex items-center gap-4">
            <div class="glass-card rounded-2xl px-6 py-4 flex items-center gap-3 border border-theme/20">
                <div class="w-3 h-3 rounded-full bg-emerald-500 animate-pulse shadow-[0_0_10px_#10b981]"></div>
                <div>
                    <span class="text-[10px] font-black uppercase tracking-widest text-slate-500 dark:text-slate-400 block">Available Balance</span>
                    <span class="text-xl font-black text-slate-900 dark:text-white font-mono" x-text="&#39;$&#39; + formatPrice(balance)"></span>
                </div>
            </div>
        </div>
      </div>

      <!-- Stats Overview -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-10">
        <div class="glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800 relative overflow-hidden group">
            <div class="scan-line"></div>
            <div class="relative z-10">
                <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Active Bots</p>
                <p class="text-3xl font-black text-slate-900 dark:text-white" x-text="activeBotCount"></p>
            </div>
            <div class="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-2xl bg-theme/10 flex items-center justify-center text-theme group-hover:scale-110 transition-transform">
                <i data-lucide="cpu" class="w-6 h-6"></i>
            </div>
        </div>
        <div class="glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800 relative overflow-hidden group">
            <div class="scan-line" style="animation-delay: 0.5s;"></div>
            <div class="relative z-10">
                <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Total Profit</p>
                <p class="text-3xl font-black" :class="totalBotProfit >= 0 ? &#39;text-emerald-400&#39; : &#39;text-rose-400&#39;" x-text="(totalBotProfit >= 0 ? &#39;+$&#39; : &#39;-$&#39;) + formatPrice(Math.abs(totalBotProfit))"></p>
            </div>
            <div class="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-2xl bg-emerald-500/10 flex items-center justify-center text-emerald-500 group-hover:scale-110 transition-transform">
                <i data-lucide="trending-up" class="w-6 h-6"></i>
            </div>
        </div>
        <div class="glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800 relative overflow-hidden group">
            <div class="scan-line" style="animation-delay: 1s;"></div>
            <div class="relative z-10">
                <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Trades Executed</p>
                <p class="text-3xl font-black text-theme" x-text="totalTradesExecuted.toLocaleString()"></p>
            </div>
            <div class="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-2xl bg-theme/10 flex items-center justify-center text-theme group-hover:scale-110 transition-transform">
                <i data-lucide="activity" class="w-6 h-6"></i>
            </div>
        </div>
        <div class="glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800 relative overflow-hidden group">
            <div class="scan-line" style="animation-delay: 1.5s;"></div>
            <div class="relative z-10">
                <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Bots Owned</p>
                <p class="text-3xl font-black text-slate-900 dark:text-white" x-text="myBots.length"></p>
            </div>
            <div class="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-2xl bg-purple-500/10 flex items-center justify-center text-purple-500 group-hover:scale-110 transition-transform">
                <i data-lucide="bot" class="w-6 h-6"></i>
            </div>
        </div>
      </div>

      <!-- My Active Bots -->
      <div x-show="myBots.length > 0" class="mb-10" x-transition>
        <h2 class="text-xs font-black uppercase tracking-widest text-slate-400 mb-4 flex items-center gap-2">
            <span class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
            Your Active AI Bots
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
            <template x-for="bot in myBots" :key="bot.subscription_id">
                <div class="bot-card owned glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800 relative overflow-hidden">
                    <div class="absolute inset-0 bg-gradient-to-br from-theme/5 to-transparent pointer-events-none"></div>
                    
                    <div class="flex items-center justify-between mb-5 relative z-10">
                        <div class="flex items-center gap-4">
                            <div class="w-14 h-14 rounded-2xl bg-gradient-to-br flex items-center justify-center text-white font-black text-2xl shadow-lg ai-brain" 
                                 :class="bot.gradient">
                                <i :data-lucide="bot.icon" class="w-7 h-7"></i>
                            </div>
                            <div>
                                <h3 class="text-sm font-black text-slate-900 dark:text-white" x-text="bot.name"></h3>
                                <p class="text-[10px] text-slate-500 dark:text-slate-400 font-mono mt-0.5" x-text="bot.ai_model"></p>
                            </div>
                        </div>
                        <div @click="toggleBot(bot.subscription_id, bot.is_running)" 
                             :class="bot.is_running ? &#39;active&#39; : &#39;&#39;"
                             class="ai-toggle" :title="bot.is_running ? &#39;Pause Bot&#39; : &#39;Resume Bot&#39;"></div>
                    </div>

                    <div class="grid grid-cols-2 gap-3 mb-4 relative z-10">
                        <div class="p-3 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                            <p class="text-[8px] font-black uppercase tracking-widest text-slate-400">Allocated</p>
                            <p class="text-sm font-black text-slate-900 dark:text-white font-mono" x-text="&#39;$&#39; + formatPrice(bot.allocated_balance)"></p>
                        </div>
                        <div class="p-3 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                            <p class="text-[8px] font-black uppercase tracking-widest text-slate-400">Profit</p>
                            <p class="text-sm font-black" :class="bot.total_profit >= 0 ? &#39;text-emerald-400&#39; : &#39;text-rose-400&#39;" x-text="(bot.total_profit >= 0 ? &#39;+$&#39; : &#39;-$&#39;) + formatPrice(Math.abs(bot.total_profit))"></p>
                        </div>
                        <div class="p-3 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                            <p class="text-[8px] font-black uppercase tracking-widest text-slate-400">Win Rate</p>
                            <p class="text-sm font-black text-theme" x-text="bot.win_count + &#39;/&#39; + bot.total_trades"></p>
                        </div>
                        <div class="p-3 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                            <p class="text-[8px] font-black uppercase tracking-widest text-slate-400">Status</p>
                            <p class="text-sm font-black" :class="bot.is_running ? &#39;text-emerald-400&#39; : &#39;text-amber-400&#39;" x-text="bot.is_running ? &#39;RUNNING&#39; : &#39;PAUSED&#39;"></p>
                        </div>
                    </div>

                    <div class="flex gap-2 relative z-10">
                        <button @click="openTradingTerminal(bot)" 
                                class="flex-1 glow-btn py-3 rounded-xl bg-theme text-white text-xs font-black uppercase tracking-widest shadow-lg">
                            <span class="relative z-10 flex items-center justify-center gap-2">
                                <i data-lucide="play" class="w-4 h-4"></i>
                                Simulate Trade
                            </span>
                        </button>
                        <button @click="openBotModal(bots.find(b => b.id === bot.id))" 
                                class="px-4 py-3 rounded-xl bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors">
                            <i data-lucide="settings" class="w-4 h-4"></i>
                        </button>
                    </div>
                </div>
            </template>
        </div>
      </div>

      <!-- Search & Filters -->
      <div class="glass-card rounded-[2rem] p-4 mb-8 border border-slate-200 dark:border-slate-800">
        <div class="flex flex-col lg:flex-row gap-4">
            <div class="flex-1 relative">
                <i data-lucide="search" class="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"></i>
                <input type="text" x-model="searchQuery" placeholder="Search AI bots by name or model..."
                       class="search-input w-full pl-10 pr-4 py-3 rounded-xl text-slate-900 dark:text-white font-bold text-sm">
            </div>
            <div class="flex gap-2 overflow-x-auto">
                <button @click="selectedRisk = &#39;all&#39;" :class="selectedRisk === &#39;all&#39; ? &#39;active bg-theme text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400&#39;" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap transition-all">All Risk</button>
                <button @click="selectedRisk = &#39;low&#39;" :class="selectedRisk === &#39;low&#39; ? &#39;active bg-emerald-500 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400&#39;" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap transition-all">Low Risk</button>
                <button @click="selectedRisk = &#39;moderate&#39;" :class="selectedRisk === &#39;moderate&#39; ? &#39;active bg-amber-500 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400&#39;" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap transition-all">Moderate</button>
                <button @click="selectedRisk = &#39;high&#39;" :class="selectedRisk === &#39;high&#39; ? &#39;active bg-rose-500 text-white&#39; : &#39;bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400&#39;" 
                        class="filter-pill px-5 py-3 rounded-xl text-xs font-black uppercase tracking-widest whitespace-nowrap transition-all">High Risk</button>
            </div>
            <select x-model="sortBy" class="px-4 py-3 rounded-xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-bold text-xs uppercase tracking-widest focus:outline-none focus:border-theme">
                <option value="price">Price: High to Low</option>
                <option value="return">Best Returns</option>
                <option value="win_rate">Win Rate</option>
                <option value="popular">Most Popular</option>
            </select>
        </div>
      </div>

      <!-- Bots Grid -->
      <h2 class="text-xs font-black uppercase tracking-widest text-slate-400 mb-4">Available AI Bots</h2>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
        <template x-for="bot in filteredBots" :key="bot.id">
            <div @click="isOwned(bot.id) ? openBotModal(bot) : openPurchaseModal(bot)" 
                 :class="isOwned(bot.id) ? &#39;owned&#39; : &#39;&#39;"
                 class="bot-card glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800 relative group">
                
                <!-- Price Tag -->
                <div class="absolute top-4 right-4 px-3 py-1 rounded-full bg-slate-900 dark:bg-white text-white dark:text-slate-900 text-xs font-black">
                    $<span x-text="formatPrice(bot.price)"></span><span class="text-[9px] opacity-60">/mo</span>
                </div>

                <div class="flex items-center gap-4 mb-5">
                    <div class="w-16 h-16 rounded-2xl bg-gradient-to-br flex items-center justify-center text-white font-black text-2xl shadow-xl transition-transform group-hover:scale-110" 
                         :class="bot.gradient">
                        <i :data-lucide="bot.icon" class="w-8 h-8"></i>
                    </div>
                    <div class="flex-1">
                        <h3 class="text-lg font-black text-slate-900 dark:text-white" x-text="bot.name"></h3>
                        <p class="text-[10px] text-slate-500 dark:text-slate-400 font-mono" x-text="bot.ai_model"></p>
                        <div class="flex items-center gap-2 mt-1.5">
                            <span class="px-2 py-0.5 rounded text-[8px] font-black uppercase tracking-widest"
                                  :class="&#39;risk-&#39; + bot.risk_level" x-text="bot.risk_level"></span>
                            <span class="text-[9px] text-slate-400 font-mono" x-text="bot.trades_per_day + &#39; trades/day&#39;"></span>
                        </div>
                    </div>
                </div>

                <p class="text-xs text-slate-600 dark:text-slate-300 leading-relaxed mb-5 line-clamp-2" x-text="bot.description"></p>

                <!-- Performance Metrics -->
                <div class="space-y-3 mb-5">
                    <div>
                        <div class="flex justify-between items-center mb-1">
                            <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">Monthly Return</span>
                            <span class="text-sm font-black text-emerald-400" x-text="&#39;+&#39; + bot.monthly_return + &#39;%&#39;"></span>
                        </div>
                        <div class="h-1.5 rounded-full bg-slate-200 dark:bg-slate-800 overflow-hidden">
                            <div class="h-full rounded-full bg-emerald-500 transition-all duration-1000" :style="&#39;width: &#39; + Math.min(bot.monthly_return * 2, 100) + &#39;%&#39;"></div>
                        </div>
                    </div>
                    <div>
                        <div class="flex justify-between items-center mb-1">
                            <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">Win Rate</span>
                            <span class="text-sm font-black" :class="getWinRateColor(bot.win_rate)" x-text="bot.win_rate + &#39;%&#39;"></span>
                        </div>
                        <div class="h-1.5 rounded-full bg-slate-200 dark:bg-slate-800 overflow-hidden">
                            <div class="h-full rounded-full bg-theme transition-all duration-1000" :style="&#39;width: &#39; + bot.win_rate + &#39;%&#39;"></div>
                        </div>
                    </div>
                </div>

                <!-- Features -->
                <div class="flex flex-wrap gap-1.5 mb-5">
                    <template x-for="feature in bot.features" :key="feature">
                        <span class="px-2 py-1 rounded-lg bg-slate-100 dark:bg-slate-800 text-[9px] font-bold text-slate-600 dark:text-slate-400" x-text="feature"></span>
                    </template>
                </div>

                <div class="flex items-center justify-between pt-4 border-t border-slate-200 dark:border-slate-800">
                    <div class="flex items-center gap-1.5">
                        <i data-lucide="users" class="w-3 h-3 text-slate-400"></i>
                        <span class="text-[10px] font-bold text-slate-500" x-text="bot.total_users.toLocaleString() + &#39; users&#39;"></span>
                    </div>
                    <button @click.stop="isOwned(bot.id) ? openTradingTerminal(getOwnedBot(bot.id)) : openPurchaseModal(bot)" 
                            :class="isOwned(bot.id) ? &#39;bg-emerald-500 hover:bg-emerald-600&#39; : &#39;bg-theme hover:brightness-110&#39;"
                            class="glow-btn px-6 py-2.5 rounded-xl text-white text-xs font-black uppercase tracking-widest shadow-lg transition-all">
                        <span class="relative z-10" x-text="isOwned(bot.id) ? &#39;Trade Now&#39; : &#39;Get Bot&#39;"></span>
                    </button>
                </div>
            </div>
        </template>
        
        <div x-show="filteredBots.length === 0" class="col-span-full text-center py-20">
            <div class="w-20 h-20 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mx-auto mb-4">
                <i data-lucide="bot-off" class="w-10 h-10 text-slate-300"></i>
            </div>
            <p class="text-sm font-bold text-slate-500 uppercase tracking-widest">No AI bots found matching your criteria.</p>
        </div>
      </div>

    </div>
  </main>

  <!-- Purchase Modal -->
  <div x-show="showPurchaseModal" style="display: none;" class="fixed inset-0 z-50 flex items-center justify-center modal-overlay p-4" x-transition>
    <div class="glass-card rounded-[2.5rem] p-8 max-w-md w-full border border-slate-200 dark:border-slate-800 shadow-2xl relative" @click.away="showPurchaseModal = false">
        <button @click="showPurchaseModal = false" class="absolute top-6 right-6 w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-slate-400 hover:text-slate-600 transition-colors">
            <i data-lucide="x" class="w-5 h-5"></i>
        </button>

        <template x-if="selectedBot">
            <div>
                <div class="text-center mb-6">
                    <div class="w-20 h-20 rounded-3xl bg-gradient-to-br flex items-center justify-center text-white font-black text-3xl shadow-xl mx-auto mb-4 ai-brain" 
                         :class="selectedBot.gradient">
                        <i :data-lucide="selectedBot.icon" class="w-10 h-10"></i>
                    </div>
                    <h3 class="text-2xl font-black text-slate-900 dark:text-white" x-text="selectedBot.name"></h3>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1" x-text="selectedBot.ai_model"></p>
                </div>

                <div class="space-y-4 mb-6">
                    <div class="flex justify-between p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Bot Price</span>
                        <span class="text-sm font-black text-slate-900 dark:text-white" x-text="&#39;$&#39; + formatPrice(selectedBot.price) + &#39;/mo&#39;"></span>
                    </div>
                    <div class="flex justify-between p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Min Allocation</span>
                        <span class="text-sm font-black text-theme" x-text="&#39;$&#39; + formatPrice(selectedBot.min_balance)"></span>
                    </div>
                    <div class="flex justify-between p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Expected Monthly</span>
                        <span class="text-sm font-black text-emerald-400" x-text="&#39;+&#39; + selectedBot.monthly_return + &#39;%&#39;"></span>
                    </div>
                </div>

                <div class="mb-6">
                    <label class="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-2 block">Allocation Amount ($)</label>
                    <input type="number" x-model="purchaseAmount" :min="selectedBot.min_balance" step="100"
                           class="w-full px-4 py-4 rounded-2xl bg-slate-50 dark:bg-slate-900 border-2 border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-black text-lg text-center focus:outline-none focus:border-theme transition-colors font-mono"
                           placeholder="Enter amount...">
                    <p class="text-[10px] text-slate-400 mt-2 text-center">Total required: $<span x-text="formatPrice(selectedBot.price + parseFloat(purchaseAmount || 0))"></span></p>
                </div>

                <button @click="purchaseBot" :disabled="isSubmitting"
                        class="w-full glow-btn py-4 rounded-2xl bg-theme text-white font-black uppercase tracking-widest text-sm shadow-xl transition-all flex items-center justify-center gap-2">
                    <span x-show="!isSubmitting" class="relative z-10 flex items-center gap-2">
                        <i data-lucide="zap" class="w-5 h-5"></i>
                        Activate Bot Now
                    </span>
                    <span x-show="isSubmitting" class="relative z-10 flex items-center gap-2">
                        <svg class="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        Processing...
                    </span>
                </button>
            </div>
        </template>
    </div>
  </div>

  <!-- Bot Detail Modal -->
  <div x-show="showBotModal" style="display: none;" class="fixed inset-0 z-50 flex items-center justify-center modal-overlay p-4" x-transition>
    <div class="glass-card rounded-[2.5rem] p-8 max-w-lg w-full border border-slate-200 dark:border-slate-800 shadow-2xl max-h-[85vh] overflow-y-auto relative" @click.away="showBotModal = false">
        <button @click="showBotModal = false" class="absolute top-6 right-6 w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-slate-400 hover:text-slate-600 transition-colors z-10">
            <i data-lucide="x" class="w-5 h-5"></i>
        </button>

        <template x-if="selectedBot">
            <div>
                <div class="flex items-center gap-4 mb-6">
                    <div class="w-20 h-20 rounded-3xl bg-gradient-to-br flex items-center justify-center text-white font-black text-2xl shadow-xl ai-brain" 
                         :class="selectedBot.gradient">
                        <i :data-lucide="selectedBot.icon" class="w-10 h-10"></i>
                    </div>
                    <div>
                        <h3 class="text-2xl font-black text-slate-900 dark:text-white" x-text="selectedBot.name"></h3>
                        <p class="text-sm text-slate-500 dark:text-slate-400" x-text="selectedBot.ai_model"></p>
                        <div class="flex items-center gap-2 mt-2">
                            <span class="px-2 py-0.5 rounded text-[10px] font-black uppercase tracking-widest"
                                  :class="&#39;risk-&#39; + selectedBot.risk_level" x-text="selectedBot.risk_level"></span>
                            <span class="text-xs text-slate-400" x-text="selectedBot.trades_per_day + &#39; trades/day&#39;"></span>
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-3 gap-3 mb-6">
                    <div class="p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800 text-center">
                        <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Return</p>
                        <p class="text-xl font-black text-emerald-400" x-text="&#39;+&#39; + selectedBot.monthly_return + &#39;%&#39;"></p>
                    </div>
                    <div class="p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800 text-center">
                        <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Win Rate</p>
                        <p class="text-xl font-black text-theme" x-text="selectedBot.win_rate + &#39;%&#39;"></p>
                    </div>
                    <div class="p-4 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800 text-center">
                        <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Users</p>
                        <p class="text-xl font-black text-slate-900 dark:text-white" x-text="selectedBot.total_users.toLocaleString()"></p>
                    </div>
                </div>

                <div class="space-y-3 mb-6">
                    <div class="flex justify-between items-center p-3 rounded-xl bg-slate-50 dark:bg-slate-900/30">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">AI Model</span>
                        <span class="text-sm font-black text-slate-700 dark:text-slate-300 font-mono" x-text="selectedBot.ai_model"></span>
                    </div>
                    <div class="flex justify-between items-center p-3 rounded-xl bg-slate-50 dark:bg-slate-900/30">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Monthly Fee</span>
                        <span class="text-sm font-black text-slate-700 dark:text-slate-300" x-text="&#39;$&#39; + formatPrice(selectedBot.price)"></span>
                    </div>
                    <div class="flex justify-between items-center p-3 rounded-xl bg-slate-50 dark:bg-slate-900/30">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Min Balance</span>
                        <span class="text-sm font-black text-slate-700 dark:text-slate-300" x-text="&#39;$&#39; + formatPrice(selectedBot.min_balance)"></span>
                    </div>
                </div>

                <div class="mb-6">
                    <p class="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-2">Features</p>
                    <div class="flex flex-wrap gap-2">
                        <template x-for="feature in selectedBot.features" :key="feature">
                            <span class="px-3 py-1.5 rounded-lg bg-theme/10 text-theme text-xs font-bold" x-text="feature"></span>
                        </template>
                    </div>
                </div>

                <p class="text-sm text-slate-600 dark:text-slate-300 leading-relaxed mb-6" x-text="selectedBot.description"></p>

                <button x-show="!isOwned(selectedBot.id)" @click="showBotModal = false; openPurchaseModal(selectedBot)" 
                        class="w-full glow-btn py-4 rounded-2xl bg-theme text-white font-black uppercase tracking-widest text-sm shadow-xl transition-all">
                    <span class="relative z-10 flex items-center justify-center gap-2">
                        <i data-lucide="shopping-cart" class="w-5 h-5"></i>
                        Purchase Bot
                    </span>
                </button>
                
                <button x-show="isOwned(selectedBot.id)" @click="showBotModal = false; openTradingTerminal(getOwnedBot(selectedBot.id))" 
                        class="w-full glow-btn py-4 rounded-2xl bg-emerald-500 text-white font-black uppercase tracking-widest text-sm shadow-xl transition-all">
                    <span class="relative z-10 flex items-center justify-center gap-2">
                        <i data-lucide="play" class="w-5 h-5"></i>
                        Launch Trading Terminal
                    </span>
                </button>
            </div>
        </template>
    </div>
  </div>

  <!-- Trading Terminal Modal -->
  <div x-show="showTradingTerminal" style="display: none;" class="fixed inset-0 z-50 flex items-center justify-center modal-overlay p-4" x-transition>
    <div class="terminal-window rounded-[1.5rem] max-w-2xl w-full shadow-2xl max-h-[80vh] overflow-hidden relative flex flex-col" @click.away="showTradingTerminal = false">
        
        <!-- Terminal Header -->
        <div class="terminal-header px-6 py-4 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <div class="w-3 h-3 rounded-full bg-rose-500"></div>
                <div class="w-3 h-3 rounded-full bg-amber-500"></div>
                <div class="w-3 h-3 rounded-full bg-emerald-500"></div>
                <span class="ml-3 text-xs font-mono text-slate-400 uppercase tracking-widest" x-text="activeTerminalBot ? activeTerminalBot.name + &#39; v2.4.1&#39; : &#39;AI Terminal&#39;"></span>
            </div>
            <button @click="showTradingTerminal = false" class="text-slate-400 hover:text-white transition-colors">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>

        <!-- Terminal Body -->
        <div class="flex-1 p-6 overflow-y-auto font-mono text-sm">
            <!-- Progress Bar -->
            <div class="mb-4 h-1 bg-slate-800 rounded-full overflow-hidden">
                <div class="h-full bg-theme transition-all duration-300" :style="&#39;width: &#39; + tradingProgress + &#39;%&#39;"></div>
            </div>

            <!-- Status -->
            <div class="flex items-center gap-2 mb-4">
                <div class="w-2 h-2 rounded-full" :class="isTrading ? &#39;bg-emerald-500 animate-pulse&#39; : &#39;bg-slate-500&#39;"></div>
                <span class="text-xs text-slate-400 uppercase tracking-widest" x-text="isTrading ? &#39;AI EXECUTING TRADES...&#39; : &#39;TRADE COMPLETE&#39;"></span>
            </div>

            <!-- Logs -->
            <div class="space-y-1">
                <template x-for="(log, index) in terminalLogs" :key="index">
                    <div class="terminal-line flex gap-3 text-xs" :style="&#39;animation-delay: &#39; + (index * 0.05) + &#39;s&#39;">
                        <span class="text-slate-600 shrink-0" x-text="&#39;[&#39; + log.time + &#39;]&#39;"></span>
                        <span :class="log.type === &#39;profit&#39; ? &#39;text-emerald-400&#39; : log.type === &#39;trade&#39; ? &#39;text-theme&#39; : &#39;text-slate-300&#39;" x-text="log.message"></span>
                    </div>
                </template>
            </div>

            <!-- Cursor -->
            <div x-show="isTrading" class="flex items-center gap-2 mt-2">
                <span class="text-theme animate-pulse">_</span>
            </div>
        </div>

        <!-- Terminal Footer -->
        <div class="terminal-header px-6 py-3 flex justify-between items-center">
            <span class="text-[10px] text-slate-500 font-mono">NEURAL_NETWORK::ACTIVE | LATENCY: 12ms</span>
            <button x-show="!isTrading" @click="showTradingTerminal = false" 
                    class="px-4 py-1.5 rounded-lg bg-theme text-white text-xs font-bold uppercase tracking-widest hover:brightness-110 transition-all">
                Close Terminal
            </button>
        </div>
    </div>
  </div>

</div>

<?php if(file_exists('include/footer.php')) include "include/footer.php"; ?>

<script src="https://unpkg.com/lucide@latest"></script>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        lucide.createIcons();
        
        // Generate neural network background
        const svg = document.getElementById('neural-network');
        const width = 1920;
        const height = 1080;
        const nodes = [];
        const nodeCount = 30;
        
        for (let i = 0; i < nodeCount; i++) {
            nodes.push({
                x: Math.random() * width,
                y: Math.random() * height,
                r: Math.random() * 3 + 1
            });
        }
        
        // Draw connections
        nodes.forEach((node, i) => {
            nodes.forEach((other, j) => {
                if (i < j) {
                    const dist = Math.hypot(node.x - other.x, node.y - other.y);
                    if (dist < 300) {
                        const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
                        line.setAttribute('x1', node.x);
                        The response was cut off. Let me continue from where it stopped to complete the neural network background JavaScript and provide the remaining files.

---

## Continuation of `AItradingBot.php` — Complete the JavaScript section:

```javascript
                        line.setAttribute('y1', node.y);
                        line.setAttribute('x2', other.x);
                        line.setAttribute('y2', other.y);
                        line.setAttribute('class', 'neural-line');
                        line.style.animationDelay = `${Math.random() * 2}s`;
                        svg.appendChild(line);
                    }
                }
            });
        });
        
        // Draw nodes
        nodes.forEach(node => {
            const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
            circle.setAttribute('cx', node.x);
            circle.setAttribute('cy', node.y);
            circle.setAttribute('r', node.r);
            circle.setAttribute('fill', 'rgba(var(--primary-rgb), 0.6)');
            svg.appendChild(circle);
        });
    });
    
    document.addEventListener('alpine:initialized', () => {
        Alpine.effect(() => {
            setTimeout(() => { lucide.createIcons(); }, 50);
        });
    });
</script>

</body>
</html>