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

// Get filter parameters
$period = isset($_GET['period']) ? $_GET['period'] : 'today';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$bot_plan = isset($_GET['bot_plan']) ? intval($_GET['bot_plan']) : 0;
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

// Set date ranges based on period
$today = date('Y-m-d');
switch ($period) {
    case 'today':
        $date_from = $today;
        $date_to = $today;
        break;
    case 'yesterday':
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $date_from = $yesterday;
        $date_to = $yesterday;
        break;
    case 'this_week':
        $date_from = date('Y-m-d', strtotime('monday this week'));
        $date_to = date('Y-m-d', strtotime('sunday this week'));
        break;
    case 'last_week':
        $date_from = date('Y-m-d', strtotime('monday last week'));
        $date_to = date('Y-m-d', strtotime('sunday last week'));
        break;
    case 'this_month':
        $date_from = date('Y-m-d', strtotime('first day of this month'));
        $date_to = date('Y-m-d', strtotime('last day of this month'));
        break;
    case 'last_month':
        $date_from = date('Y-m-d', strtotime('first day of last month'));
        $date_to = date('Y-m-d', strtotime('last day of last month'));
        break;
    case 'this_year':
        $date_from = date('Y-01-01');
        $date_to = date('Y-12-31');
        break;
    case 'custom':
        // Use custom dates from form
        break;
    default:
        $date_from = $today;
        $date_to = $today;
}

// Build query for profit data
$profit_sql = "SELECT 
                DATE(t.date) as transaction_date,
                COUNT(t.id) as total_transactions,
                SUM(CASE WHEN t.type = 'profit' THEN t.amount ELSE 0 END) as total_profit,
                SUM(CASE WHEN t.type = 'loss' THEN t.amount ELSE 0 END) as total_loss,
                SUM(CASE WHEN t.type = 'fee' THEN t.amount ELSE 0 END) as total_fees,
                (SUM(CASE WHEN t.type = 'profit' THEN t.amount ELSE 0 END) - 
                 SUM(CASE WHEN t.type = 'loss' THEN t.amount ELSE 0 END) - 
                 SUM(CASE WHEN t.type = 'fee' THEN t.amount ELSE 0 END)) as net_profit
               FROM transactions t
               WHERE t.status = 'completed' 
                 AND t.type IN ('profit', 'loss', 'fee')";

// Add date filter
if ($date_from && $date_to) {
    $profit_sql .= " AND DATE(t.date) BETWEEN '$date_from' AND '$date_to'";
}

// Add user filter
if ($user_id > 0) {
    $profit_sql .= " AND t.user_id = $user_id";
}

// Add bot plan filter (if applicable)
if ($bot_plan > 0) {
    $profit_sql .= " AND t.related_id IN (SELECT id FROM user_bot_subscriptions WHERE bot_plan_id = $bot_plan) 
                     AND t.related_type = 'bot_transaction'";
}

$profit_sql .= " GROUP BY DATE(t.date) ORDER BY transaction_date DESC";

$profit_result = mysqli_query($conn, $profit_sql);

// Get summary totals
$summary_sql = str_replace("GROUP BY DATE(t.date) ORDER BY transaction_date DESC", "", $profit_sql);
$summary_result = mysqli_query($conn, $summary_sql);
$summary = mysqli_fetch_assoc($summary_result);

// Get bot plans for filter
$bot_plans_sql = "SELECT id, plan_name FROM trading_bot_plans WHERE is_active = 1 ORDER BY sort_order";
$bot_plans_result = mysqli_query($conn, $bot_plans_sql);

// Get top performing users
$top_users_sql = "SELECT 
                    u.id,
                    u.username,
                    u.email,
                    COUNT(t.id) as total_trades,
                    SUM(CASE WHEN t.type = 'profit' THEN t.amount ELSE 0 END) as total_profit,
                    SUM(CASE WHEN t.type = 'loss' THEN t.amount ELSE 0 END) as total_loss,
                    (SUM(CASE WHEN t.type = 'profit' THEN t.amount ELSE 0 END) - 
                     SUM(CASE WHEN t.type = 'loss' THEN t.amount ELSE 0 END)) as net_profit
                  FROM transactions t
                  LEFT JOIN users u ON t.user_id = u.id
                  WHERE t.status = 'completed' 
                    AND t.type IN ('profit', 'loss')";

