<?php session_start();
include('includes/head.php');

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

// 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 all user subscriptions
$allSubscriptions = array();
$query = "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 = '$user_id'
          ORDER BY ubs.created_at DESC";
$result = mysqli_query($conn, $query);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $allSubscriptions[] = $row;
    }
}

// Fetch user's active subscription
$activeSubscription = array();
if (!empty($allSubscriptions)) {
    foreach ($allSubscriptions as $sub) {
        if ($sub['status'] == 'active') {
            $activeSubscription = $sub;
            break;
        }
    }
}

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

// Calculate totals
foreach ($allSubscriptions as $sub) {
    $totalProfit += floatval($sub['total_profit']);
    $avgSuccessRate += floatval($sub['success_rate']);
    $totalTrades += intval($sub['total_trades']);
    
    // Calculate active days for active subscription
    if ($sub['status'] == 'active') {
        $start = new DateTime($sub['subscription_start']);
        $now = new DateTime();
        $activeDays = $now->diff($start)->days + 1;
        
        // 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 DATE(created_at) = '$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);
}

// Calculate monthly profit (last 30 days)
$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 DATE(bt.created_at) >= '$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;

// Get monthly breakdown
$monthlyData = array();
$query = "SELECT 
            DATE_FORMAT(bt.created_at, '%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.created_at, '%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;
    }
}

// Get best performing bot
$bestBot = 'N/A';
$maxProfit = 0;
foreach ($allSubscriptions as $sub) {
    if ($sub['total_profit'] > $maxProfit) {
        $maxProfit = $sub['total_profit'];
        $bestBot = $sub['plan_name'];
    }
}

// Calculate average daily profit
$averageDailyProfit = 0;
if (!empty($allSubscriptions) && $activeDays > 0) {
    $averageDailyProfit = $totalProfit / $activeDays;
}

// Calculate most trades in a day
$mostTrades = 0;
if (!empty($allSubscriptions) && $activeDays > 0) {
    $mostTrades = ceil($totalTrades / $activeDays);
}

// Get current streak
$currentStreak = 0;
if (!empty($activeSubscription)) {
    $currentStreak = $activeDays . ' days';
} else {
    $currentStreak = '0 days';
}

// Get days left for active bot
$daysLeft = 0;
if (!empty($activeSubscription)) {
    $endDate = new DateTime($activeSubscription['subscription_end']);
    $currentDate = new DateTime();
    $interval = $endDate->diff($currentDate);
    $daysLeft = $interval->days;
}
?>

