<?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';

// Default date range (last 30 days)
$default_start = date('Y-m-d', strtotime('-30 days'));
$default_end = date('Y-m-d');

// Get filter parameters
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : $default_start;
$date_to = isset($_GET['date_from']) ? $_GET['date_to'] : $default_end;
$report_type = isset($_GET['report_type']) ? $_GET['report_type'] : 'daily';
$group_by = isset($_GET['group_by']) ? $_GET['group_by'] : 'date';

// Validate dates
if (!empty($date_from) && !empty($date_to) && strtotime($date_from) > strtotime($date_to)) {
    $temp = $date_from;
    $date_from = $date_to;
    $date_to = $temp;
}

// Calculate totals
$total_revenue = 0;
$total_profit = 0;
$total_fees = 0;
$total_subscriptions = 0;
$total_deposits = 0;
$total_withdrawals = 0;

// Get subscription revenue
$sub_sql = "SELECT COALESCE(SUM(subscription_fee), 0) as total FROM user_bot_subscriptions 
            WHERE subscription_start BETWEEN '$date_from' AND '$date_to' 
            AND status = 'active'";
$sub_result = mysqli_query($conn, $sub_sql);
$sub_row = mysqli_fetch_assoc($sub_result);
$total_subscriptions = $sub_row['total'];

// Get deposit revenue
$deposit_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM deposits 
                WHERE status = 'confirmed' 
                AND DATE(created_at) BETWEEN '$date_from' AND '$date_to'";
$deposit_result = mysqli_query($conn, $deposit_sql);
$deposit_row = mysqli_fetch_assoc($deposit_result);
$total_deposits = $deposit_row['total'];

// Get withdrawal amounts
$withdrawal_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM withdrawals 
                   WHERE status = 'completed' 
                   AND DATE(created_at) BETWEEN '$date_from' AND '$date_to'";
$withdrawal_result = mysqli_query($conn, $withdrawal_sql);
$withdrawal_row = mysqli_fetch_assoc($withdrawal_result);
$total_withdrawals = $withdrawal_row['total'];

// Get trading profit
$profit_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM transactions 
               WHERE type = 'profit' AND status = 'completed' 
               AND DATE(date) BETWEEN '$date_from' AND '$date_to'";
$profit_result = mysqli_query($conn, $profit_sql);
$profit_row = mysqli_fetch_assoc($profit_result);
$total_profit = $profit_row['total'];

// Get fees
$fees_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM transactions 
             WHERE type = 'fee' AND status = 'completed' 
             AND DATE(date) BETWEEN '$date_from' AND '$date_to'";
$fees_result = mysqli_query($conn, $fees_sql);
$fees_row = mysqli_fetch_assoc($fees_result);
$total_fees = $fees_row['total'];

// Calculate total revenue
$total_revenue = $total_subscriptions + $total_deposits + $total_profit + $total_fees;

// Get revenue by bot plan
$plan_revenue_sql = "SELECT p.plan_name, p.plan_slug, COUNT(s.id) as subscriptions, 
                     COALESCE(SUM(p.subscription_fee), 0) as revenue
                     FROM trading_bot_plans p 
                     LEFT JOIN user_bot_subscriptions s ON p.id = s.bot_plan_id 
                     AND s.subscription_start BETWEEN '$date_from' AND '$date_to'
                     AND s.status = 'active'
                     WHERE p.is_active = 1
                     GROUP BY p.id
                     ORDER BY revenue DESC";
$plan_revenue_result = mysqli_query($conn, $plan_revenue_sql);

// Get daily revenue data for chart
$daily_sql = "SELECT DATE(created_at) as date, 
              SUM(CASE WHEN type = 'profit' THEN amount ELSE 0 END) as profit,
              SUM(CASE WHEN type = 'fee' THEN amount ELSE 0 END) as fees
              FROM transactions 
              WHERE status = 'completed' 
              AND DATE(created_at) BETWEEN '$date_from' AND '$date_to'
              GROUP BY DATE(created_at)
              ORDER BY date";
$daily_result = mysqli_query($conn, $daily_sql);