if ($date_from && $date_to) {
    $top_users_sql .= " AND DATE(t.date) BETWEEN '$date_from' AND '$date_to'";
}

$top_users_sql .= " GROUP BY u.id 
                    HAVING net_profit > 0 
                    ORDER BY net_profit DESC 
                    LIMIT 10";

$top_users_result = mysqli_query($conn, $top_users_sql);

// Get top performing bot plans
$top_bots_sql = "SELECT 
                    p.id,
                    p.plan_name,
                    COUNT(DISTINCT s.id) as total_subscriptions,
                    COUNT(t.id) as total_trades,
                    SUM(CASE WHEN bt.transaction_type = 'profit' THEN bt.amount ELSE 0 END) as total_profit,
                    SUM(CASE WHEN bt.transaction_type = 'loss' THEN bt.amount ELSE 0 END) as total_loss,
                    (SUM(CASE WHEN bt.transaction_type = 'profit' THEN bt.amount ELSE 0 END) - 
                     SUM(CASE WHEN bt.transaction_type = 'loss' THEN bt.amount ELSE 0 END)) as net_profit
                  FROM bot_transactions bt
                  LEFT JOIN user_bot_subscriptions s ON bt.subscription_id = s.id
                  LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
                  WHERE bt.transaction_type IN ('profit', 'loss')";

if ($date_from && $date_to) {
    $top_bots_sql .= " AND DATE(bt.transaction_date) BETWEEN '$date_from' AND '$date_to'";
}

$top_bots_sql .= " GROUP BY p.id 
                   ORDER BY net_profit DESC 
                   LIMIT 10";

$top_bots_result = mysqli_query($conn, $top_bots_sql);
?>

