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

// Check admin session
$admin_id = $_SESSION['admin_id'] ?: 1;
$admin_name = $_SESSION['admin_name'] ?: 'System Admin';
$admin_role = $_SESSION['admin_role'] ?: 'admin';

// Date range for filtering
$default_start = date('Y-m-01'); // First day of current month
$default_end = date('Y-m-d'); // Today

$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : $default_start;
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : $default_end;
$bot_plan = isset($_GET['bot_plan']) ? intval($_GET['bot_plan']) : 0;
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$report_type = isset($_GET['report_type']) ? $_GET['report_type'] : 'daily';

// Validate dates
if (!strtotime($start_date) || !strtotime($end_date)) {
    $start_date = $default_start;
    $end_date = $default_end;
}

// Get bot plans for filter dropdown
$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 active users for filter dropdown
$users_sql = "SELECT id, username, first_name, last_name FROM users WHERE status = 'verified' ORDER BY username";
$users_result = mysqli_query($conn, $users_sql);

// Calculate date difference for time-based calculations
$date_diff = strtotime($end_date) - strtotime($start_date);
$days_diff = floor($date_diff / (60 * 60 * 24)) + 1;

// Main trading statistics query
$stats_sql = "SELECT 
    COUNT(DISTINCT s.user_id) as active_traders,
    COUNT(DISTINCT s.id) as active_subscriptions,
    COALESCE(SUM(s.trading_balance), 0) as total_trading_capital,
    COALESCE(SUM(s.total_profit), 0) as total_profit_generated,
    COALESCE(AVG(s.success_rate), 0) as avg_success_rate,
    COALESCE(SUM(s.total_trades), 0) as total_trades_executed
    FROM user_bot_subscriptions s
    WHERE s.status = 'active' 
    AND s.subscription_start <= '$end_date' 
    AND (s.subscription_end >= '$start_date' OR s.subscription_end IS NULL)";

if ($bot_plan > 0) {
    $stats_sql .= " AND s.bot_plan_id = $bot_plan";
}
if ($user_id > 0) {
    $stats_sql .= " AND s.user_id = $user_id";
}

$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);

// Daily profit/loss data
$daily_sql = "SELECT 
    DATE(t.date) as trade_date,
    SUM(CASE WHEN t.type = 'profit' THEN t.amount ELSE 0 END) as daily_profit,
    SUM(CASE WHEN t.type = 'loss' THEN t.amount ELSE 0 END) as daily_loss,
    COUNT(t.id) as total_trades
    FROM transactions t
    WHERE t.type IN ('profit', 'loss')
    AND t.status = 'completed'
    AND DATE(t.date) BETWEEN '$start_date' AND '$end_date'";

if ($user_id > 0) {
    $daily_sql .= " AND t.user_id = $user_id";
}

$daily_sql .= " GROUP BY DATE(t.date) ORDER BY trade_date";

$daily_result = mysqli_query($conn, $daily_sql);

// Bot plan performance
$bot_performance_sql = "SELECT 
    p.plan_name,
    COUNT(DISTINCT s.id) as subscription_count,
    COALESCE(SUM(s.trading_balance), 0) as total_capital,
    COALESCE(SUM(s.total_profit), 0) as total_profit,
    COALESCE(AVG(s.success_rate), 0) as avg_success,
    COALESCE(SUM(s.total_trades), 0) as total_trades
    FROM trading_bot_plans p
    LEFT JOIN user_bot_subscriptions s ON p.id = s.bot_plan_id 
    AND s.status = 'active'
    AND s.subscription_start <= '$end_date' 
    AND (s.subscription_end >= '$start_date' OR s.subscription_end IS NULL)
    WHERE p.is_active = 1";

if ($user_id > 0) {
    $bot_performance_sql .= " AND s.user_id = $user_id";
}

$bot_performance_sql .= " GROUP BY p.id ORDER BY p.sort_order";
$bot_performance_result = mysqli_query($conn, $bot_performance_sql);

