<?php session_start();

?>
<!DOCTYPE html>
<html lang="en" data-bs-theme="<?php echo isset($_COOKIE['theme']) ? $_COOKIE['theme'] : 'light'; ?>">
    
<?php include('includes/head.php');?>

<body class="dashboard">
    <div id="preloader" class="preloader-wrapper">
        <div class="loader">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <div id="main-wrapper">
        <?php include('includes/header.php');?>
        <?php include('includes/sidebar.php');?>
        <div class="content-body">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title">
                            <div class="row align-items-center justify-content-between">
                                <div class="col-xl-4">
                                    <div class="page-title-content">
                                        <h3>Dashboard</h3>
                                        <p class="mb-2">Welcome <?php echo htmlspecialchars($userFirstName .' '. $userLastName);?></p>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <div class="breadcrumbs"><a href="#">Home </a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="#">Dashboard</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ($userVerified == 0) { ?>
                    <div class="col-md-6">
                        <div class="card border-warning shadow-sm mb-3">
                            <div class="card-body bg-warning">
                                <div class="row align-items-center">
                                    <!-- Icon column - hidden on mobile, visible on desktop -->
                                    <div class="col-auto d-none d-md-block">
                                        <div class="icon-circle bg-danger ">
                                            <i class="fas fa-user-clock text-white fa-lg"></i>
                                        </div>
                                    </div>
                                    
                                    <!-- Content column -->
                                    <div class="col-md-8 col-12">
                                        <div class="d-flex align-items-center mb-2">
                                            <!-- Mobile icon - visible only on mobile -->
                                            <div class="d-md-none me-2">
                                                <i class="fas fa-user-clock text-white fa-lg"></i>
                                            </div>
                                            <div>
                                                <span class="badge bg-danger text-dark mb-1">VERIFICATION REQUIRED</span>
                                                <h6 class="mb-0 fw-bold">Complete KYC Verification</h6>
                                                <p class="text-muted small mb-2 mt-1">Verify your identity to access withdrawals and all trading features.</p>
                                            </div>
                                        </div>
                                        <div class="d-flex flex-wrap align-items-center gap-2">
                                            <a href="kyc-verification.php" class="btn btn-primary btn-sm">
                                                <i class="fas fa-id-card-alt me-1"></i> Verify Now
                                            </a>
                                            <small class="text-muted">
                                                <i class="fas fa-lock me-1"></i>Secure process
                                            </small>
                                        </div>
                                    </div>
                                    
                                    <!-- Badges column - stack on mobile -->
                                    <div class="col-md-12 col-12 mt-3 mt-md-0">
                                        <div class="text-md-end">
                                            <div class="small text-muted mb-1 d-none d-md-block">Unlocks:</div>
                                            <div class="d-flex flex-wrap gap-1 justify-content-start justify-content-md-end">
                                                <span class="badge bg-light text-dark border">Withdrawals</span>
                                                <span class="badge bg-light text-dark border">Trading Limits</span>
                                                <span class="badge bg-light text-dark border mt-1 mt-md-0">All Features</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php } ?>
                
                <?php  
                // Fetch bot statistics from database
                // 1. Get active bot subscription
                $activeBot = null;
                $activeBotName = "None";
                $activeBotRoi = "0.00%";
                $daysLeft = 0;
                $botStatus = "INACTIVE";
                
                $botQuery = "SELECT ubs.*, tbp.plan_name, tbp.daily_roi_percentage 
                            FROM user_bot_subscriptions ubs
                            JOIN trading_bot_plans tbp ON ubs.bot_plan_id = tbp.id
                            WHERE ubs.user_id = '$userID' AND ubs.status = 'active'
                            ORDER BY ubs.created_at DESC LIMIT 1";
                $botResult = mysqli_query($conn, $botQuery);
                if ($botResult && mysqli_num_rows($botResult) > 0) {
                    $activeBot = mysqli_fetch_assoc($botResult);
                    $activeBotName = $activeBot['plan_name'];
                    $activeBotRoi = $activeBot['daily_roi_percentage'] . "%";
                    $botStatus = "ACTIVE";
                    
                    // Calculate days left
                    $endDate = new DateTime($activeBot['subscription_end']);
                    $currentDate = new DateTime();
                    $interval = $endDate->diff($currentDate);
                    $daysLeft = $interval->days;
                }
                
                // 2. Get total bot profit from all subscriptions
                $totalBotProfit = 0;
                $totalQuery = "SELECT COALESCE(SUM(total_profit), 0) as total_bot_profit 
                              FROM user_bot_subscriptions 
                              WHERE user_id = '$userID'";
                $totalResult = mysqli_query($conn, $totalQuery);
                if ($totalResult && mysqli_num_rows($totalResult) > 0) {
                    $totalRow = mysqli_fetch_assoc($totalResult);
                    $totalBotProfit = $totalRow['total_bot_profit'];
                }
                
                // 3. Get average success rate
                $avgSuccessRate = 0;
                $successQuery = "SELECT COALESCE(AVG(success_rate), 0) as avg_success 
                                FROM user_bot_subscriptions 
                                WHERE user_id = '$userID'";
                $successResult = mysqli_query($conn, $successQuery);
                if ($successResult && mysqli_num_rows($successResult) > 0) {
                    $successRow = mysqli_fetch_assoc($successResult);
                    $avgSuccessRate = $successRow['avg_success'];
                }
                
                // 4. Get today's profit for active bot
                $todayProfit = 0;
                if ($activeBot) {
                    $today = date('Y-m-d');
                    $todayQuery = "SELECT COALESCE(SUM(amount), 0) as today_profit 
                                  FROM bot_transactions 
                                  WHERE subscription_id = '{$activeBot['id']}' 
                                  AND transaction_date = '$today' 
                                  AND transaction_type = 'profit'";
                    $todayResult = mysqli_query($conn, $todayQuery);
                    if ($todayResult && mysqli_num_rows($todayResult) > 0) {
                        $todayRow = mysqli_fetch_assoc($todayResult);
                        $todayProfit = $todayRow['today_profit'];
                    }
                }
                
                // 5. Calculate monthly profit (last 30 days)
                $monthlyProfit = 0;
                $thirtyDaysAgo = date('Y-m-d', strtotime('-30 days'));
                $monthlyQuery = "SELECT COALESCE(SUM(bt.amount), 0) as monthly_profit 
                                FROM bot_transactions bt
                                JOIN user_bot_subscriptions ubs ON bt.subscription_id = ubs.id
                                WHERE ubs.user_id = '$userID' 
                                AND bt.transaction_date >= '$thirtyDaysAgo' 
                                AND bt.transaction_type = 'profit'";
                $monthlyResult = mysqli_query($conn, $monthlyQuery);
                if ($monthlyResult && mysqli_num_rows($monthlyResult) > 0) {
                    $monthlyRow = mysqli_fetch_assoc($monthlyResult);
                    $monthlyProfit = $monthlyRow['monthly_profit'];
                }
                ?>
                
                <!-- Bot Stats Summary -->
                <div class="row">
                    <div class="col-xl-3 col-lg-6 col-md-6 col-sm-6">
                        <div class="stat-widget-1">
                            <h6>Fund Balance <span style="float: right"> 
                                <img src="https://cryptologos.cc/logos/tether-usdt-logo.svg?v=035" width="24" alt="USDT">
                            </span></h6>
                            <h3>$ <?php echo number_format($fundBalance, 2);?> 
                                <span style="float: right; color: #F97316;">
                                    <?php if ($funds_locked == 1) { ?>
                                        <i class="fi fi-rr-lock"></i>
                                    <?php } ?>
                                </span>
                            </h3>
                            <p>
                                <a href="wallets.php" class="btn btn-primary"> 
                                    <i class="fi fi-rr-square-plus"></i> Add Fund
                                </a>
                            </p>
                        </div>
                    </div>
                    <div class="col-xl-3 col-lg-6 col-md-6 col-sm-6">
                        <div class="stat-widget-1">
                            <h6>Total Bot Profit</h6>
                            <h3>$ <?php echo number_format($totalBotProfit, 2);?>
                                <span style="float: right">
                                    <i class="fi fi-rr-wallet"></i>
                                </span>
                            </h3>
                            <p>
                                <span class="text-success">
                                    <i class="fi fi-rr-arrow-trend-up"></i>
                                    <?php echo $monthlyProfit > 0 ? number_format(($monthlyProfit / max(1, $totalBotProfit - $monthlyProfit)) * 100, 2) : '0.00'; ?>%
                                </span>
                                Last month <strong>$<?php echo number_format($monthlyProfit, 2); ?></strong>
                            </p>
                        </div>
                    </div>
                    <div class="col-xl-3 col-lg-6 col-md-6 col-sm-6">
                        <div class="stat-widget-1">
                            <h6>Available Balance</h6>
                            <h3>$ <?php echo number_format($availableBalance, 2);?></h3>
                            <p>
                                <span class="text-success">
                                    <i class="fi fi-rr-arrow-trend-up"></i>2.47%
                                </span>
                                Last month <strong>$<?php echo number_format($monthlyProfit, 2); ?></strong>
                            </p>
                        </div>
                    </div>
                    <div class="col-xl-3 col-lg-6 col-md-6 col-sm-6">
                        <div class="stat-widget-1">
                            <h6>AI Trading Bot 
                                <span class="text-<?php echo $botStatus == 'ACTIVE' ? 'success' : 'danger'; ?>" style="float: right;">
                                    <?php echo $botStatus; ?>
                                </span>
                            </h6>
                            <h3 style="color: <?php echo $botStatus == 'ACTIVE' ? '#DC2626' : '#6B7280'; ?>">
                                <?php echo $activeBotName; ?>
                            </h3>
                            <p>
                                <?php if($botStatus == 'ACTIVE'): ?>
                                    <span class="text-success">
                                        <i class="fi fi-rr-arrow-trend-up"></i>
                                        <?php echo $activeBotRoi; ?>
                                    </span>
                                    <strong style="float: right;"><?php echo $daysLeft; ?> Days Left</strong>
                                <?php else: ?>
                                    <span class="text-muted">No active bot</span>
                                    <a href="trading_bots.php" style="float: right;" class="btn btn-sm btn-primary">
                                        <i class="fi fi-rr-robot"></i> Get Started
                                    </a>
                                <?php endif; ?>
                            </p>
                        </div>
                    </div>
                </div>

                <!-- Active Bot Details (Only show if bot is active) -->
                <?php if($botStatus == 'ACTIVE' && $activeBot): ?>
                <h3>Active Bot Details</h3>
                <div class="row g-4">
                    <!-- Daily Rate -->
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <p class="mb-1">Daily Rate</p>
                                        <h3 class="fw-bold mb-1">
                                            <i class="fi fi-rr-arrow-up-right"></i>
                                            <?php echo $activeBotRoi; ?>
                                        </h3>
                                        <div class="d-flex align-items-center gap-2">
                                            <span class="badge bg-transparent text-dark border d-flex align-items-center px-2 py-1">
                                                <!-- Badge content if needed -->
                                            </span>
                                            <span class="small text-muted">fixed</span>
                                        </div>
                                    </div>
                                    <div class="p-2 bg-primary bg-opacity-25 rounded-circle">
                                        <i class="fi fi-rr-arrow-trend-up"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Daily Expected Interest -->
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <p class="mb-1">Today's Profit</p>
                                        <h3 class="fw-bold mb-1">
                                            <?php if($todayProfit > 0): ?>
                                                <span class="text-success">+$<?php echo number_format($todayProfit, 2); ?></span>
                                            <?php elseif($todayProfit < 0): ?>
                                                <span class="text-danger">-$<?php echo number_format(abs($todayProfit), 2); ?></span>
                                            <?php else: ?>
                                                $<?php echo number_format($todayProfit, 2); ?>
                                            <?php endif; ?>
                                        </h3>
                                        <div class="d-flex align-items-center gap-2">
                                            <span class="badge bg-transparent text-dark border d-flex align-items-center px-2 py-1">
                                                <i class="fi fi-rr-arrow-up-right me-2"></i>
                                            </span>
                                            <span class="small text-muted">updated <?php echo date('H:i'); ?></span>
                                        </div>
                                    </div>
                                    <div class="p-2 bg-primary bg-opacity-25 rounded-circle">
                                        <i class="fi fi-rr-arrow-trend-<?php echo $todayProfit > 0 ? 'up' : 'down'; ?>"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Trading Accuracy -->
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <p class="mb-1">Trading Accuracy</p>
                                        <h3 class="fw-bold mb-1"><?php echo number_format($avgSuccessRate, 1); ?>%</h3>
                                        <div class="d-flex align-items-center gap-2">
                                            <span class="badge bg-transparent text-dark border d-flex align-items-center px-2 py-1">
                                                <i class="fi fi-rr-arrow-up-right me-2"></i>
                                            </span>
                                            <span class="small text-muted">overall</span>
                                        </div>
                                    </div>
                                    <div class="p-2 bg-primary bg-opacity-25 rounded-circle">
                                        <i class="fi fi-rr-wallet"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <!-- No Active Bot Message -->
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body text-center py-5">
                                <div class="mb-3">
                                    <i class="fi fi-rr-robot text-muted" style="font-size: 3rem;"></i>
                                </div>
                                <h4>No Active Trading Bot</h4>
                                <p class="text-muted mb-4">You don't have an active trading bot. Subscribe to start automated trading.</p>
                                <a href="trading_bots.php" class="btn btn-primary btn-lg">
                                    <i class="fi fi-rr-shopping-cart"></i> Browse Trading Bots
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Trading Charts and Analytics -->
                <div class="row mt-4">
                    <div class="col-xxl-8 col-xl-8 col-lg-6">
                        <div class="card">
                            <div class="card-header balance-trend">
                                <h4 class="card-title">Trading History 
                                    <br> 
                                    <span>$<?php echo number_format($totalBotProfit, 2); ?></span>
                                </h4>
                                <div class="trend-stats">
                                    <p class="mb-0">Last Month</p>
                                    <span class="text-success">
                                        <i class="fi fi-rr-arrow-trend-up"></i>
                                        <?php echo $monthlyProfit > 0 ? number_format(($monthlyProfit / max(1, $totalBotProfit - $monthlyProfit)) * 100, 2) : '0.00'; ?>%
                                    </span>
                                </div>
                            </div>
                            <div class="card-body">
                                <canvas id="profileWallet"></canvas>
                            </div>
                        </div>
                    </div>
                    <div class="col-xxl-4 col-xl-4 col-lg-6 col-md-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Bot Performance Breakdown</h4>
                            </div>
                            <div class="card-body">
                                <div class="progress-stacked">
                                    <?php
                                    // Get performance breakdown for active bot
                                    if($activeBot) {
                                        $successRate = $avgSuccessRate;
                                        $neutralRate = 100 - $successRate - 5;
                                        $lossRate = 5;
                                    } else {
                                        $successRate = 0;
                                        $neutralRate = 0;
                                        $lossRate = 0;
                                    }
                                    ?>
                                    <div class="progress" style="width: <?php echo $successRate; ?>%">
                                        <div class="progress-bar bg-success"></div>
                                    </div>
                                    <div class="progress" style="width: <?php echo $neutralRate; ?>%">
                                        <div class="progress-bar bg-warning"></div>
                                    </div>
                                    <div class="progress" style="width: <?php echo $lossRate; ?>%">
                                        <div class="progress-bar bg-danger"></div>
                                    </div>
                                </div>
                                <div class="list-1 mt-3">
                                    <ul>
                                        <li>
                                            <p class="mb-0"><i class="fi fi-rr-circle text-success"></i> Profitable Trades</p>
                                            <h5 class="mb-0"><span><?php echo number_format($successRate, 1); ?>%</span>Success Rate</h5>
                                        </li>
                                        <li>
                                            <p class="mb-0"><i class="fi fi-rr-circle text-warning"></i> Break-even</p>
                                            <h5 class="mb-0"><span><?php echo number_format($neutralRate, 1); ?>%</span>Neutral</h5>
                                        </li>
                                        <li>
                                            <p class="mb-0"><i class="fi fi-rr-circle text-danger"></i> Loss Trades</p>
                                            <h5 class="mb-0"><span><?php echo number_format($lossRate, 1); ?>%</span>Minimal Loss</h5>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Recent Transactions -->
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Recent Bot Transactions</h4>
                                <a href="transactions.php">See more</a>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table mb-0 table-responsive-sm">
                                        <thead>
                                            <tr>
                                                <th>Date</th>
                                                <th>Description</th>
                                                <th>Bot</th>
                                                <th>Type</th>
                                                <th>Amount</th>
                                                <th>Status</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            // Get recent bot transactions
                                            $transQuery = "SELECT bt.*, tbp.plan_name 
                                                         FROM bot_transactions bt
                                                         JOIN user_bot_subscriptions ubs ON bt.subscription_id = ubs.id
                                                         JOIN trading_bot_plans tbp ON ubs.bot_plan_id = tbp.id
                                                         WHERE ubs.user_id = '$userID'
                                                         ORDER BY bt.transaction_date DESC, bt.created_at DESC 
                                                         LIMIT 5";
                                            $transResult = mysqli_query($conn, $transQuery);
                                            if ($transResult && mysqli_num_rows($transResult) > 0) {
                                                while ($trans = mysqli_fetch_assoc($transResult)) {
                                                    $statusClass = 'bg-success';
                                                    $statusText = 'Completed';
                                                    if ($trans['transaction_type'] == 'loss') {
                                                        $statusClass = 'bg-danger';
                                                        $statusText = 'Loss';
                                                    } elseif ($trans['transaction_type'] == 'fee') {
                                                        $statusClass = 'bg-warning';
                                                        $statusText = 'Fee';
                                                    }
                                            ?>
                                            <tr>
                                                <td><?php echo date('Y-m-d', strtotime($trans['transaction_date'])); ?></td>
                                                <td><?php echo htmlspecialchars($trans['description']); ?></td>
                                                <td>
                                                    <span class="badge bg-primary"><?php echo htmlspecialchars($trans['plan_name']); ?></span>
                                                </td>
                                                <td>
                                                    <span class="badge <?php echo $statusClass; ?>"><?php echo $statusText; ?></span>
                                                </td>
                                                <td class="<?php echo $trans['transaction_type'] == 'profit' ? 'text-success' : ($trans['transaction_type'] == 'loss' ? 'text-danger' : 'text-warning'); ?>">
                                                    <?php echo $trans['transaction_type'] == 'profit' ? '+' : ($trans['transaction_type'] == 'loss' ? '-' : ''); ?>
                                                    $<?php echo number_format($trans['amount'], 2); ?>
                                                </td>
                                                <td><span class="badge bg-success">Completed</span></td>
                                            </tr>
                                            <?php
                                                }
                                            } else {
                                            ?>
                                            <tr>
                                                <td colspan="6" class="text-center py-4">
                                                    <div class="text-muted">
                                                        <i class="fi fi-rr-document-signed text-muted mb-2" style="font-size: 2rem;"></i>
                                                        <p>No bot transactions found</p>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php
                                            }
                                            ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div class="row mt-4">
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body text-center">
                                <div class="mb-3">
                                    <i class="fi fi-rr-robot text-primary" style="font-size: 2.5rem;"></i>
                                </div>
                                <h5>Manage Bots</h5>
                                <p class="text-muted">View, upgrade or cancel your bot subscriptions</p>
                                <a href="trading_bots.php" class="btn btn-outline-primary">
                                    <i class="fi fi-rr-settings"></i> Manage
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body text-center">
                                <div class="mb-3">
                                    <i class="fi fi-rr-chart-histogram text-success" style="font-size: 2.5rem;"></i>
                                </div>
                                <h5>View Reports</h5>
                                <p class="text-muted">Detailed performance reports and analytics</p>
                                <a href="bot-statistics.php" class="btn btn-outline-success">
                                    <i class="fi fi-rr-chart-pie-alt"></i> View Reports
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body text-center">
                                <div class="mb-3">
                                    <i class="fi fi-rr-square-plus text-info" style="font-size: 2.5rem;"></i>
                                </div>
                                <h5>Add Funds</h5>
                                <p class="text-muted">Deposit funds to trade with higher amounts</p>
                                <button class="btn btn-outline-info">
                                    <i class="fi fi-rr-credit-card"></i> Add Funds
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php include('includes/footer.php');?>
    </div>
   
    <!-- Chart.js Script -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Trading History Chart
        const ctx = document.getElementById('profileWallet').getContext('2d');
        
        // Sample data - you would replace this with actual data from PHP
        const tradingHistoryChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                datasets: [{
                    label: 'Bot Profit',
                    data: [
                        <?php echo number_format($monthlyProfit * 0.2, 0); ?>,
                        <?php echo number_format($monthlyProfit * 0.4, 0); ?>,
                        <?php echo number_format($monthlyProfit * 0.6, 0); ?>,
                        <?php echo number_format($monthlyProfit * 0.8, 0); ?>,
                        <?php echo number_format($monthlyProfit, 0); ?>,
                        <?php echo number_format($totalBotProfit, 0); ?>
                    ],
                    borderColor: 'rgb(59, 130, 246)',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.1)'
                        },
                        ticks: {
                            callback: function(value) {
                                return '$' + value;
                            }
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
        
        // Auto-refresh data every 30 seconds if bot is active
        <?php if($botStatus == 'ACTIVE'): ?>
        setInterval(function() {
            // You could add AJAX call here to refresh bot stats
            console.log('Bot stats refresh interval');
        }, 30000);
        <?php endif; ?>
    });
    </script>
</body>
</html>