<!DOCTYPE html>
<html lang="en">
  	
	
	<body class="hold-transition dark-skin sidebar-mini theme-primary fixed">
		
		<div class="wrapper">
		  	<div id="loader"></div>
		  	
		  <?php include('includes/header.php') ?>

		  <?php include('includes/sidebar.php') ?>

		  	<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<div class="container-full">
					<!-- Main content -->
					<section class="content">
						<div class="row">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h4 class="box-title"><i class="fas fa-chart-line me-2"></i>Profit & Loss Report</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" onclick="window.print()">
												<i class="fas fa-print me-1"></i> Print Report
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-12">
												<form method="GET" class="row g-3">
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">Period</label>
															<select class="form-control" name="period" onchange="this.form.submit()">
																<option value="today" <?php echo $period == 'today' ? 'selected' : ''; ?>>Today</option>
																<option value="yesterday" <?php echo $period == 'yesterday' ? 'selected' : ''; ?>>Yesterday</option>
																<option value="this_week" <?php echo $period == 'this_week' ? 'selected' : ''; ?>>This Week</option>
																<option value="last_week" <?php echo $period == 'last_week' ? 'selected' : ''; ?>>Last Week</option>
																<option value="this_month" <?php echo $period == 'this_month' ? 'selected' : ''; ?>>This Month</option>
																<option value="last_month" <?php echo $period == 'last_month' ? 'selected' : ''; ?>>Last Month</option>
																<option value="this_year" <?php echo $period == 'this_year' ? 'selected' : ''; ?>>This Year</option>
																<option value="custom" <?php echo $period == 'custom' ? 'selected' : ''; ?>>Custom Range</option>
															</select>
														</div>
													</div>
													
													<?php if ($period == 'custom'): ?>
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">From Date</label>
															<input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">To Date</label>
															<input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
														</div>
													</div>
													<?php else: ?>
														<input type="hidden" name="date_from" value="<?php echo $date_from; ?>">
														<input type="hidden" name="date_to" value="<?php echo $date_to; ?>">
													<?php endif; ?>
													
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">Bot Plan</label>
															<select class="form-control" name="bot_plan" onchange="this.form.submit()">
																<option value="0">All Plans</option>
																<?php while ($plan = mysqli_fetch_assoc($bot_plans_result)): ?>
																	<option value="<?php echo $plan['id']; ?>" <?php echo $bot_plan == $plan['id'] ? 'selected' : ''; ?>>
																		<?php echo htmlspecialchars($plan['plan_name']); ?>
																	</option>
																<?php endwhile; ?>
															</select>
														</div>
													</div>
													
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">User (Optional)</label>
															<input type="text" class="form-control" name="user_id" placeholder="User ID" value="<?php echo $user_id ? $user_id : ''; ?>">
														</div>
													</div>
													
													<div class="col-md-3 d-flex align-items-end">
														<div class="form-group">
															<button type="submit" class="btn btn-primary"><i class="fas fa-filter me-1"></i> Apply Filters</button>
															<?php if ($period != 'today' || $bot_plan != 0 || $user_id != 0): ?>
																<a href="profit_loss.php" class="btn btn-secondary ms-2">Reset</a>
															<?php endif; ?>
														</div>
													</div>
												</form>
											</div>
										</div>
										
										<!-- Summary Cards -->
										<div class="row mb-20">
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-success pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Total Profit</h5>
																<h2 class="text-white fw-500 mb-0">$<?php echo number_format($summary['total_profit'] ?: 0, 2); ?></h2>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-arrow-up fa-2x text-white"></i>
															</div>
														</div>
														<p class="text-white-50 mb-0 mt-10">From <?php echo $summary['total_transactions'] ?: 0; ?> trades</p>
													</div>
												</div>
											</div>
											
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-danger pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Total Loss</h5>
																<h2 class="text-white fw-500 mb-0">$<?php echo number_format($summary['total_loss'] ?: 0, 2); ?></h2>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-arrow-down fa-2x text-white"></i>
															</div>
														</div>
														<p class="text-white-50 mb-0 mt-10">Risk management</p>
													</div>
												</div>
											</div>
											
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-warning pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Total Fees</h5>
																<h2 class="text-white fw-500 mb-0">$<?php echo number_format($summary['total_fees'] ?: 0, 2); ?></h2>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-file-invoice fa-2x text-white"></i>
															</div>
														</div>
														<p class="text-white-50 mb-0 mt-10">Subscription & transaction fees</p>
													</div>
												</div>
											</div>
											
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-primary pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Net Profit</h5>
																<h2 class="text-white fw-500 mb-0">$<?php echo number_format($summary['net_profit'] ?: 0, 2); ?></h2>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-chart-line fa-2x text-white"></i>
															</div>
														</div>
														<p class="text-white-50 mb-0 mt-10">After fees & losses</p>
														<?php 
														$profit_margin = ($summary['total_profit'] > 0) ? 
															(($summary['net_profit'] / $summary['total_profit']) * 100) : 0;
														?>
														<p class="text-white-50 mb-0">Margin: <?php echo number_format($profit_margin, 2); ?>%</p>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Date Range Info -->
										<div class="alert alert-info mb-20">
											<div class="d-flex justify-content-between align-items-center">
												<div>
													<i class="fas fa-calendar-alt me-2"></i>
													<strong>Report Period:</strong> 
													<?php echo date('F d, Y', strtotime($date_from)); ?> 
													to 
													<?php echo date('F d, Y', strtotime($date_to)); ?>
												</div>
												<div>
													<?php 
													$days_count = (strtotime($date_to) - strtotime($date_from)) / (60 * 60 * 24) + 1;
													echo "<strong>" . intval($days_count) . "</strong> days";
													?>
												</div>
											</div>
										</div>
										
										<!-- Main Content Tabs -->
										<div class="row">
											<div class="col-12">
												<ul class="nav nav-tabs" role="tablist">
													<li class="nav-item">
														<a class="nav-link active" data-bs-toggle="tab" href="#daily">Daily Breakdown</a>
													</li>
													<li class="nav-item">
														<a class="nav-link" data-bs-toggle="tab" href="#top_users">Top Performers</a>
													</li>
													<li class="nav-item">
														<a class="nav-link" data-bs-toggle="tab" href="#top_bots">Bot Performance</a>
													</li>
													<li class="nav-item">
														<a class="nav-link" data-bs-toggle="tab" href="#charts">Charts</a>
													</li>
												</ul>
												
												<div class="tab-content mt-3">
													<!-- Daily Breakdown Tab -->
													<div class="tab-pane fade show active" id="daily">
														<div class="table-responsive">
															<table class="table table-hover table-bordered" id="dailyTable">
																<thead class="bg-light">
																	<tr>
																		<th>Date</th>
																		<th>Total Trades</th>
																		<th>Profit</th>
																		<th>Loss</th>
																		<th>Fees</th>
																		<th>Net Profit</th>
																		<th>Profit/Loss Ratio</th>
																		<th>Actions</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($profit_result) > 0): ?>
																		<?php 
																		$total_profit_all = 0;
																		$total_loss_all = 0;
																		$total_fees_all = 0;
																		$total_net_all = 0;
																		?>
																		<?php while ($day = mysqli_fetch_assoc($profit_result)): ?>
																			<?php
																			$date_formatted = date('D, M d, Y', strtotime($day['transaction_date']));
																			$profit = floatval($day['total_profit']);
																			$loss = floatval($day['total_loss']);
																			$fees = floatval($day['total_fees']);
																			$net = floatval($day['net_profit']);
																			$pl_ratio = ($loss > 0) ? ($profit / $loss) : ($profit > 0 ? '∞' : 0);
																			
																			$total_profit_all += $profit;
																			$total_loss_all += $loss;
																			$total_fees_all += $fees;
																			$total_net_all += $net;
																			?>
																			<tr>
																				<td>
																					<strong><?php echo $date_formatted; ?></strong>
																				</td>
																				<td>
																					<span class="badge bg-info"><?php echo $day['total_transactions']; ?> trades</span>
																				</td>
																				<td class="text-success fw-500">
																					+ $<?php echo number_format($profit, 2); ?>
																				</td>
																				<td class="text-danger fw-500">
																					- $<?php echo number_format($loss, 2); ?>
																				</td>
																				<td class="text-warning">
																					$<?php echo number_format($fees, 2); ?>
																				</td>
																				<td class="<?php echo $net >= 0 ? 'text-success' : 'text-danger'; ?> fw-500">
																					<?php echo $net >= 0 ? '+' : '-'; ?> $<?php echo number_format(abs($net), 2); ?>
																				</td>
																				<td>
																					<?php if (is_numeric($pl_ratio)): ?>
																						<span class="badge <?php echo $pl_ratio >= 1 ? 'bg-success' : 'bg-warning'; ?>">
																							<?php echo number_format($pl_ratio, 2); ?>:1
																						</span>
																						<small class="text-mute ms-2">
																							(<?php echo round(($profit / ($profit + $loss)) * 100, 1); ?>% win rate)
																						</small>
																					<?php else: ?>
																						<span class="badge bg-success"><?php echo $pl_ratio; ?></span>
																					<?php endif; ?>
																				</td>
																				<td>
																					<a href="profit_details.php?date=<?php echo $day['transaction_date']; ?>&bot_plan=<?php echo $bot_plan; ?>&user_id=<?php echo $user_id; ?>" 
																					   class="btn btn-sm btn-light" title="View Details">
																						<i class="fas fa-eye"></i>
																					</a>
																				</td>
																			</tr>
																		<?php endwhile; ?>
																		
																		<!-- Totals Row -->
																		<tr class="bg-light fw-bold">
																			<td><strong>TOTAL</strong></td>
																			<td><?php echo $summary['total_transactions'] ?: 0; ?></td>
																			<td class="text-success">+ $<?php echo number_format($total_profit_all, 2); ?></td>
																			<td class="text-danger">- $<?php echo number_format($total_loss_all, 2); ?></td>
																			<td class="text-warning">$<?php echo number_format($total_fees_all, 2); ?></td>
																			<td class="<?php echo $total_net_all >= 0 ? 'text-success' : 'text-danger'; ?>">
																				<?php echo $total_net_all >= 0 ? '+' : '-'; ?> $<?php echo number_format(abs($total_net_all), 2); ?>
																			</td>
																			<td>
																				<?php 
																				$total_pl_ratio = ($total_loss_all > 0) ? ($total_profit_all / $total_loss_all) : ($total_profit_all > 0 ? '∞' : 0);
																				if (is_numeric($total_pl_ratio)) {
																					echo '<span class="badge ' . ($total_pl_ratio >= 1 ? 'bg-success' : 'bg-warning') . '">';
																					echo number_format($total_pl_ratio, 2) . ':1</span>';
																					echo '<small class="text-mute ms-2">(';
																					echo round(($total_profit_all / ($total_profit_all + $total_loss_all)) * 100, 1);
																					echo '% win rate)</small>';
																				} else {
																					echo '<span class="badge bg-success">' . $total_pl_ratio . '</span>';
																				}
																				?>
																			</td>
																			<td></td>
																		</tr>
																	<?php else: ?>
																		<tr>
																			<td colspan="8" class="text-center py-20">
																				<i class="fas fa-chart-line fa-2x text-mute mb-3"></i>
																				<h5>No profit/loss data found</h5>
																				<p class="text-mute">Try adjusting your date range or filters</p>
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
													
													<!-- Top Performers Tab -->
													<div class="tab-pane fade" id="top_users">
														<div class="table-responsive">
															<table class="table table-hover">
																<thead>
																	<tr>
																		<th>Rank</th>
																		<th>User</th>
																		<th>Total Trades</th>
																		<th>Total Profit</th>
																		<th>Total Loss</th>
																		<th>Net Profit</th>
																		<th>Win Rate</th>
																		<th>Actions</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($top_users_result) > 0): ?>
																		<?php $rank = 1; ?>
																		<?php while ($user = mysqli_fetch_assoc($top_users_result)): ?>
																			<?php
																			$win_rate = ($user['total_profit'] + $user['total_loss'] > 0) ? 
																				($user['total_profit'] / ($user['total_profit'] + $user['total_loss'])) * 100 : 0;
																			?>
																			<tr>
																				<td>
																					<div class="d-flex align-items-center">
																						<span class="badge bg-<?php echo $rank <= 3 ? 'warning' : 'info'; ?> me-2">
																							#<?php echo $rank; ?>
																						</span>
																						<?php if ($rank == 1): ?>
																							<i class="fas fa-trophy text-warning"></i>
																						<?php endif; ?>
																					</div>
																				</td>
																				<td>
																					<div class="d-flex align-items-center">
																						<div class="me-10">
																							<div class="bg-primary rounded-circle w-40 h-40 d-flex align-items-center justify-content-center">
																								<i class="fas fa-user text-white"></i>
																							</div>
																						</div>
																						<div>
																							<p class="mb-0 fw-500"><?php echo htmlspecialchars($user['username']); ?></p>
																							<small class="text-mute"><?php echo htmlspecialchars($user['email']); ?></small>
																						</div>
																					</div>
																				</td>
																				<td>
																					<span class="badge bg-light text-dark"><?php echo $user['total_trades']; ?></span>
																				</td>
																				<td class="text-success fw-500">
																					+ $<?php echo number_format($user['total_profit'], 2); ?>
																				</td>
																				<td class="text-danger">
																					- $<?php echo number_format($user['total_loss'], 2); ?>
																				</td>
																				<td class="fw-500 <?php echo $user['net_profit'] >= 0 ? 'text-success' : 'text-danger'; ?>">
																					<?php echo $user['net_profit'] >= 0 ? '+' : '-'; ?> $<?php echo number_format(abs($user['net_profit']), 2); ?>
																				</td>
																				<td>
																					<div class="progress" style="height: 20px;">
																						<div class="progress-bar bg-success" role="progressbar" 
																							 style="width: <?php echo $win_rate; ?>%">
																							<?php echo round($win_rate, 1); ?>%
																						</div>
																					</div>
																				</td>
																				<td>
																					<a href="view_user.php?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-light">
																						<i class="fas fa-user"></i> Profile
																					</a>
																				</td>
																			</tr>
																			<?php $rank++; ?>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="8" class="text-center py-20">
																				<i class="fas fa-users fa-2x text-mute mb-3"></i>
																				<h5>No user performance data</h5>
																				<p class="text-mute">No profitable trades in selected period</p>
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
													
													<!-- Bot Performance Tab -->
													<div class="tab-pane fade" id="top_bots">
														<div class="table-responsive">
															<table class="table table-hover">
																<thead>
																	<tr>
																		<th>Bot Plan</th>
																		<th>Active Subs</th>
																		<th>Total Trades</th>
																		<th>Total Profit</th>
																		<th>Total Loss</th>
																		<th>Net Profit</th>
																		<th>Avg. Profit/Sub</th>
																		<th>Performance</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($top_bots_result) > 0): ?>
																		<?php while ($bot = mysqli_fetch_assoc($top_bots_result)): ?>
																			<?php
																			$avg_profit = $bot['total_subscriptions'] > 0 ? 
																				$bot['net_profit'] / $bot['total_subscriptions'] : 0;
																			$success_rate = ($bot['total_profit'] + $bot['total_loss'] > 0) ? 
																				($bot['total_profit'] / ($bot['total_profit'] + $bot['total_loss'])) * 100 : 0;
																			?>
																			<tr>
																				<td>
																					<strong><?php echo htmlspecialchars($bot['plan_name']); ?></strong>
																				</td>
																				<td>
																					<span class="badge bg-info"><?php echo $bot['total_subscriptions']; ?></span>
																				</td>
																				<td>
																					<?php echo $bot['total_trades']; ?>
																				</td>
																				<td class="text-success fw-500">
																					+ $<?php echo number_format($bot['total_profit'], 2); ?>
																				</td>
																				<td class="text-danger">
																					- $<?php echo number_format($bot['total_loss'], 2); ?>
																				</td>
																				<td class="fw-500 <?php echo $bot['net_profit'] >= 0 ? 'text-success' : 'text-danger'; ?>">
																					<?php echo $bot['net_profit'] >= 0 ? '+' : '-'; ?> $<?php echo number_format(abs($bot['net_profit']), 2); ?>
																				</td>
																				<td>
																					<span class="badge <?php echo $avg_profit >= 0 ? 'bg-success' : 'bg-danger'; ?>">
																						$<?php echo number_format($avg_profit, 2); ?>
																					</span>
																				</td>
																				<td>
																					<div class="d-flex align-items-center">
																						<div class="progress flex-grow-1" style="height: 10px;">
																							<div class="progress-bar bg-success" role="progressbar" 
																								 style="width: <?php echo $success_rate; ?>%">
																							</div>
																						</div>
																						<small class="ms-2 text-mute"><?php echo round($success_rate, 1); ?>%</small>
																					</div>
																				</td>
																			</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="8" class="text-center py-20">
																				<i class="fas fa-robot fa-2x text-mute mb-3"></i>
																				<h5>No bot performance data</h5>
																				<p class="text-mute">No bot trades in selected period</p>
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
													
													<!-- Charts Tab -->
													<div class="tab-pane fade" id="charts">
														<div class="row">
															<div class="col-md-6">
																<div class="box">
																	<div class="box-header">
																		<h5 class="box-title">Profit vs Loss Trend</h5>
																	</div>
																	<div class="box-body">
																		<canvas id="profitLossChart" height="250"></canvas>
																	</div>
																</div>
															</div>
															<div class="col-md-6">
																<div class="box">
																	<div class="box-header">
																		<h5 class="box-title">Monthly Performance</h5>
																	</div>
																	<div class="box-body">
																		<canvas id="monthlyChart" height="250"></canvas>
																	</div>
																</div>
															</div>
															<div class="col-md-12 mt-3">
																<div class="box">
																	<div class="box-header">
																		<h5 class="box-title">Profit Distribution by Bot Plan</h5>
																	</div>
																	<div class="box-body">
																		<canvas id="planDistributionChart" height="150"></canvas>
																	</div>
																</div>
															</div>
														</div>
														<div class="alert alert-info mt-3">
															<i class="fas fa-info-circle me-2"></i>
															Chart data is based on the current filter selection. Change filters to update charts.
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Export Options -->
										<div class="row mt-20">
											<div class="col-12">
												<div class="box bg-light">
													<div class="box-body">
														<h5 class="mb-3"><i class="fas fa-download me-2"></i>Export Report</h5>
														<div class="btn-group">
															<a href="export_profit_loss.php?period=<?php echo $period; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&bot_plan=<?php echo $bot_plan; ?>&user_id=<?php echo $user_id; ?>&format=csv" 
															   class="btn btn-outline-primary">
																<i class="fas fa-file-csv me-1"></i> CSV
															</a>
															<a href="export_profit_loss.php?period=<?php echo $period; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&bot_plan=<?php echo $bot_plan; ?>&user_id=<?php echo $user_id; ?>&format=excel" 
															   class="btn btn-outline-success">
																<i class="fas fa-file-excel me-1"></i> Excel
															</a>
															<a href="export_profit_loss.php?period=<?php echo $period; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&bot_plan=<?php echo $bot_plan; ?>&user_id=<?php echo $user_id; ?>&format=pdf" 
															   class="btn btn-outline-danger">
																<i class="fas fa-file-pdf me-1"></i> PDF
															</a>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- Chart.js -->
		<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
		
		<!-- DataTables -->
		<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
		<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
		<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
		
		<script>
		$(document).ready(function() {
			// Initialize DataTable
			$('#dailyTable').DataTable({
				"pageLength": 25,
				"order": [[0, 'desc']],
				"language": {
					"search": "Search:",
					"lengthMenu": "Show _MENU_ entries",
					"info": "Showing _START_ to _END_ of _TOTAL_ entries",
					"paginate": {
						"first": "First",
						"last": "Last",
						"next": "Next",
						"previous": "Previous"
					}
				}
			});
			
			// Initialize Charts
			initializeCharts();
		});
		
		function initializeCharts() {
			// Profit vs Loss Chart
			var profitLossCtx = document.getElementById('profitLossChart').getContext('2d');
			var profitLossChart = new Chart(profitLossCtx, {
				type: 'line',
				data: {
					labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
					datasets: [{
						label: 'Profit',
						data: [1200, 1900, 3000, 5000, 2000, 3000, 4500],
						borderColor: '#28a745',
						backgroundColor: 'rgba(40, 167, 69, 0.1)',
						tension: 0.4,
						fill: true
					}, {
						label: 'Loss',
						data: [400, 1200, 800, 1500, 1000, 500, 800],
						borderColor: '#dc3545',
						backgroundColor: 'rgba(220, 53, 69, 0.1)',
						tension: 0.4,
						fill: true
					}]
				},
				options: {
					responsive: true,
					plugins: {
						legend: {
							position: 'top',
						},
						tooltip: {
							mode: 'index',
							intersect: false,
						}
					},
					scales: {
						y: {
							beginAtZero: true,
							ticks: {
								callback: function(value) {
									return '$' + value;
								}
							}
						}
					}
				}
			});
			
			// Monthly Performance Chart
			var monthlyCtx = document.getElementById('monthlyChart').getContext('2d');
			var monthlyChart = new Chart(monthlyCtx, {
				type: 'bar',
				data: {
					labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
					datasets: [{
						label: 'Net Profit',
						data: [5000, 7000, 8000, 12000, 15000, 18000, 22000, 25000, 28000, 32000, 35000, 40000],
						backgroundColor: 'rgba(54, 162, 235, 0.7)',
						borderColor: 'rgba(54, 162, 235, 1)',
						borderWidth: 1
					}]
				},
				options: {
					responsive: true,
					plugins: {
						legend: {
							position: 'top',
						}
					},
					scales: {
						y: {
							beginAtZero: true,
							ticks: {
								callback: function(value) {
									return '$' + value;
								}
							}
						}
					}
				}
			});
			
			// Plan Distribution Chart
			var planCtx = document.getElementById('planDistributionChart').getContext('2d');
			var planChart = new Chart(planCtx, {
				type: 'doughnut',
				data: {
					labels: ['AI Alpha', 'AI Sigma', 'AI Quantum', 'AI Omega'],
					datasets: [{
						data: [30000, 45000, 60000, 85000],
						backgroundColor: [
							'rgba(255, 99, 132, 0.7)',
							'rgba(54, 162, 235, 0.7)',
							'rgba(255, 206, 86, 0.7)',
							'rgba(75, 192, 192, 0.7)'
						],
						borderColor: [
							'rgba(255, 99, 132, 1)',
							'rgba(54, 162, 235, 1)',
							'rgba(255, 206, 86, 1)',
							'rgba(75, 192, 192, 1)'
						],
						borderWidth: 1
					}]
				},
				options: {
					responsive: true,
					plugins: {
						legend: {
							position: 'right',
						},
						tooltip: {
							callbacks: {
								label: function(context) {
									let label = context.label || '';
									if (label) {
										label += ': ';
									}
									label += '$' + context.raw;
									return label;
								}
							}
						}
					}
				}
			});
		}
		
		// Auto-refresh data every 60 seconds
		setInterval(function() {
			location.reload();
		}, 60000); // 60 seconds
		</script>
		
		<style>
		.nav-tabs .nav-link.active {
			background-color: #f8f9fa;
			border-color: #dee2e6 #dee2e6 #f8f9fa;
			font-weight: 500;
		}
		.bg-white-20 {
			background-color: rgba(255, 255, 255, 0.2);
		}
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
		}
		.badge {
			padding: 5px 10px;
			border-radius: 20px;
			font-size: 12px;
			font-weight: 600;
		}
		.progress {
			border-radius: 10px;
		}
		.progress-bar {
			border-radius: 10px;
		}
		@media print {
			.sidebar, .header, .box-controls, .nav-tabs, .export-options {
				display: none !important;
			}
			.box {
				border: 1px solid #ddd !important;
			}
		}
		</style>
		
	</body>
</html>