// Top performing traders
$top_traders_sql = "SELECT 
    u.id,
    u.username,
    u.first_name,
    u.last_name,
    COUNT(DISTINCT s.id) as active_bots,
    COALESCE(SUM(s.total_profit), 0) as total_profit,
    COALESCE(AVG(s.success_rate), 0) as avg_success_rate,
    COALESCE(SUM(s.total_trades), 0) as total_trades
    FROM users u
    LEFT JOIN user_bot_subscriptions s ON u.id = s.user_id 
    AND s.status = 'active'
    AND s.subscription_start <= '$end_date' 
    AND (s.subscription_end >= '$start_date' OR s.subscription_end IS NULL)
    WHERE u.status = 'verified'";

if ($bot_plan > 0) {
    $top_traders_sql .= " AND s.bot_plan_id = $bot_plan";
}

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

$top_traders_result = mysqli_query($conn, $top_traders_sql);

// Recent trading activities
$recent_activities_sql = "SELECT 
    t.*,
    u.username,
    p.plan_name
    FROM transactions t
    LEFT JOIN users u ON t.user_id = u.id
    LEFT JOIN user_bot_subscriptions s ON t.related_id = s.id AND t.related_type = 'subscription'
    LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
    WHERE t.type IN ('profit', 'loss')
    AND t.status = 'completed'
    AND DATE(t.date) BETWEEN '$start_date' AND '$end_date'";

if ($bot_plan > 0) {
    $recent_activities_sql .= " AND s.bot_plan_id = $bot_plan";
}
if ($user_id > 0) {
    $recent_activities_sql .= " AND t.user_id = $user_id";
}

$recent_activities_sql .= " ORDER BY t.created_at DESC LIMIT 20";
$recent_activities_result = mysqli_query($conn, $recent_activities_sql);

// Calculate summary statistics
$total_profit = $stats['total_profit_generated'] ?: 0;
$total_capital = $stats['total_trading_capital'] ?: 0;
$roi_percentage = $total_capital > 0 ? ($total_profit / $total_capital) * 100 : 0;
$avg_daily_profit = $days_diff > 0 ? $total_profit / $days_diff : 0;
?>