// Prepare chart data
$chart_labels = [];
$chart_profit = [];
$chart_fees = [];
$chart_deposits = [];

while ($row = mysqli_fetch_assoc($daily_result)) {
    $chart_labels[] = date('M d', strtotime($row['date']));
    $chart_profit[] = floatval($row['profit']);
    $chart_fees[] = floatval($row['fees']);
    
    // Get deposits for this day
    $deposit_day_sql = "SELECT COALESCE(SUM(amount), 0) as total FROM deposits 
                       WHERE status = 'confirmed' AND DATE(created_at) = '{$row['date']}'";
    $deposit_day_result = mysqli_query($conn, $deposit_day_sql);
    $deposit_day_row = mysqli_fetch_assoc($deposit_day_result);
    $chart_deposits[] = floatval($deposit_day_row['total']);
}

// Get top revenue users
$top_users_sql = "SELECT u.id, u.username, u.email, 
                  COALESCE(SUM(t.amount), 0) as total_spent,
                  COUNT(DISTINCT s.id) as subscriptions
                  FROM users u
                  LEFT JOIN transactions t ON u.id = t.user_id 
                  AND t.type IN ('fee', 'deposit') 
                  AND t.status = 'completed'
                  AND DATE(t.date) BETWEEN '$date_from' AND '$date_to'
                  LEFT JOIN user_bot_subscriptions s ON u.id = s.user_id 
                  AND s.subscription_start BETWEEN '$date_from' AND '$date_to'
                  WHERE u.status = 'verified'
                  GROUP BY u.id
                  HAVING total_spent > 0
                  ORDER BY total_spent DESC
                  LIMIT 10";
$top_users_result = mysqli_query($conn, $top_users_sql);

// Get monthly comparison
$current_month = date('Y-m');
$prev_month = date('Y-m', strtotime('-1 month'));

$current_month_sql = "SELECT 
                      COALESCE(SUM(CASE WHEN type = 'profit' THEN amount ELSE 0 END), 0) as profit,
                      COALESCE(SUM(CASE WHEN type = 'fee' THEN amount ELSE 0 END), 0) as fees
                      FROM transactions 
                      WHERE status = 'completed' 
                      AND DATE_FORMAT(date, '%Y-%m') = '$current_month'";
$current_month_result = mysqli_query($conn, $current_month_sql);
$current_month_row = mysqli_fetch_assoc($current_month_result);

$prev_month_sql = "SELECT 
                   COALESCE(SUM(CASE WHEN type = 'profit' THEN amount ELSE 0 END), 0) as profit,
                   COALESCE(SUM(CASE WHEN type = 'fee' THEN amount ELSE 0 END), 0) as fees
                   FROM transactions 
                   WHERE status = 'completed' 
                   AND DATE_FORMAT(date, '%Y-%m') = '$prev_month'";
$prev_month_result = mysqli_query($conn, $prev_month_sql);
$prev_month_row = mysqli_fetch_assoc($prev_month_result);

// Calculate growth
$profit_growth = 0;
$fees_growth = 0;

if ($prev_month_row['profit'] > 0) {
    $profit_growth = (($current_month_row['profit'] - $prev_month_row['profit']) / $prev_month_row['profit']) * 100;
}

if ($prev_month_row['fees'] > 0) {
    $fees_growth = (($current_month_row['fees'] - $prev_month_row['fees']) / $prev_month_row['fees']) * 100;
}
?>

