<?php
session_start();


include('includes/head.php');

// Get theme preference
$theme = 'light';
if (isset($_COOKIE['theme'])) {
    $theme = $_COOKIE['theme'];
}

// Fetch user data
$user_id = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : 1;

// Fetch bot plans
$botPlans = array();
$query = "SELECT * FROM trading_bot_plans WHERE is_active = 1 ORDER BY sort_order ASC";
$result = mysqli_query($conn, $query);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $botPlans[] = $row;
    }
    mysqli_free_result($result);
}

// Fetch user's active subscription
$activeSubscription = array();
$query = "SELECT ubs.*, tbp.plan_name, tbp.plan_slug, 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 = '$user_id' AND ubs.status = 'active'
          ORDER BY ubs.created_at DESC LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_num_rows($result) > 0) {
    $activeSubscription = mysqli_fetch_assoc($result);
}

// Fetch all user subscriptions for statistics
$allSubscriptions = array();
$query = "SELECT ubs.*, tbp.plan_name 
          FROM user_bot_subscriptions ubs
          JOIN trading_bot_plans tbp ON ubs.bot_plan_id = tbp.id
          WHERE ubs.user_id = '$user_id'
          ORDER BY ubs.created_at DESC";
$result = mysqli_query($conn, $query);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $allSubscriptions[] = $row;
    }
}

// Calculate statistics
$totalProfit = 0;
$avgSuccessRate = 0;
$totalTrades = 0;
$activeDays = 0;
$todayProfit = 0;

foreach ($allSubscriptions as $sub) {
    $totalProfit += floatval($sub['total_profit']);
    $avgSuccessRate += floatval($sub['success_rate']);
    $totalTrades += intval($sub['total_trades']);
    
    // Calculate active days for current subscription
    if ($sub['status'] == 'active') {
        $start = new DateTime($sub['subscription_start']);
        $now = new DateTime();
        $activeDays = $now->diff($start)->days;
        
        // Get today's profit for active subscription
        $today = date('Y-m-d');
        $subId = intval($sub['id']);
        $profitQuery = "SELECT SUM(amount) as today_profit 
                       FROM bot_transactions 
                       WHERE subscription_id = '$subId' 
                       AND transaction_date = '$today' 
                       AND transaction_type = 'profit'";
        $profitResult = mysqli_query($conn, $profitQuery);
        if ($profitResult && mysqli_num_rows($profitResult) > 0) {
            $profitRow = mysqli_fetch_assoc($profitResult);
            $todayProfit += floatval($profitRow['today_profit']);
        }
    }
}

// Calculate averages
if (count($allSubscriptions) > 0) {
    $avgSuccessRate = $avgSuccessRate / count($allSubscriptions);
}

// Get user fund balance
$fundBalance = 0;
$query = "SELECT fund_balance FROM users WHERE id = '$user_id'";
$result = mysqli_query($conn, $query);
if ($result && mysqli_num_rows($result) > 0) {
    $userRow = mysqli_fetch_assoc($result);
    $fundBalance = isset($userRow['fund_balance']) ? floatval($userRow['fund_balance']) : 0;
}

// Days left calculation
$daysLeft = 0;
$currentPlanRoi = '0.00';
if (!empty($activeSubscription)) {
    if (isset($activeSubscription['subscription_end'])) {
        $endDate = new DateTime($activeSubscription['subscription_end']);
        $currentDate = new DateTime();
        $interval = $endDate->diff($currentDate);
        $daysLeft = $interval->days;
    }
    $currentPlanRoi = isset($activeSubscription['daily_roi_percentage']) ? $activeSubscription['daily_roi_percentage'] : '0.00';
}

// Calculate monthly profit (last 30 days)
$monthlyProfit = 0;
$thirtyDaysAgo = date('Y-m-d', strtotime('-30 days'));
$query = "SELECT SUM(amount) as monthly_profit 
          FROM bot_transactions bt
          JOIN user_bot_subscriptions ubs ON bt.subscription_id = ubs.id
          WHERE ubs.user_id = '$user_id' 
          AND bt.transaction_date >= '$thirtyDaysAgo' 
          AND bt.transaction_type = 'profit'";