<!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>Trading Report & Analytics</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" onclick="printReport()">
												<i class="fas fa-print me-1"></i> Print Report
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Report Filters -->
										<div class="row mb-20">
											<div class="col-md-12">
												<form method="GET" class="row g-3">
													<div class="col-md-3">
														<label class="form-label">Start Date</label>
														<input type="date" class="form-control" name="start_date" value="<?php echo $start_date; ?>">
													</div>
													<div class="col-md-3">
														<label class="form-label">End Date</label>
														<input type="date" class="form-control" name="end_date" value="<?php echo $end_date; ?>">
													</div>
													<div class="col-md-2">
														<label class="form-label">Bot Plan</label>
														<select class="form-control" name="bot_plan">
															<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 class="col-md-2">
														<label class="form-label">User</label>
														<select class="form-control" name="user_id">
															<option value="0">All Users</option>
															<?php while ($user = mysqli_fetch_assoc($users_result)): ?>
																<option value="<?php echo $user['id']; ?>" <?php echo $user_id == $user['id'] ? 'selected' : ''; ?>>
																	<?php echo htmlspecialchars($user['username'] . ' - ' . $user['first_name'] . ' ' . $user['last_name']); ?>
																</option>
															<?php endwhile; ?>
														</select>
													</div>
													<div class="col-md-2">
														<label class="form-label">Report Type</label>
														<select class="form-control" name="report_type">
															<option value="daily" <?php echo $report_type == 'daily' ? 'selected' : ''; ?>>Daily</option>
															<option value="weekly" <?php echo $report_type == 'weekly' ? 'selected' : ''; ?>>Weekly</option>
															<option value="monthly" <?php echo $report_type == 'monthly' ? 'selected' : ''; ?>>Monthly</option>
														</select>
													</div>
													<div class="col-md-12 mt-3">
														<button type="submit" class="btn btn-primary">
															<i class="fas fa-filter me-1"></i> Apply Filters
														</button>
														<a href="trading_report.php" class="btn btn-secondary">
															<i class="fas fa-redo me-1"></i> Reset
														</a>
														<div class="btn-group float-end">
															<button type="button" class="btn btn-success dropdown-toggle" data-bs-toggle="dropdown">
																<i class="fas fa-download me-1"></i> Export
															</button>
															<div class="dropdown-menu">
																<a class="dropdown-item" href="export_trading_report.php?format=csv&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&bot_plan=<?php echo $bot_plan; ?>&user_id=<?php echo $user_id; ?>">
																	<i class="fas fa-file-csv"></i> CSV
																</a>
																<a class="dropdown-item" href="export_trading_report.php?format=excel&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&bot_plan=<?php echo $bot_plan; ?>&user_id=<?php echo $user_id; ?>">
																	<i class="fas fa-file-excel"></i> Excel
																</a>
																<a class="dropdown-item" href="export_trading_report.php?format=pdf&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&bot_plan=<?php echo $bot_plan; ?>&user_id=<?php echo $user_id; ?>">
																	<i class="fas fa-file-pdf"></i> PDF
																</a>
															</div>
														</div>
													</div>
												</form>
											</div>
										</div>
										
										<!-- Summary Stats -->
										<div class="row mb-20">
											<div class="col-md-12">
												<div class="alert alert-info">
													<div class="d-flex justify-content-between align-items-center">
														<div>
															<h5 class="mb-0">Report Period: <?php echo date('F d, Y', strtotime($start_date)); ?> to <?php echo date('F d, Y', strtotime($end_date)); ?></h5>
															<p class="mb-0"><?php echo $days_diff; ?> days analyzed</p>
														</div>
														<div>
															<span class="badge bg-primary fs-16">Generated: <?php echo date('F d, Y H:i'); ?></span>
														</div>
													</div>
												</div>
											</div>
											
											<!-- Summary Cards -->
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-primary pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500">$<?php echo number_format($total_profit, 2); ?></h1>
														<p class="text-white mb-0">Total Profit Generated</p>
														<small class="text-white-50">Avg Daily: $<?php echo number_format($avg_daily_profit, 2); ?></small>
													</div>
												</div>
											</div>
											
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-success pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500">$<?php echo number_format($total_capital, 2); ?></h1>
														<p class="text-white mb-0">Trading Capital</p>
														<small class="text-white-50">Active Investments</small>
													</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 text-center">
														<h1 class="text-white fw-500"><?php echo number_format($roi_percentage, 2); ?>%</h1>
														<p class="text-white mb-0">Average ROI</p>
														<small class="text-white-50">Return on Investment</small>
													</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 text-center">
														<h1 class="text-white fw-500"><?php echo number_format($stats['total_trades_executed'] ?: 0); ?></h1>
														<p class="text-white mb-0">Total Trades</p>
														<small class="text-white-50">Executed Orders</small>
													</div>
												</div>
											</div>
											
											<!-- Additional Stats -->
											<div class="col-xl-4 col-md-6 col-12">
												<div class="box bg-gradient-info pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo number_format($stats['active_traders'] ?: 0); ?></h1>
														<p class="text-white mb-0">Active Traders</p>
														<small class="text-white-50">Currently Trading</small>
													</div>
												</div>
											</div>
											
											<div class="col-xl-4 col-md-6 col-12">
												<div class="box bg-gradient-secondary pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo number_format($stats['active_subscriptions'] ?: 0); ?></h1>
														<p class="text-white mb-0">Active Bots</p>
														<small class="text-white-50">Running Subscriptions</small>
													</div>
												</div>
											</div>
											
											<div class="col-xl-4 col-md-6 col-12">
												<div class="box bg-gradient-dark pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo number_format($stats['avg_success_rate'] ?: 0, 1); ?>%</h1>
														<p class="text-white mb-0">Success Rate</p>
														<small class="text-white-50">Average Win Rate</small>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Daily Profit/Loss Chart -->
										<div class="row mb-20">
											<div class="col-md-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-bar me-2"></i>Daily Profit & Loss Analysis</h5>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover table-bordered" id="dailyTable">
																<thead class="bg-light">
																	<tr>
																		<th>Date</th>
																		<th>Profit ($)</th>
																		<th>Loss ($)</th>
																		<th>Net P/L ($)</th>
																		<th>Total Trades</th>
																		<th>Win Rate</th>
																		<th>Details</th>
																	</tr>
																</thead>
																<tbody>
																	<?php 
																	$total_profit_sum = 0;
																	$total_loss_sum = 0;
																	$total_trades_sum = 0;
																	
																	if (mysqli_num_rows($daily_result) > 0): 
																		while ($day = mysqli_fetch_assoc($daily_result)): 
																			$net_pl = $day['daily_profit'] - $day['daily_loss'];
																			$win_rate = $day['total_trades'] > 0 ? ($day['daily_profit'] / ($day['daily_profit'] + $day['daily_loss']) * 100) : 0;
																			
																			$total_profit_sum += $day['daily_profit'];
																			$total_loss_sum += $day['daily_loss'];
																			$total_trades_sum += $day['total_trades'];
																			?>
																			<tr class="<?php echo $net_pl >= 0 ? 'table-success' : 'table-danger'; ?>">
																				<td><?php echo date('M d, Y', strtotime($day['trade_date'])); ?></td>
																				<td class="text-success fw-500">$<?php echo number_format($day['daily_profit'], 2); ?></td>
																				<td class="text-danger fw-500">$<?php echo number_format($day['daily_loss'], 2); ?></td>
																				<td class="fw-500 <?php echo $net_pl >= 0 ? 'text-success' : 'text-danger'; ?>">
																					$<?php echo number_format($net_pl, 2); ?>
																				</td>
																				<td><?php echo number_format($day['total_trades']); ?></td>
																				<td><?php echo number_format($win_rate, 1); ?>%</td>
																				<td>
																					<button class="btn btn-sm btn-light" onclick="viewDayDetails('<?php echo $day['trade_date']; ?>')">
																						<i class="fas fa-eye"></i>
																					</button>
																				</td>
																			</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="7" class="text-center py-20">
																				<i class="fas fa-chart-bar fa-2x text-mute mb-3"></i>
																				<h5>No trading data found</h5>
																				<p class="text-mute">Try adjusting your date range</p>
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
																<tfoot class="bg-light">
																	<tr>
																		<th>Total</th>
																		<th class="text-success">$<?php echo number_format($total_profit_sum, 2); ?></th>
																		<th class="text-danger">$<?php echo number_format($total_loss_sum, 2); ?></th>
																		<th class="<?php echo ($total_profit_sum - $total_loss_sum) >= 0 ? 'text-success' : 'text-danger'; ?>">
																			$<?php echo number_format($total_profit_sum - $total_loss_sum, 2); ?>
																		</th>
																		<th><?php echo number_format($total_trades_sum); ?></th>
																		<th><?php echo $total_trades_sum > 0 ? number_format(($total_profit_sum / ($total_profit_sum + $total_loss_sum) * 100), 1) : '0'; ?>%</th>
																		<th></th>
																	</tr>
																</tfoot>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Bot Plan Performance -->
										<div class="row mb-20">
											<div class="col-md-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-robot me-2"></i>Bot Plan Performance</h5>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover table-bordered">
																<thead class="bg-light">
																	<tr>
																		<th>Bot Plan</th>
																		<th>Active Subscriptions</th>
																		<th>Total Capital</th>
																		<th>Total Profit</th>
																		<th>Avg Success Rate</th>
																		<th>Total Trades</th>
																		<th>ROI</th>
																		<th>Performance</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($bot_performance_result) > 0): 
																		while ($bot = mysqli_fetch_assoc($bot_performance_result)): 
																			$roi = $bot['total_capital'] > 0 ? ($bot['total_profit'] / $bot['total_capital']) * 100 : 0;
																			$performance_class = $roi > 15 ? 'success' : ($roi > 5 ? 'warning' : 'danger');
																			?>
																			<tr>
																				<td><strong><?php echo htmlspecialchars($bot['plan_name']); ?></strong></td>
																				<td><?php echo number_format($bot['subscription_count']); ?></td>
																				<td>$<?php echo number_format($bot['total_capital'], 2); ?></td>
																				<td class="text-success fw-500">$<?php echo number_format($bot['total_profit'], 2); ?></td>
																				<td><?php echo number_format($bot['avg_success'], 1); ?>%</td>
																				<td><?php echo number_format($bot['total_trades']); ?></td>
																				<td>
																					<span class="badge bg-<?php echo $performance_class; ?>">
																						<?php echo number_format($roi, 2); ?>%
																					</span>
																				</td>
																				<td>
																					<div class="progress" style="height: 10px;">
																						<div class="progress-bar bg-<?php echo $performance_class; ?>" 
																							 style="width: <?php echo min($roi, 100); ?>%"></div>
																					</div>
																				</td>
																			</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="8" class="text-center py-20">No bot performance data found</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Top Performing Traders -->
										<div class="row mb-20">
											<div class="col-md-6">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-trophy me-2"></i>Top Performing Traders</h5>
													</div>
													<div class="box-body">
														<?php if (mysqli_num_rows($top_traders_result) > 0): ?>
															<div class="table-responsive">
																<table class="table table-hover">
																	<thead>
																		<tr>
																			<th>Rank</th>
																			<th>Trader</th>
																			<th>Active Bots</th>
																			<th>Total Profit</th>
																			<th>Success Rate</th>
																		</tr>
																	</thead>
																	<tbody>
																		<?php 
																		$rank = 1;
																		while ($trader = mysqli_fetch_assoc($top_traders_result)): 
																			$medal_class = $rank == 1 ? 'bg-warning text-dark' : ($rank == 2 ? 'bg-secondary' : ($rank == 3 ? 'bg-danger' : 'bg-light'));
																			?>
																			<tr>
																				<td>
																					<span class="badge <?php echo $medal_class; ?> p-2">
																						<?php echo $rank; ?>
																					</span>
																				</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($trader['username']); ?></p>
																							<small class="text-mute"><?php echo htmlspecialchars($trader['first_name'] . ' ' . $trader['last_name']); ?></small>
																						</div>
																					</div>
																				</td>
																				<td><?php echo number_format($trader['active_bots']); ?></td>
																				<td class="text-success fw-500">$<?php echo number_format($trader['total_profit'], 2); ?></td>
																				<td>
																					<span class="badge bg-<?php echo $trader['avg_success_rate'] > 80 ? 'success' : ($trader['avg_success_rate'] > 60 ? 'warning' : 'danger'); ?>">
																						<?php echo number_format($trader['avg_success_rate'], 1); ?>%
																					</span>
																				</td>
																			</tr>
																			<?php $rank++; ?>
																		<?php endwhile; ?>
																	</tbody>
																</table>
															</div>
														<?php else: ?>
															<div class="alert alert-info">
																<i class="fas fa-info-circle me-2"></i> No top performers data available
															</div>
														<?php endif; ?>
													</div>
												</div>
											</div>
											
											<!-- Recent Trading Activities -->
											<div class="col-md-6">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-history me-2"></i>Recent Trading Activities</h5>
													</div>
													<div class="box-body">
														<?php if (mysqli_num_rows($recent_activities_result) > 0): ?>
															<div class="table-responsive">
																<table class="table table-hover">
																	<thead>
																		<tr>
																			<th>Time</th>
																			<th>User</th>
																			<th>Type</th>
																			<th>Amount</th>
																			<th>Bot Plan</th>
																		</tr>
																	</thead>
																	<tbody>
																		<?php while ($activity = mysqli_fetch_assoc($recent_activities_result)): ?>
																			<tr>
																				<td>
																					<small><?php echo date('H:i', strtotime($activity['created_at'])); ?></small>
																				</td>
																				<td>
																					<small><?php echo htmlspecialchars($activity['username']); ?></small>
																				</td>
																				<td>
																					<span class="badge bg-<?php echo $activity['type'] == 'profit' ? 'success' : 'danger'; ?>">
																						<?php echo ucfirst($activity['type']); ?>
																					</span>
																				</td>
																				<td class="fw-500 <?php echo $activity['type'] == 'profit' ? 'text-success' : 'text-danger'; ?>">
																					$<?php echo number_format($activity['amount'], 2); ?>
																				</td>
																				<td>
																					<small><?php echo htmlspecialchars($activity['plan_name'] ?: 'N/A'); ?></small>
																				</td>
																			</tr>
																		<?php endwhile; ?>
																	</tbody>
																</table>
															</div>
														<?php else: ?>
															<div class="alert alert-info">
																<i class="fas fa-info-circle me-2"></i> No recent trading activities
															</div>
														<?php endif; ?>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Insights & Recommendations -->
										<div class="row">
											<div class="col-md-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-lightbulb me-2"></i>Insights & Recommendations</h5>
													</div>
													<div class="box-body">
														<div class="row">
															<div class="col-md-4">
																<div class="card border-primary">
																	<div class="card-body">
																		<h6 class="card-title text-primary">
																			<i class="fas fa-chart-line me-2"></i>Performance Summary
																		</h6>
																		<ul class="list-unstyled">
																			<li class="mb-2">
																				<i class="fas fa-check-circle text-success me-2"></i>
																				Total Profit: <strong>$<?php echo number_format($total_profit, 2); ?></strong>
																			</li>
																			<li class="mb-2">
																				<i class="fas fa-percentage text-info me-2"></i>
																				Average ROI: <strong><?php echo number_format($roi_percentage, 2); ?>%</strong>
																			</li>
																			<li class="mb-2">
																				<i class="fas fa-tachometer-alt text-warning me-2"></i>
																				Success Rate: <strong><?php echo number_format($stats['avg_success_rate'] ?: 0, 1); ?>%</strong>
																			</li>
																		</ul>
																	</div>
																</div>
															</div>
															
															<div class="col-md-4">
																<div class="card border-success">
																	<div class="card-body">
																		<h6 class="card-title text-success">
																			<i class="fas fa-robot me-2"></i>Bot Insights
																		</h6>
																		<ul class="list-unstyled">
																			<li class="mb-2">
																				<i class="fas fa-users text-primary me-2"></i>
																				Active Traders: <strong><?php echo number_format($stats['active_traders'] ?: 0); ?></strong>
																			</li>
																			<li class="mb-2">
																				<i class="fas fa-play-circle text-success me-2"></i>
																				Active Bots: <strong><?php echo number_format($stats['active_subscriptions'] ?: 0); ?></strong>
																			</li>
																			<li class="mb-2">
																				<i class="fas fa-exchange-alt text-info me-2"></i>
																				Total Trades: <strong><?php echo number_format($stats['total_trades_executed'] ?: 0); ?></strong>
																			</li>
																		</ul>
																	</div>
																</div>
															</div>
															
															<div class="col-md-4">
																<div class="card border-warning">
																	<div class="card-body">
																		<h6 class="card-title text-warning">
																			<i class="fas fa-bullseye me-2"></i>Recommendations
																		</h6>
																		<ul class="list-unstyled">
																			<?php if ($roi_percentage > 20): ?>
																				<li class="mb-2">
																					<i class="fas fa-star text-warning me-2"></i>
																					<strong>Excellent Performance!</strong> Consider scaling successful strategies.
																				</li>
																			<?php endif; ?>
																			
																			<?php if (($stats['avg_success_rate'] ?: 0) < 70): ?>
																				<li class="mb-2">
																					<i class="fas fa-exclamation-triangle text-danger me-2"></i>
																					Consider reviewing trading strategies for improvement.
																				</li>
																			<?php endif; ?>
																			
																			<?php if (($stats['active_traders'] ?: 0) < 10): ?>
																				<li class="mb-2">
																					<i class="fas fa-user-plus text-info me-2"></i>
																					Focus on user acquisition to increase trading volume.
																				</li>
																			<?php endif; ?>
																			
																			<li class="mb-2">
																				<i class="fas fa-chart-bar text-primary me-2"></i>
																				Monitor daily P/L closely and adjust strategies as needed.
																			</li>
																		</ul>
																	</div>
																</div>
															</div>
														</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 -->
		
		<!-- Modal for Day Details -->
		<div class="modal fade" id="dayDetailsModal" tabindex="-1" aria-labelledby="dayDetailsModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="dayDetailsModalLabel">Daily Trading Details</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body" id="dayDetailsContent">
						<!-- Content will be loaded via JavaScript -->
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
					</div>
				</div>
			</div>
		</div>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- 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>
		
		<!-- Chart.js for visualizations -->
		<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
		
		<script>
		$(document).ready(function() {
			// Initialize DataTable
			$('#dailyTable').DataTable({
				"pageLength": 10,
				"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"
					}
				}
			});
			
			// Create Profit/Loss Chart
			createProfitLossChart();
		});
		
		// Function to view day details
		function viewDayDetails(date) {
			$.ajax({
				url: 'ajax/get_day_details.php',
				type: 'GET',
				data: {
					date: date,
					bot_plan: <?php echo $bot_plan; ?>,
					user_id: <?php echo $user_id; ?>,
					start_date: '<?php echo $start_date; ?>',
					end_date: '<?php echo $end_date; ?>'
				},
				success: function(data) {
					$('#dayDetailsContent').html(data);
					$('#dayDetailsModal').modal('show');
				}
			});
		}
		
		// Function to print report
		function printReport() {
			window.open('print_trading_report.php?start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&bot_plan=<?php echo $bot_plan; ?>&user_id=<?php echo $user_id; ?>', '_blank');
		}
		
		// Create Profit/Loss Chart
		function createProfitLossChart() {
			// This would be populated with actual data from your database
			// For now, it's a placeholder
			const ctx = document.createElement('canvas');
			ctx.id = 'profitLossChart';
			ctx.style.maxHeight = '300px';
			$('.box-body').first().append(ctx);
			
			const chart = new Chart(ctx, {
				type: 'line',
				data: {
					labels: ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5', 'Day 6', 'Day 7'],
					datasets: [{
						label: 'Profit',
						data: [1200, 1900, 3000, 5000, 2000, 3000, 4500],
						borderColor: 'rgb(75, 192, 192)',
						backgroundColor: 'rgba(75, 192, 192, 0.2)',
						tension: 0.1
					}, {
						label: 'Loss',
						data: [200, 400, 100, 300, 500, 200, 100],
						borderColor: 'rgb(255, 99, 132)',
						backgroundColor: 'rgba(255, 99, 132, 0.2)',
						tension: 0.1
					}]
				},
				options: {
					responsive: true,
					plugins: {
						legend: {
							position: 'top',
						},
						title: {
							display: true,
							text: '7-Day Profit/Loss Trend'
						}
					}
				}
			});
		}
		
		// Auto-refresh data every 5 minutes
		setInterval(function() {
			// Refresh the page to get updated data
			// You could also implement AJAX refresh for specific sections
			console.log('Auto-refresh triggered at ' + new Date().toLocaleTimeString());
			// Uncomment the next line to enable auto-refresh
			// location.reload();
		}, 300000); // 5 minutes
		</script>
		
		<style>
		.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;
		}
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		.card {
			border-radius: 10px;
			overflow: hidden;
		}
		.tab-content {
			padding: 20px;
			border: 1px solid #dee2e6;
			border-top: none;
			border-radius: 0 0 10px 10px;
		}
		.nav-tabs .nav-link.active {
			background-color: #fff;
			border-color: #dee2e6 #dee2e6 #fff;
		}
		</style>
		
	</body>
</html>