<!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-bar me-2"></i>Revenue Report</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" onclick="exportRevenue()">
												<i class="fas fa-download me-1"></i> Export Report
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-8">
												<form method="GET" class="row">
													<div class="col-md-3">
														<div class="form-group">
															<label>Date From</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>Date To</label>
															<input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<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>
													<div class="col-md-3">
														<div class="form-group">
															<label>&nbsp;</label>
															<div>
																<button type="submit" class="btn btn-primary"><i class="fas fa-filter me-1"></i> Apply</button>
																<a href="revenue.php" class="btn btn-secondary">Reset</a>
															</div>
														</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-primary pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Total Revenue</h5>
																<h2 class="text-white fw-500 mb-0">$<?php echo number_format($total_revenue, 2); ?></h2>
																<p class="text-white-50 mb-0">Period: <?php echo date('M d', strtotime($date_from)); ?> - <?php echo date('M d', strtotime($date_to)); ?></p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-money-bill-wave fa-2x text-white"></i>
															</div>
														</div>
													</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">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Trading Profit</h5>
																<h2 class="text-white fw-500 mb-0">$<?php echo number_format($total_profit, 2); ?></h2>
																<p class="text-white-50 mb-0">
																	Growth: 
																	<span class="<?php echo $profit_growth >= 0 ? 'text-success' : 'text-danger'; ?>">
																		<?php echo number_format($profit_growth, 1); ?>%
																	</span>
																</p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-chart-line fa-2x text-white"></i>
															</div>
														</div>
													</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">Subscription Fees</h5>
																<h2 class="text-white fw-500 mb-0">$<?php echo number_format($total_subscriptions, 2); ?></h2>
																<p class="text-white-50 mb-0">Active subscriptions</p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-robot fa-2x text-white"></i>
															</div>
														</div>
													</div>
												</div>
											</div>
											
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-info pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Total Deposits</h5>
																<h2 class="text-white fw-500 mb-0">$<?php echo number_format($total_deposits, 2); ?></h2>
																<p class="text-white-50 mb-0">Withdrawals: $<?php echo number_format($total_withdrawals, 2); ?></p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-download fa-2x text-white"></i>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Revenue Chart -->
										<div class="row mb-20">
											<div class="col-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-area me-2"></i>Revenue Trend</h5>
														<div class="dropdown">
															<button class="btn btn-light btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown">
																View
															</button>
															<div class="dropdown-menu">
																<a class="dropdown-item" href="javascript:void(0)" onclick="updateChart('profit')">Trading Profit</a>
																<a class="dropdown-item" href="javascript:void(0)" onclick="updateChart('fees')">Fees</a>
																<a class="dropdown-item" href="javascript:void(0)" onclick="updateChart('deposits')">Deposits</a>
																<a class="dropdown-item" href="javascript:void(0)" onclick="updateChart('all')">All Revenue</a>
															</div>
														</div>
													</div>
													<div class="box-body">
														<div id="revenueChart" style="height: 300px;"></div>
													</div>
												</div>
											</div>
										</div>
										
										<div class="row">
											<!-- Revenue by Bot Plan -->
											<div class="col-xl-6 col-lg-6">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-robot me-2"></i>Revenue by Bot Plan</h5>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover">
																<thead>
																	<tr>
																		<th>Plan</th>
																		<th>Subscriptions</th>
																		<th>Revenue</th>
																		<th>Percentage</th>
																	</tr>
																</thead>
																<tbody>
																	<?php 
																	$plan_total = 0;
																	while ($plan = mysqli_fetch_assoc($plan_revenue_result)): 
																		$plan_total += $plan['revenue'];
																	?>
																	<tr>
																		<td>
																			<div class="d-flex align-items-center">
																				<div class="me-10">
																					<div class="bg-primary rounded-circle w-30 h-30 d-flex align-items-center justify-content-center">
																						<i class="fas fa-robot text-white"></i>
																					</div>
																				</div>
																				<div>
																					<p class="mb-0 fw-500"><?php echo htmlspecialchars($plan['plan_name']); ?></p>
																					<small class="text-mute"><?php echo $plan['plan_slug']; ?></small>
																				</div>
																			</div>
																		</td>
																		<td><?php echo $plan['subscriptions']; ?></td>
																		<td class="fw-500">$<?php echo number_format($plan['revenue'], 2); ?></td>
																		<td>
																			<?php if ($total_subscriptions > 0): ?>
																				<?php $percentage = ($plan['revenue'] / $total_subscriptions) * 100; ?>
																				<div class="progress" style="height: 20px;">
																					<div class="progress-bar bg-success" style="width: <?php echo $percentage; ?>%">
																						<?php echo number_format($percentage, 1); ?>%
																					</div>
																				</div>
																			<?php endif; ?>
																		</td>
																	</tr>
																	<?php endwhile; ?>
																	
																	<tr class="bg-light">
																		<td><strong>Total</strong></td>
																		<td><strong><?php echo mysqli_num_rows($plan_revenue_result); ?></strong></td>
																		<td class="fw-500"><strong>$<?php echo number_format($plan_total, 2); ?></strong></td>
																		<td>100%</td>
																	</tr>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
											
											<!-- Top Revenue Users -->
											<div class="col-xl-6 col-lg-6">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-users me-2"></i>Top Revenue Users</h5>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover">
																<thead>
																	<tr>
																		<th>User</th>
																		<th>Subscriptions</th>
																		<th>Total Spent</th>
																		<th>Status</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($top_users_result) > 0): ?>
																		<?php while ($user = mysqli_fetch_assoc($top_users_result)): ?>
																		<tr>
																			<td>
																				<div class="d-flex align-items-center">
																					<div class="me-10">
																						<div class="bg-primary rounded-circle w-30 h-30 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><?php echo $user['subscriptions']; ?></td>
																			<td class="fw-500 text-success">$<?php echo number_format($user['total_spent'], 2); ?></td>
																			<td>
																				<a href="view_user.php?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-light">
																					<i class="fas fa-eye"></i> View
																				</a>
																			</td>
																		</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="4" class="text-center py-20">
																				<i class="fas fa-users fa-2x text-mute mb-3"></i>
																				<h5>No revenue data</h5>
																				<p class="text-mute">No users have made purchases in this period</p>
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Detailed Revenue Breakdown -->
										<div class="row mt-20">
											<div class="col-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-list-alt me-2"></i>Detailed Revenue Breakdown</h5>
													</div>
													<div class="box-body">
														<div class="row">
															<div class="col-md-6">
																<div class="table-responsive">
																	<table class="table table-sm">
																		<thead>
																			<tr class="bg-light">
																				<th colspan="2">Revenue Sources</th>
																			</tr>
																		</thead>
																		<tbody>
																			<tr>
																				<td><i class="fas fa-robot text-primary me-2"></i> Bot Subscriptions</td>
																				<td class="text-end fw-500">$<?php echo number_format($total_subscriptions, 2); ?></td>
																			</tr>
																			<tr>
																				<td><i class="fas fa-chart-line text-success me-2"></i> Trading Profit</td>
																				<td class="text-end fw-500">$<?php echo number_format($total_profit, 2); ?></td>
																			</tr>
																			<tr>
																				<td><i class="fas fa-file-invoice text-warning me-2"></i> Transaction Fees</td>
																				<td class="text-end fw-500">$<?php echo number_format($total_fees, 2); ?></td>
																			</tr>
																			<tr>
																				<td><i class="fas fa-download text-info me-2"></i> User Deposits</td>
																				<td class="text-end fw-500">$<?php echo number_format($total_deposits, 2); ?></td>
																			</tr>
																			<tr class="bg-light">
																				<td><strong>Total Revenue</strong></td>
																				<td class="text-end fw-500"><strong>$<?php echo number_format($total_revenue, 2); ?></strong></td>
																			</tr>
																		</tbody>
																	</table>
																</div>
															</div>
															
															<div class="col-md-6">
																<div class="table-responsive">
																	<table class="table table-sm">
																		<thead>
																			<tr class="bg-light">
																				<th colspan="2">Monthly Comparison</th>
																			</tr>
																		</thead>
																		<tbody>
																			<tr>
																				<td>Current Month (<?php echo date('F Y'); ?>)</td>
																				<td class="text-end">
																					<span class="badge bg-success">$<?php echo number_format($current_month_row['profit'], 2); ?></span>
																				</td>
																			</tr>
																			<tr>
																				<td>Previous Month (<?php echo date('F Y', strtotime('-1 month')); ?>)</td>
																				<td class="text-end">
																					<span class="badge bg-secondary">$<?php echo number_format($prev_month_row['profit'], 2); ?></span>
																				</td>
																			</tr>
																			<tr>
																				<td>Profit Growth</td>
																				<td class="text-end">
																					<span class="badge bg-<?php echo $profit_growth >= 0 ? 'success' : 'danger'; ?>">
																						<?php echo $profit_growth >= 0 ? '+' : ''; ?><?php echo number_format($profit_growth, 1); ?>%
																					</span>
																				</td>
																			</tr>
																			<tr>
																				<td>Fees Growth</td>
																				<td class="text-end">
																					<span class="badge bg-<?php echo $fees_growth >= 0 ? 'success' : 'danger'; ?>">
																						<?php echo $fees_growth >= 0 ? '+' : ''; ?><?php echo number_format($fees_growth, 1); ?>%
																					</span>
																				</td>
																			</tr>
																			<tr class="bg-light">
																				<td><strong>Net Profit (Estimate)</strong></td>
																				<td class="text-end fw-500">
																					<strong class="text-success">$<?php echo number_format($total_profit + $total_fees + $total_subscriptions - $total_withdrawals, 2); ?></strong>
																				</td>
																			</tr>
																		</tbody>
																	</table>
																</div>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Revenue Statistics -->
										<div class="row mt-20">
											<div class="col-md-4">
												<div class="box">
													<div class="box-body text-center">
														<div class="mb-3">
															<i class="fas fa-calendar-alt fa-3x text-primary"></i>
														</div>
														<h3 class="fw-500"><?php echo number_format($total_revenue / max(1, (strtotime($date_to) - strtotime($date_from)) / (60*60*24)), 2); ?></h3>
														<p class="text-mute mb-0">Daily Average Revenue</p>
													</div>
												</div>
											</div>
											
											<div class="col-md-4">
												<div class="box">
													<div class="box-body text-center">
														<div class="mb-3">
															<i class="fas fa-user-check fa-3x text-success"></i>
														</div>
														<h3 class="fw-500">$<?php echo number_format($total_subscriptions / max(1, mysqli_num_rows($plan_revenue_result)), 2); ?></h3>
														<p class="text-mute mb-0">Average Subscription Value</p>
													</div>
												</div>
											</div>
											
											<div class="col-md-4">
												<div class="box">
													<div class="box-body text-center">
														<div class="mb-3">
															<i class="fas fa-percentage fa-3x text-warning"></i>
														</div>
														<h3 class="fw-500"><?php echo $total_deposits > 0 ? number_format(($total_profit / $total_deposits) * 100, 1) : '0'; ?>%</h3>
														<p class="text-mute mb-0">Profit to Deposit Ratio</p>
													</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') ?>
		
		<!-- Apex Charts -->
		<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
		
		<script>
		let revenueChart;
		let currentChartType = 'all';
		
		$(document).ready(function() {
			// Initialize revenue chart
			initRevenueChart();
			
			// Auto-refresh every 5 minutes
			setInterval(function() {
				updateRevenueStats();
			}, 300000); // 5 minutes
		});
		
		// Initialize Revenue Chart
		function initRevenueChart() {
			var options = {
				series: [
					{
						name: 'Trading Profit',
						data: <?php echo json_encode($chart_profit); ?>,
						color: '#28a745'
					},
					{
						name: 'Fees',
						data: <?php echo json_encode($chart_fees); ?>,
						color: '#ffc107'
					},
					{
						name: 'Deposits',
						data: <?php echo json_encode($chart_deposits); ?>,
						color: '#17a2b8'
					}
				],
				chart: {
					type: 'area',
					height: 300,
					toolbar: {
						show: true,
						tools: {
							download: true,
							selection: true,
							zoom: true,
							zoomin: true,
							zoomout: true,
							pan: true,
							reset: true
						}
					}
				},
				dataLabels: {
					enabled: false
				},
				stroke: {
					curve: 'smooth',
					width: 2
				},
				fill: {
					type: 'gradient',
					gradient: {
						shadeIntensity: 1,
						opacityFrom: 0.7,
						opacityTo: 0.3,
						stops: [0, 90, 100]
					}
				},
				xaxis: {
					categories: <?php echo json_encode($chart_labels); ?>,
					labels: {
						style: {
							colors: '#8c8c8c'
						}
					}
				},
				yaxis: {
					labels: {
						formatter: function(value) {
							return '$' + value.toFixed(2);
						},
						style: {
							colors: '#8c8c8c'
						}
					}
				},
				legend: {
					position: 'top',
					horizontalAlign: 'right'
				},
				grid: {
					borderColor: '#f1f1f1'
				},
				tooltip: {
					y: {
						formatter: function(value) {
							return '$' + value.toFixed(2);
						}
					}
				}
			};
			
			revenueChart = new ApexCharts(document.querySelector("#revenueChart"), options);
			revenueChart.render();
		}
		
		// Update Chart View
		function updateChart(type) {
			currentChartType = type;
			
			// You would typically fetch new data from the server here
			// For now, we'll just toggle series visibility
			switch(type) {
				case 'profit':
					revenueChart.updateSeries([
						{ data: <?php echo json_encode($chart_profit); ?> },
						{ data: [] },
						{ data: [] }
					]);
					break;
				case 'fees':
					revenueChart.updateSeries([
						{ data: [] },
						{ data: <?php echo json_encode($chart_fees); ?> },
						{ data: [] }
					]);
					break;
				case 'deposits':
					revenueChart.updateSeries([
						{ data: [] },
						{ data: [] },
						{ data: <?php echo json_encode($chart_deposits); ?> }
					]);
					break;
				case 'all':
					revenueChart.updateSeries([
						{ data: <?php echo json_encode($chart_profit); ?> },
						{ data: <?php echo json_encode($chart_fees); ?> },
						{ data: <?php echo json_encode($chart_deposits); ?> }
					]);
					break;
			}
		}
		
		// Update Revenue Stats
		function updateRevenueStats() {
			$.ajax({
				url: 'ajax/get_revenue_stats.php',
				type: 'GET',
				data: {
					date_from: '<?php echo $date_from; ?>',
					date_to: '<?php echo $date_to; ?>'
				},
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update summary cards
						$('.bg-gradient-primary .fw-500').text('$' + stats.total_revenue);
						$('.bg-gradient-success .fw-500').text('$' + stats.total_profit);
						$('.bg-gradient-warning .fw-500').text('$' + stats.total_subscriptions);
						$('.bg-gradient-info .fw-500').text('$' + stats.total_deposits);
						
						// Update detailed breakdown
						$('.table-sm td:contains("Bot Subscriptions")').next().text('$' + stats.total_subscriptions);
						$('.table-sm td:contains("Trading Profit")').next().text('$' + stats.total_profit);
						$('.table-sm td:contains("Transaction Fees")').next().text('$' + stats.total_fees);
						$('.table-sm td:contains("User Deposits")').next().text('$' + stats.total_deposits);
						$('.table-sm td:contains("Total Revenue")').next().text('$' + stats.total_revenue);
						$('.table-sm td:contains("Net Profit (Estimate)")').next().text('$' + stats.net_profit);
						
						// Show notification
						Swal.fire({
							toast: true,
							position: 'top-end',
							icon: 'success',
							title: 'Revenue Stats Updated',
							showConfirmButton: false,
							timer: 1500
						});
					}
				}
			});
		}
		
		// Export Revenue Report
		function exportRevenue() {
			var date_from = $('input[name="date_from"]').val();
			var date_to = $('input[name="date_to"]').val();
			var report_type = $('select[name="report_type"]').val();
			
			var url = 'export_revenue.php?date_from=' + date_from + 
					 '&date_to=' + date_to + 
					 '&report_type=' + report_type;
			
			window.open(url, '_blank');
		}
		
		// Print Report
		function printReport() {
			window.print();
		}
		</script>
		
		<style>
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		.bg-white-20 {
			background-color: rgba(255, 255, 255, 0.2);
		}
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
		}
		.box {
			border-radius: 10px;
			overflow: hidden;
		}
		</style>
		
	</body>
</html>