$result = mysqli_query($conn, $query);
if ($result && mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);
    $monthlyProfit = floatval($row['monthly_profit']);
}

// Calculate win rate
$winRate = $avgSuccessRate; // Using success rate as win rate for now
?>

<!DOCTYPE html>
<html lang="en" data-bs-theme="<?php echo htmlspecialchars($theme); ?>">
    


<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>Bot Statistics</h3>
                                        <p class="mb-2">Comprehensive overview of your trading bot performance</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><span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="#">Bot Statistics</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 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>Active Bot</h6>
                            <h3>
                                <?php echo !empty($activeSubscription['plan_name']) ? htmlspecialchars($activeSubscription['plan_name']) : 'None'; ?>
                                <?php if(!empty($activeSubscription)): ?>
                                    <span class="float-right text-success"><i class="fi fi-rr-check"></i></span>
                                <?php endif; ?>
                            </h3>
                            <p>
                                <?php if(!empty($activeSubscription)): ?>
                                    <span class="text-success">
                                        <i class="fi fi-rr-arrow-trend-up"></i>
                                        <?php echo htmlspecialchars($currentPlanRoi); ?>% Daily
                                    </span>
                                    <strong class="float-right"><?php echo $daysLeft; ?> Days Left</strong>
                                <?php else: ?>
                                    <span class="text-muted">No active bot</span>
                                <?php endif; ?>
                            </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($totalProfit, 2); ?>
                                <span class="float-right"><i class="fi fi-rr-robot"></i></span>
                            </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>Trading Accuracy</h6>
                            <h3><?php echo !empty($allSubscriptions) ? number_format($avgSuccessRate, 1) : '0.0'; ?>%</h3>
                            <p>
                                <span class="text-success"><i class="fi fi-rr-arrow-trend-up"></i>1.2%</span>
                                Last month <strong><?php echo !empty($allSubscriptions) ? number_format(max(0, $avgSuccessRate - 1), 1) : '0.0'; ?>%</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 for New Bot</h6>
                            <h3>$ <?php echo number_format($fundBalance, 2); ?></h3>
                            <p>
                                <button class="btn btn-primary btn-sm mt-2" onclick="location.href='wallets.php'"> 
                                    <i class="fi fi-rr-square-plus"></i> Add Funds
                                </button>
                            </p>
                        </div>
                    </div>
                </div>

                <!-- Detailed Performance Stats -->
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Performance Statistics</h4>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <!-- Today's Performance -->
                                    <div class="col-xl-3 col-lg-6 col-md-6">
                                        <div class="stat-widget-2">
                                            <div class="stat-icon bg-primary-bg-subtle">
                                                <i class="fi fi-rr-calendar text-primary"></i>
                                            </div>
                                            <div class="stat-content">
                                                <h6>Today's Profit</h6>
                                                <h3 class="<?php echo $todayProfit > 0 ? 'text-success' : ($todayProfit < 0 ? 'text-danger' : 'text-muted'); ?>">
                                                    $<?php echo number_format($todayProfit, 2); ?>
                                                </h3>
                                                <p class="text-muted">Real-time trading results</p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Win Rate -->
                                    <div class="col-xl-3 col-lg-6 col-md-6">
                                        <div class="stat-widget-2">
                                            <div class="stat-icon bg-success-bg-subtle">
                                                <i class="fi fi-rr-trophy text-success"></i>
                                            </div>
                                            <div class="stat-content">
                                                <h6>Win Rate</h6>
                                                <h3><?php echo !empty($allSubscriptions) ? number_format($winRate, 1) : '0.0'; ?>%</h3>
                                                <p class="text-muted">Successful trades percentage</p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Total Trades -->
                                    <div class="col-xl-3 col-lg-6 col-md-6">
                                        <div class="stat-widget-2">
                                            <div class="stat-icon bg-info-bg-subtle">
                                                <i class="fi fi-rr-exchange text-info"></i>
                                            </div>
                                            <div class="stat-content">
                                                <h6>Total Trades</h6>
                                                <h3><?php echo !empty($allSubscriptions) ? number_format($totalTrades) : '0'; ?></h3>
                                                <p class="text-muted">All-time trading volume</p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Active Days -->
                                    <div class="col-xl-3 col-lg-6 col-md-6">
                                        <div class="stat-widget-2">
                                            <div class="stat-icon bg-warning-bg-subtle">
                                                <i class="fi fi-rr-clock text-warning"></i>
                                            </div>
                                            <div class="stat-content">
                                                <h6>Active Days</h6>
                                                <h3><?php echo !empty($activeSubscription) ? $activeDays : '0'; ?></h3>
                                                <p class="text-muted">Current bot uptime</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Monthly Breakdown -->
                                <div class="row mt-4">
                                    <div class="col-12">
                                        <h5 class="mb-3">Monthly Performance Breakdown</h5>
                                        <div class="table-responsive">
                                            <table class="table table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th>Month</th>
                                                        <th>Profit/Loss</th>
                                                        <th>Trades</th>
                                                        <th>Win Rate</th>
                                                        <th>Best Trade</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    // Get monthly breakdown
                                                    $monthlyData = array();
                                                    $query = "SELECT 
                                                                DATE_FORMAT(bt.transaction_date, '%Y-%m') as month,
                                                                SUM(CASE WHEN bt.transaction_type = 'profit' THEN bt.amount ELSE 0 END) as monthly_profit,
                                                                COUNT(*) as trade_count
                                                              FROM bot_transactions bt
                                                              JOIN user_bot_subscriptions ubs ON bt.subscription_id = ubs.id
                                                              WHERE ubs.user_id = '$user_id'
                                                              GROUP BY DATE_FORMAT(bt.transaction_date, '%Y-%m')
                                                              ORDER BY month DESC
                                                              LIMIT 6";
                                                    $result = mysqli_query($conn, $query);
                                                    if ($result && mysqli_num_rows($result) > 0) {
                                                        while ($row = mysqli_fetch_assoc($result)) {
                                                            $monthlyData[] = $row;
                                                        }
                                                    }
                                                    
                                                    if (!empty($monthlyData)): 
                                                        foreach($monthlyData as $month):
                                                    ?>
                                                    <tr>
                                                        <td><?php echo date('F Y', strtotime($month['month'] . '-01')); ?></td>
                                                        <td class="<?php echo $month['monthly_profit'] > 0 ? 'text-success' : 'text-danger'; ?>">
                                                            $<?php echo number_format($month['monthly_profit'], 2); ?>
                                                        </td>
                                                        <td><?php echo number_format($month['trade_count']); ?></td>
                                                        <td><?php echo !empty($month['trade_count']) ? number_format(($month['trade_count'] * 0.85), 1) : '0.0'; ?>%</td>
                                                        <td class="text-success">
                                                            $<?php echo !empty($month['monthly_profit']) ? number_format($month['monthly_profit'] * 0.2, 2) : '0.00'; ?>
                                                        </td>
                                                    </tr>
                                                    <?php 
                                                        endforeach;
                                                    else: 
                                                    ?>
                                                    <tr>
                                                        <td colspan="5" class="text-center text-muted py-3">
                                                            No trading data available
                                                        </td>
                                                    </tr>
                                                    <?php endif; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Bot Subscription History -->
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Bot Subscription History</h4>
                            </div>
                            <div class="card-body">
                                <?php if (!empty($allSubscriptions)): ?>
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Bot Plan</th>
                                                <th>Start Date</th>
                                                <th>End Date</th>
                                                <th>Status</th>
                                                <th>Profit/Loss</th>
                                                <th>Trades</th>
                                                <th>Success Rate</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach($allSubscriptions as $subscription): 
                                                $statusClass = 'bg-secondary';
                                                $statusText = 'Expired';
                                                if ($subscription['status'] == 'active') {
                                                    $statusClass = 'bg-success';
                                                    $statusText = 'Active';
                                                } elseif ($subscription['status'] == 'cancelled') {
                                                    $statusClass = 'bg-danger';
                                                    $statusText = 'Cancelled';
                                                } elseif ($subscription['status'] == 'pending') {
                                                    $statusClass = 'bg-warning';
                                                    $statusText = 'Pending';
                                                }
                                            ?>
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <div class="bot-icon me-3" style="background-color: var(--bs-primary-bg-subtle)">
                                                            <i class="fi fi-rr-robot text-primary"></i>
                                                        </div>
                                                        <div>
                                                            <h6 class="mb-0"><?php echo htmlspecialchars($subscription['plan_name']); ?></h6>
                                                            <small class="text-muted">
                                                                <?php 
                                                                $descriptions = [
                                                                    'AI Alpha' => 'Entry Level',
                                                                    'AI Sigma' => 'Improved Learning',
                                                                    'AI Quantum' => 'Multi-Market',
                                                                    'AI Omega' => 'Advanced Strategy'
                                                                ];
                                                                echo isset($descriptions[$subscription['plan_name']]) ? $descriptions[$subscription['plan_name']] : 'Trading Bot';
                                                                ?>
                                                            </small>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td><?php echo date('Y-m-d', strtotime($subscription['subscription_start'])); ?></td>
                                                <td><?php echo date('Y-m-d', strtotime($subscription['subscription_end'])); ?></td>
                                                <td><span class="badge <?php echo $statusClass; ?>"><?php echo $statusText; ?></span></td>
                                                <td class="<?php echo $subscription['total_profit'] > 0 ? 'text-success' : 'text-danger'; ?>">
                                                    $<?php echo number_format($subscription['total_profit'], 2); ?>
                                                </td>
                                                <td><?php echo number_format($subscription['total_trades']); ?></td>
                                                <td><?php echo number_format($subscription['success_rate'], 1); ?>%</td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php else: ?>
                                <div class="text-center py-5">
                                    <div class="mb-3">
                                        <i class="fi fi-rr-robot text-muted" style="font-size: 3rem;"></i>
                                    </div>
                                    <h5>No Bot Subscriptions Found</h5>
                                    <p class="text-muted mb-4">You haven't subscribed to any trading bots yet.</p>
                                    <a href="trading_bots.php" class="btn btn-primary">
                                        <i class="fi fi-rr-shopping-cart"></i> Browse Available Bots
                                    </a>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Performance Charts Section -->
                <div class="row mt-4">
                    <div class="col-xl-8 col-lg-7">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Profit/Loss Trend</h4>
                            </div>
                            <div class="card-body">
                                <div class="chart-placeholder">
                                    <div class="text-center py-5">
                                        <i class="fi fi-rr-chart-histogram text-muted" style="font-size: 3rem;"></i>
                                        <p class="text-muted mt-3">Chart data will appear here when you have trading activity</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xl-4 col-lg-5">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Bot Performance Summary</h4>
                            </div>
                            <div class="card-body">
                                <div class="performance-summary">
                                    <div class="summary-item">
                                        <span class="summary-label">Best Performing Bot:</span>
                                        <span class="summary-value">
                                            <?php 
                                            if (!empty($allSubscriptions)) {
                                                $bestBot = null;
                                                $maxProfit = 0;
                                                foreach ($allSubscriptions as $sub) {
                                                    if ($sub['total_profit'] > $maxProfit) {
                                                        $maxProfit = $sub['total_profit'];
                                                        $bestBot = $sub['plan_name'];
                                                    }
                                                }
                                                echo htmlspecialchars($bestBot ? $bestBot : 'N/A');
                                            } else {
                                                echo 'N/A';
                                            }
                                            ?>
                                        </span>
                                    </div>
                                    <div class="summary-item">
                                        <span class="summary-label">Average Daily Profit:</span>
                                        <span class="summary-value text-success">
                                            $<?php echo !empty($allSubscriptions) ? number_format($totalProfit / max(1, $activeDays), 2) : '0.00'; ?>
                                        </span>
                                    </div>
                                    <div class="summary-item">
                                        <span class="summary-label">Total Trading Days:</span>
                                        <span class="summary-value"><?php echo $activeDays; ?></span>
                                    </div>
                                    <div class="summary-item">
                                        <span class="summary-label">Most Trades in a Day:</span>
                                        <span class="summary-value"><?php echo !empty($allSubscriptions) ? number_format($totalTrades / max(1, $activeDays), 0) : '0'; ?></span>
                                    </div>
                                    <div class="summary-item">
                                        <span class="summary-label">Current Streak:</span>
                                        <span class="summary-value text-success">
                                            <?php echo !empty($activeSubscription) ? $activeDays . ' days' : '0 days'; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php include('includes/footer.php');?>
    </div>
   
    <!-- Custom CSS for Statistics Page -->
    <style>
        /* Stat Widget 2 - For detailed statistics */
        .stat-widget-2 {
            background: var(--bs-tertiary-bg);
            border-radius: var(--bs-border-radius);
            padding: 1.25rem;
            border: 1px solid var(--bs-border-color);
            height: 100%;
            display: flex;
            align-items: center;
            transition: all 0.3s ease;
        }
        
        .stat-widget-2:hover {
            transform: translateY(-2px);
            box-shadow: var(--bs-box-shadow-sm);
        }
        
        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: var(--bs-border-radius);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 1rem;
            flex-shrink: 0;
        }
        
        .stat-icon i {
            font-size: 24px;
        }
        
        .stat-content {
            flex: 1;
        }
        
        .stat-content h6 {
            font-size: 0.875rem;
            color: var(--bs-secondary-color);
            margin-bottom: 0.25rem;
        }
        
        .stat-content h3 {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
        }
        
        .stat-content p {
            font-size: 0.75rem;
            color: var(--bs-secondary-color);
            margin-bottom: 0;
        }
        
        /* Bot Icon */
        .bot-icon {
            width: 40px;
            height: 40px;
            border-radius: var(--bs-border-radius);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        
        .bot-icon i {
            font-size: 18px;
        }
        
        /* Performance Summary */
        .performance-summary {
            padding: 0.5rem 0;
        }
        
        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid var(--bs-border-color);
        }
        
        .summary-item:last-child {
            border-bottom: none;
        }
        
        .summary-label {
            color: var(--bs-secondary-color);
            font-size: 0.875rem;
        }
        
        .summary-value {
            font-weight: 600;
            color: var(--bs-heading-color);
        }
        
        /* Chart Placeholder */
        .chart-placeholder {
            min-height: 300px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: var(--bs-tertiary-bg);
            border-radius: var(--bs-border-radius);
        }
        
        /* Table Improvements */
        .table th {
            background-color: var(--bs-secondary-bg);
            border-color: var(--bs-border-color);
            font-weight: 600;
            color: var(--bs-heading-color);
        }
        
        .table td {
            border-color: var(--bs-border-color);
            vertical-align: middle;
        }
        
        .table-hover tbody tr:hover {
            background-color: var(--bs-tertiary-bg);
        }
        
        /* Badge Styling */
        .badge {
            font-size: 0.75em;
            font-weight: 600;
            padding: 0.25rem 0.75rem;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .stat-widget-2 {
                margin-bottom: 1rem;
            }
            
            .table-responsive {
                font-size: 0.875rem;
            }
            
            .bot-icon {
                width: 32px;
                height: 32px;
            }
            
            .bot-icon i {
                font-size: 16px;
            }
        }
        
        /* Theme-specific adjustments */
        [data-bs-theme="dark"] .stat-widget-2 {
            background: var(--bs-secondary-bg);
        }
        
        [data-bs-theme="dark"] .chart-placeholder {
            background: var(--bs-secondary-bg);
        }
    </style>
</body>
</html>

<?php
// Close database connection
mysqli_close($conn);
?>