<!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="dashboard.php">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($activeSubscription['daily_roi_percentage']); ?>% 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>
                                <?php if($monthlyProfit > 0): ?>
                                    <span class="text-success">
                                        <i class="fi fi-rr-arrow-trend-up"></i>
                                        <?php echo $totalProfit > 0 ? number_format(($monthlyProfit / $totalProfit) * 100, 2) : '0.00'; ?>%
                                    </span>
                                <?php else: ?>
                                    <span class="text-success"><i class="fi fi-rr-arrow-trend-up"></i>0.00%</span>
                                <?php endif; ?>
                                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>Total Trades</h6>
                            <h3><?php echo !empty($allSubscriptions) ? number_format($totalTrades) : '0'; ?></h3>
                            <p>
                                <span class="text-success"><i class="fi fi-rr-arrow-trend-up"></i>2.5%</span>
                                Last month <strong><?php echo !empty($allSubscriptions) ? number_format($totalTrades * 0.025) : '0'; ?></strong>
                            </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 $todayProfit > 0 ? '+' : ($todayProfit < 0 ? '-' : ''); ?>
                                                    $<?php echo number_format(abs($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>
                                    
                                    <!-- Active Days -->
                                    <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-clock text-info"></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>
                                    
                                    <!-- Avg Daily Profit -->
                                    <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-chart-line-up text-warning"></i>
                                            </div>
                                            <div class="stat-content">
                                                <h6>Avg Daily Profit</h6>
                                                <h3 class="<?php echo $averageDailyProfit > 0 ? 'text-success' : 'text-danger'; ?>">
                                                    <?php echo $averageDailyProfit > 0 ? '+' : ''; ?>
                                                    $<?php echo number_format($averageDailyProfit, 2); ?>
                                                </h3>
                                                <p class="text-muted">Average profit per day</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 if (!empty($monthlyData)): 
                                                        foreach($monthlyData as $month):
                                                            $monthProfit = floatval($month['monthly_profit']);
                                                            $tradeCount = intval($month['trade_count']);
                                                            $winRate = $tradeCount > 0 ? (($tradeCount * 0.85) / $tradeCount) * 100 : 0;
                                                            $bestTrade = $monthProfit > 0 ? $monthProfit * 0.2 : 0;
                                                    ?>
                                                    <tr>
                                                        <td><?php echo date('F Y', strtotime($month['month'] . '-01')); ?></td>
                                                        <td class="<?php echo $monthProfit > 0 ? 'text-success' : ($monthProfit < 0 ? 'text-danger' : 'text-muted'); ?>">
                                                            <?php echo $monthProfit > 0 ? '+' : ($monthProfit < 0 ? '-' : ''); ?>
                                                            $<?php echo number_format(abs($monthProfit), 2); ?>
                                                        </td>
                                                        <td><?php echo number_format($tradeCount); ?></td>
                                                        <td><?php echo number_format($winRate, 1); ?>%</td>
                                                        <td class="text-success">
                                                            $<?php echo number_format($bestTrade, 2); ?>
                                                        </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 Performance Charts -->
                <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">
                                    <canvas id="profitLossChart" height="300"></canvas>
                                </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 echo htmlspecialchars($bestBot); ?></span>
                                    </div>
                                    <div class="summary-item">
                                        <span class="summary-label">Average Daily Profit:</span>
                                        <span class="summary-value text-success">
                                            $<?php echo number_format($averageDailyProfit, 2); ?>
                                        </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 $mostTrades; ?></span>
                                    </div>
                                    <div class="summary-item">
                                        <span class="summary-label">Current Streak:</span>
                                        <span class="summary-value text-success"><?php echo $currentStreak; ?></span>
                                    </div>
                                    <div class="summary-item">
                                        <span class="summary-label">Total Subscriptions:</span>
                                        <span class="summary-value"><?php echo count($allSubscriptions); ?></span>
                                    </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 $subscription['total_profit'] > 0 ? '+' : ''; ?>
                                                    $<?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>
            </div>
        </div>
        <?php include('includes/footer.php');?>
    </div>
   
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <!-- 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;
        }
        
        /* 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>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Profit/Loss Chart
        const ctx = document.getElementById('profitLossChart').getContext('2d');
        
        // Prepare chart data
        const months = [];
        const profits = [];
        
        <?php 
        // Reverse monthly data for chronological order
        $reversedMonthlyData = array_reverse($monthlyData);
        foreach($reversedMonthlyData as $month): 
        ?>
        months.push('<?php echo date('M', strtotime($month['month'] . '-01')); ?>');
        profits.push(<?php echo floatval($month['monthly_profit']); ?>);
        <?php endforeach; ?>
        
        // If no data, use sample data
        if (months.length === 0) {
            months.push('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun');
            profits.push(500, 800, 1200, 900, 1500, 1800);
        }
        
        const profitLossChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: months,
                datasets: [{
                    label: 'Monthly Profit ($)',
                    data: profits,
                    borderColor: 'rgb(59, 130, 246)',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    tension: 0.4,
                    fill: true,
                    pointBackgroundColor: function(context) {
                        const value = context.dataset.data[context.dataIndex];
                        return value >= 0 ? 'rgb(34, 197, 94)' : 'rgb(239, 68, 68)';
                    },
                    pointBorderColor: function(context) {
                        const value = context.dataset.data[context.dataIndex];
                        return value >= 0 ? 'rgb(34, 197, 94)' : 'rgb(239, 68, 68)';
                    }
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const value = context.raw;
                                return `${value >= 0 ? 'Profit' : 'Loss'}: $${Math.abs(value).toFixed(2)}`;
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.1)'
                        },
                        ticks: {
                            callback: function(value) {
                                return '$' + value;
                            }
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
        
        // Theme-aware chart colors
        function updateChartColors() {
            const isDark = document.documentElement.getAttribute('data-bs-theme') === 'dark';
            const gridColor = isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)';
            const textColor = isDark ? 'rgb(209, 213, 219)' : 'rgb(55, 65, 81)';
            
            profitLossChart.options.scales.y.grid.color = gridColor;
            profitLossChart.options.scales.y.ticks.color = textColor;
            profitLossChart.options.scales.x.ticks.color = textColor;
            profitLossChart.update();
        }
        
        // Initial color update
        updateChartColors();
        
        // Watch for theme changes
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.attributeName === 'data-bs-theme') {
                    updateChartColors();
                }
            });
        });
        
        observer.observe(document.documentElement, {
            attributes: true,
            attributeFilter: ['data-bs-theme']
        });
    });
    </script>
</body>
</html>

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