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

// Default date range (current month)
$current_month = date('Y-m');
$default_from = date('Y-m-01');
$default_to = date('Y-m-t');

// Get filter parameters
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : $default_from;
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : $default_to;
$report_type = isset($_GET['report_type']) ? $_GET['report_type'] : 'overview';

// Validate dates
if ($date_from > $date_to) {
    $temp = $date_from;
    $date_from = $date_to;
    $date_to = $temp;
}

// Calculate date differences
$days_diff = floor((strtotime($date_to) - strtotime($date_from)) / (60 * 60 * 24)) + 1;

// Get financial summary data
function getFinancialSummary($conn, $date_from, $date_to) {
    $summary = array();
    
    // Total Revenue (Subscription fees + Deposits)
    $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'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $summary['subscription_revenue'] = $row['total'];
    
    $sql = "SELECT COALESCE(SUM(amount), 0) as total FROM deposits 
            WHERE created_at BETWEEN '$date_from' AND '$date_to' AND status = 'confirmed'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $summary['deposit_revenue'] = $row['total'];
    
    $summary['total_revenue'] = $summary['subscription_revenue'] + $summary['deposit_revenue'];
    
    // Total Expenses (Withdrawals + Fees)
    $sql = "SELECT COALESCE(SUM(amount), 0) as total FROM withdrawals 
            WHERE created_at BETWEEN '$date_from' AND '$date_to' AND status = 'completed'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $summary['withdrawal_expenses'] = $row['total'];
    
    $sql = "SELECT COALESCE(SUM(fee), 0) as total FROM withdrawals 
            WHERE created_at BETWEEN '$date_from' AND '$date_to' AND status = 'completed'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $summary['fee_income'] = $row['total'];
    
    // Total Profit from trading
    $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'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $summary['trading_profit'] = $row['total'];
    
    // Net Profit
    $summary['net_profit'] = $summary['total_revenue'] + $summary['fee_income'] + $summary['trading_profit'] - $summary['withdrawal_expenses'];
    
    // Get daily data for charts
    $summary['daily_data'] = getDailyFinancialData($conn, $date_from, $date_to);
    
    // Get subscription breakdown
    $summary['subscription_breakdown'] = getSubscriptionBreakdown($conn, $date_from, $date_to);
    
    // Get top revenue users
    $summary['top_users'] = getTopRevenueUsers($conn, $date_from, $date_to);
    
    return $summary;
}

function getDailyFinancialData($conn, $date_from, $date_to) {
    $data = array();
    
    // Generate all dates in range
    $current = strtotime($date_from);
    $end = strtotime($date_to);
    
    while ($current <= $end) {
        $date = date('Y-m-d', $current);
        $data[$date] = array(
            'date' => date('M d', $current),
            'revenue' => 0,
            'expenses' => 0,
            'profit' => 0,
            'subscriptions' => 0,
            'deposits' => 0,
            'withdrawals' => 0
        );
        $current = strtotime('+1 day', $current);
    }
    
    // Get daily revenue (subscriptions)
    $sql = "SELECT DATE(subscription_start) as date, COUNT(*) as count, SUM(subscription_fee) as amount 
            FROM user_bot_subscriptions 
            WHERE subscription_start BETWEEN '$date_from' AND '$date_to' AND status = 'active'
            GROUP BY DATE(subscription_start)";
    $result = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_assoc($result)) {
        if (isset($data[$row['date']])) {
            $data[$row['date']]['subscriptions'] = $row['count'];
            $data[$row['date']]['revenue'] += $row['amount'];
        }
    }
    
    // Get daily deposits
    $sql = "SELECT DATE(created_at) as date, COUNT(*) as count, SUM(amount) as amount 
            FROM deposits 
            WHERE created_at BETWEEN '$date_from' AND '$date_to' AND status = 'confirmed'
            GROUP BY DATE(created_at)";
    $result = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_assoc($result)) {
        if (isset($data[$row['date']])) {
            $data[$row['date']]['deposits'] = $row['count'];
            $data[$row['date']]['revenue'] += $row['amount'];
        }
    }
    
    // Get daily withdrawals
    $sql = "SELECT DATE(created_at) as date, COUNT(*) as count, SUM(amount) as amount 
            FROM withdrawals 
            WHERE created_at BETWEEN '$date_from' AND '$date_to' AND status = 'completed'
            GROUP BY DATE(created_at)";
    $result = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_assoc($result)) {
        if (isset($data[$row['date']])) {
            $data[$row['date']]['withdrawals'] = $row['count'];
            $data[$row['date']]['expenses'] += $row['amount'];
        }
    }
    
    // Get daily profit
    $sql = "SELECT DATE(date) as date, SUM(amount) as amount 
            FROM transactions 
            WHERE type = 'profit' AND status = 'completed' 
            AND DATE(date) BETWEEN '$date_from' AND '$date_to'
            GROUP BY DATE(date)";
    $result = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_assoc($result)) {
        if (isset($data[$row['date']])) {
            $data[$row['date']]['profit'] = $row['amount'];
        }
    }
    
    return array_values($data);
}

function getSubscriptionBreakdown($conn, $date_from, $date_to) {
    $breakdown = array();
    
    $sql = "SELECT p.plan_name, COUNT(s.id) as count, SUM(p.subscription_fee) 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";
    
    $result = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_assoc($result)) {
        $breakdown[] = $row;
    }
    
    return $breakdown;
}

function getTopRevenueUsers($conn, $date_from, $date_to, $limit = 10) {
    $users = array();
    
    $sql = "SELECT u.id, u.username, u.email,
            (SELECT COALESCE(SUM(p.subscription_fee), 0) 
             FROM user_bot_subscriptions s 
             JOIN trading_bot_plans p ON s.bot_plan_id = p.id
             WHERE s.user_id = u.id 
             AND s.subscription_start BETWEEN '$date_from' AND '$date_to'
             AND s.status = 'active') as subscription_revenue,
            (SELECT COALESCE(SUM(amount), 0) 
             FROM deposits 
             WHERE user_id = u.id 
             AND created_at BETWEEN '$date_from' AND '$date_to'
             AND status = 'confirmed') as deposit_amount,
            (SELECT COALESCE(SUM(amount), 0) 
             FROM withdrawals 
             WHERE user_id = u.id 
             AND created_at BETWEEN '$date_from' AND '$date_to'
             AND status = 'completed') as withdrawal_amount
            FROM users u
            WHERE u.status = 'verified'
            HAVING (subscription_revenue + deposit_amount) > 0
            ORDER BY (subscription_revenue + deposit_amount) DESC
            LIMIT $limit";
    
    $result = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_assoc($result)) {
        $row['total_revenue'] = $row['subscription_revenue'] + $row['deposit_amount'];
        $users[] = $row;
    }
    
    return $users;
}

// Get financial data
$financial_data = getFinancialSummary($conn, $date_from, $date_to);

// Format numbers
function format_money($amount) {
    return '$' . number_format($amount, 2);
}

function format_percent($value, $total) {
    if ($total == 0) return '0.00%';
    return number_format(($value / $total) * 100, 2) . '%';
}
?>

<!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">
										<div class="d-flex justify-content-between align-items-center">
											<div>
												<h4 class="box-title"><i class="fas fa-chart-pie me-2"></i>Financial Summary</h4>
												<p class="mb-0 text-mute">Comprehensive financial analysis and reporting</p>
											</div>
											<div class="dropdown">
												<button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
													<i class="fas fa-download me-1"></i> Export Report
												</button>
												<div class="dropdown-menu">
													<a class="dropdown-item" href="#" onclick="exportReport('pdf')"><i class="fas fa-file-pdf"></i> PDF Report</a>
													<a class="dropdown-item" href="#" onclick="exportReport('excel')"><i class="fas fa-file-excel"></i> Excel Sheet</a>
													<a class="dropdown-item" href="#" onclick="exportReport('csv')"><i class="fas fa-file-csv"></i> CSV Data</a>
												</div>
											</div>
										</div>
									</div>
									<div class="box-body">
										<!-- Date Range Filter -->
										<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 class="form-label">Date From</label>
															<input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>" required>
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">Date To</label>
															<input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>" required>
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">Report Type</label>
															<select class="form-control" name="report_type" onchange="this.form.submit()">
																<option value="overview" <?php echo $report_type == 'overview' ? 'selected' : ''; ?>>Overview</option>
																<option value="detailed" <?php echo $report_type == 'detailed' ? 'selected' : ''; ?>>Detailed</option>
																<option value="comparison" <?php echo $report_type == 'comparison' ? 'selected' : ''; ?>>Comparison</option>
															</select>
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">&nbsp;</label>
															<div>
																<button type="submit" class="btn btn-primary"><i class="fas fa-filter me-1"></i> Apply Filter</button>
																<a href="financial_summary.php" class="btn btn-secondary">Reset</a>
															</div>
														</div>
													</div>
												</form>
											</div>
											<div class="col-md-4">
												<div class="alert alert-info">
													<div class="d-flex justify-content-between">
														<div>
															<i class="fas fa-calendar-alt me-2"></i>
															<strong>Period:</strong> <?php echo date('M d, Y', strtotime($date_from)); ?> - <?php echo date('M d, Y', strtotime($date_to)); ?>
														</div>
														<div>
															<strong><?php echo $days_diff; ?> days</strong>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Summary Cards -->
										<div class="row">
											<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 format_money($financial_data['total_revenue']); ?></h2>
																<p class="text-white-50 mb-0">All income sources</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 class="mt-20">
															<div class="d-flex justify-content-between">
																<span class="text-white-50">Subscriptions</span>
																<span class="text-white-50"><?php echo format_money($financial_data['subscription_revenue']); ?></span>
															</div>
															<div class="d-flex justify-content-between">
																<span class="text-white-50">Deposits</span>
																<span class="text-white-50"><?php echo format_money($financial_data['deposit_revenue']); ?></span>
															</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">Net Profit</h5>
																<h2 class="text-white fw-500 mb-0"><?php echo format_money($financial_data['net_profit']); ?></h2>
																<p class="text-white-50 mb-0">After all expenses</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 class="mt-20">
															<div class="d-flex justify-content-between">
																<span class="text-white-50">Trading Profit</span>
																<span class="text-white-50"><?php echo format_money($financial_data['trading_profit']); ?></span>
															</div>
															<div class="d-flex justify-content-between">
																<span class="text-white-50">Fee Income</span>
																<span class="text-white-50"><?php echo format_money($financial_data['fee_income']); ?></span>
															</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">Total Expenses</h5>
																<h2 class="text-white fw-500 mb-0"><?php echo format_money($financial_data['withdrawal_expenses']); ?></h2>
																<p class="text-white-50 mb-0">User withdrawals</p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-upload fa-2x text-white"></i>
															</div>
														</div>
														<div class="mt-20">
															<div class="d-flex justify-content-between">
																<span class="text-white-50">Daily Avg.</span>
																<span class="text-white-50"><?php echo format_money($days_diff > 0 ? $financial_data['withdrawal_expenses'] / $days_diff : 0); ?></span>
															</div>
															<div class="d-flex justify-content-between">
																<span class="text-white-50">Per User</span>
																<span class="text-white-50">
																	<?php
																	$user_count = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as total FROM users WHERE status = 'verified'"))['total'];
																	echo format_money($user_count > 0 ? $financial_data['withdrawal_expenses'] / $user_count : 0);
																	?>
																</span>
															</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">Profit Margin</h5>
																<h2 class="text-white fw-500 mb-0">
																	<?php
																	$margin = $financial_data['total_revenue'] > 0 ? ($financial_data['net_profit'] / $financial_data['total_revenue']) * 100 : 0;
																	echo number_format($margin, 2) . '%';
																	?>
																</h2>
																<p class="text-white-50 mb-0">Net profit / Revenue</p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-percentage fa-2x text-white"></i>
															</div>
														</div>
														<div class="mt-20">
															<div class="d-flex justify-content-between">
																<span class="text-white-50">Daily Revenue</span>
																<span class="text-white-50"><?php echo format_money($days_diff > 0 ? $financial_data['total_revenue'] / $days_diff : 0); ?></span>
															</div>
															<div class="d-flex justify-content-between">
																<span class="text-white-50">Daily Profit</span>
																<span class="text-white-50"><?php echo format_money($days_diff > 0 ? $financial_data['net_profit'] / $days_diff : 0); ?></span>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Charts Section -->
										<div class="row mt-20">
											<div class="col-xl-8 col-lg-6">
												<div class="box b-1">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-bar me-2"></i>Revenue & Expenses Trend</h5>
														<div class="dropdown">
															<button class="btn btn-sm btn-light dropdown-toggle" type="button" data-bs-toggle="dropdown">
																Daily
															</button>
															<div class="dropdown-menu">
																<a class="dropdown-item" href="javascript:void(0)" onclick="changeChartView('daily')">Daily View</a>
																<a class="dropdown-item" href="javascript:void(0)" onclick="changeChartView('weekly')">Weekly View</a>
																<a class="dropdown-item" href="javascript:void(0)" onclick="changeChartView('monthly')">Monthly View</a>
															</div>
														</div>
													</div>
													<div class="box-body">
														<div id="revenueExpenseChart" style="height: 300px;"></div>
													</div>
												</div>
											</div>
											
											<div class="col-xl-4 col-lg-6">
												<div class="box b-1">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-pie me-2"></i>Revenue Breakdown</h5>
													</div>
													<div class="box-body">
														<div id="revenueBreakdownChart" style="height: 300px;"></div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Detailed Tables -->
										<div class="row mt-20">
											<!-- Subscription Breakdown -->
											<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>Subscription Revenue by 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>
																		<th>Avg. Value</th>
																	</tr>
																</thead>
																<tbody>
																	<?php 
																	$total_subs = 0;
																	$total_rev = 0;
																	foreach ($financial_data['subscription_breakdown'] as $plan): 
																		$total_subs += $plan['count'];
																		$total_rev += $plan['revenue'];
																	endforeach;
																	?>
																	
																	<?php foreach ($financial_data['subscription_breakdown'] as $plan): ?>
																		<?php if ($plan['count'] > 0): ?>
																			<tr>
																				<td><?php echo htmlspecialchars($plan['plan_name']); ?></td>
																				<td><?php echo $plan['count']; ?></td>
																				<td class="fw-500"><?php echo format_money($plan['revenue']); ?></td>
																				<td>
																					<div class="d-flex align-items-center">
																						<div class="progress flex-grow-1 me-2" style="height: 6px;">
																							<div class="progress-bar bg-primary" style="width: <?php echo $total_rev > 0 ? ($plan['revenue'] / $total_rev * 100) : 0; ?>%"></div>
																						</div>
																						<span><?php echo format_percent($plan['revenue'], $total_rev); ?></span>
																					</div>
																				</td>
																				<td><?php echo format_money($plan['count'] > 0 ? $plan['revenue'] / $plan['count'] : 0); ?></td>
																			</tr>
																		<?php endif; ?>
																	<?php endforeach; ?>
																	
																	<tr class="bg-light fw-500">
																		<td>Total</td>
																		<td><?php echo $total_subs; ?></td>
																		<td><?php echo format_money($total_rev); ?></td>
																		<td>100%</td>
																		<td><?php echo format_money($total_subs > 0 ? $total_rev / $total_subs : 0); ?></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>
														<small class="text-mute">Users generating highest revenue</small>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover">
																<thead>
																	<tr>
																		<th>User</th>
																		<th>Subscriptions</th>
																		<th>Deposits</th>
																		<th>Withdrawals</th>
																		<th>Net Revenue</th>
																		<th>Action</th>
																	</tr>
																</thead>
																<tbody>
																	<?php foreach ($financial_data['top_users'] as $user): ?>
																		<tr>
																			<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 class="fw-500 text-primary"><?php echo format_money($user['subscription_revenue']); ?></td>
																			<td class="fw-500 text-success"><?php echo format_money($user['deposit_amount']); ?></td>
																			<td class="fw-500 text-danger"><?php echo format_money($user['withdrawal_amount']); ?></td>
																			<td class="fw-500">
																				<span class="badge bg-<?php echo $user['total_revenue'] > 1000 ? 'success' : 'info'; ?>">
																					<?php echo format_money($user['total_revenue']); ?>
																				</span>
																			</td>
																			<td>
																				<a href="view_user.php?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-light">
																					<i class="fas fa-eye"></i>
																				</a>
																			</td>
																		</tr>
																	<?php endforeach; ?>
																	
																	<?php if (empty($financial_data['top_users'])): ?>
																		<tr>
																			<td colspan="6" class="text-center py-20">
																				<i class="fas fa-users fa-2x text-mute mb-3"></i>
																				<p class="text-mute">No revenue data available for this period</p>
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Daily Financial Data -->
										<div class="row mt-20">
											<div class="col-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-calendar-day me-2"></i>Daily Financial Activity</h5>
														<small class="text-mute">Day-by-day breakdown</small>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-bordered table-hover" id="dailyDataTable">
																<thead class="bg-light">
																	<tr>
																		<th>Date</th>
																		<th>Revenue</th>
																		<th>Expenses</th>
																		<th>Profit</th>
																		<th>Subscriptions</th>
																		<th>Deposits</th>
																		<th>Withdrawals</th>
																		<th>Net</th>
																	</tr>
																</thead>
																<tbody>
																	<?php foreach ($financial_data['daily_data'] as $day): ?>
																		<?php
																		$net = $day['revenue'] + $day['profit'] - $day['expenses'];
																		$net_class = $net >= 0 ? 'text-success' : 'text-danger';
																		?>
																		<tr>
																			<td><strong><?php echo $day['date']; ?></strong></td>
																			<td class="text-success fw-500"><?php echo format_money($day['revenue']); ?></td>
																			<td class="text-danger fw-500"><?php echo format_money($day['expenses']); ?></td>
																			<td class="text-primary fw-500"><?php echo format_money($day['profit']); ?></td>
																			<td><?php echo $day['subscriptions']; ?></td>
																			<td><?php echo $day['deposits']; ?></td>
																			<td><?php echo $day['withdrawals']; ?></td>
																			<td class="fw-500 <?php echo $net_class; ?>"><?php echo format_money($net); ?></td>
																		</tr>
																	<?php endforeach; ?>
																</tbody>
																<tfoot class="bg-light">
																	<tr>
																		<th>Total</th>
																		<th class="text-success"><?php echo format_money($financial_data['total_revenue']); ?></th>
																		<th class="text-danger"><?php echo format_money($financial_data['withdrawal_expenses']); ?></th>
																		<th class="text-primary"><?php echo format_money($financial_data['trading_profit']); ?></th>
																		<th>
																			<?php
																			$total_subs = array_sum(array_column($financial_data['daily_data'], 'subscriptions'));
																			echo $total_subs;
																			?>
																		</th>
																		<th>
																			<?php
																			$total_deps = array_sum(array_column($financial_data['daily_data'], 'deposits'));
																			echo $total_deps;
																			?>
																		</th>
																		<th>
																			<?php
																			$total_with = array_sum(array_column($financial_data['daily_data'], 'withdrawals'));
																			echo $total_with;
																			?>
																		</th>
																		<th class="<?php echo $financial_data['net_profit'] >= 0 ? 'text-success' : 'text-danger'; ?>">
																			<?php echo format_money($financial_data['net_profit']); ?>
																		</th>
																	</tr>
																</tfoot>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Key Metrics -->
										<div class="row mt-20">
											<div class="col-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-bar me-2"></i>Key Performance Indicators</h5>
													</div>
													<div class="box-body">
														<div class="row">
															<div class="col-md-3">
																<div class="text-center p-3">
																	<div class="bg-primary-light rounded-circle w-60 h-60 mx-auto d-flex align-items-center justify-content-center mb-3">
																		<i class="fas fa-dollar-sign fa-2x text-primary"></i>
																	</div>
																	<h3 class="fw-500"><?php echo format_money($financial_data['total_revenue']); ?></h3>
																	<p class="text-mute mb-0">Total Revenue</p>
																	<small class="text-success">
																		<i class="fas fa-arrow-up me-1"></i> 
																		<?php echo format_money($days_diff > 0 ? $financial_data['total_revenue'] / $days_diff : 0); ?> daily
																	</small>
																</div>
															</div>
															
															<div class="col-md-3">
																<div class="text-center p-3">
																	<div class="bg-success-light rounded-circle w-60 h-60 mx-auto d-flex align-items-center justify-content-center mb-3">
																		<i class="fas fa-chart-line fa-2x text-success"></i>
																	</div>
																	<h3 class="fw-500"><?php echo format_money($financial_data['net_profit']); ?></h3>
																	<p class="text-mute mb-0">Net Profit</p>
																	<small class="<?php echo $financial_data['net_profit'] >= 0 ? 'text-success' : 'text-danger'; ?>">
																		<?php echo $financial_data['net_profit'] >= 0 ? '+' : ''; ?>
																		<?php echo $financial_data['total_revenue'] > 0 ? number_format(($financial_data['net_profit'] / $financial_data['total_revenue']) * 100, 2) : '0.00'; ?>% margin
																	</small>
																</div>
															</div>
															
															<div class="col-md-3">
																<div class="text-center p-3">
																	<div class="bg-warning-light rounded-circle w-60 h-60 mx-auto d-flex align-items-center justify-content-center mb-3">
																		<i class="fas fa-robot fa-2x text-warning"></i>
																	</div>
																	<h3 class="fw-500">
																		<?php
																		$active_subs = mysqli_fetch_assoc(mysqli_query($conn, 
																			"SELECT COUNT(*) as total FROM user_bot_subscriptions 
																			 WHERE status = 'active' AND subscription_end >= CURDATE()"))['total'];
																		echo $active_subs;
																		?>
																	</h3>
																	<p class="text-mute mb-0">Active Subscriptions</p>
																	<small class="text-info">
																		MRR: <?php echo format_money($financial_data['subscription_revenue']); ?>
																	</small>
																</div>
															</div>
															
															<div class="col-md-3">
																<div class="text-center p-3">
																	<div class="bg-info-light rounded-circle w-60 h-60 mx-auto d-flex align-items-center justify-content-center mb-3">
																		<i class="fas fa-user-check fa-2x text-info"></i>
																	</div>
																	<h3 class="fw-500">
																		<?php
																		$active_users = mysqli_fetch_assoc(mysqli_query($conn, 
																			"SELECT COUNT(*) as total FROM users WHERE status = 'verified'"))['total'];
																		echo $active_users;
																		?>
																	</h3>
																	<p class="text-mute mb-0">Active Users</p>
																	<small class="text-primary">
																		ARPU: <?php echo format_money($active_users > 0 ? $financial_data['total_revenue'] / $active_users : 0); ?>
																	</small>
																</div>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Notes and Export -->
										<div class="row mt-20">
											<div class="col-12">
												<div class="box bg-light">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h6 class="mb-1"><i class="fas fa-info-circle me-2"></i>Report Notes</h6>
																<p class="mb-0 text-mute">Report generated on <?php echo date('F d, Y H:i:s'); ?></p>
															</div>
															<div>
																<button class="btn btn-primary" onclick="printReport()">
																	<i class="fas fa-print me-1"></i> Print Report
																</button>
															</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 -->
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- Apex Charts -->
		<script src="https://cdn.jsdelivr.net/npm/apexcharts"></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
			$('#dailyDataTable').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"
					}
				}
			});
			
			// Initialize Charts
			loadRevenueExpenseChart();
			loadRevenueBreakdownChart();
			
			// Auto-refresh every 5 minutes
			setInterval(function() {
				updateFinancialStats();
			}, 300000); // 5 minutes
		});
		
		// Revenue & Expense Chart
		function loadRevenueExpenseChart() {
			var dates = <?php echo json_encode(array_column($financial_data['daily_data'], 'date')); ?>;
			var revenue = <?php echo json_encode(array_column($financial_data['daily_data'], 'revenue')); ?>;
			var expenses = <?php echo json_encode(array_column($financial_data['daily_data'], 'expenses')); ?>;
			var profit = <?php echo json_encode(array_column($financial_data['daily_data'], 'profit')); ?>;
			
			var options = {
				series: [
					{
						name: 'Revenue',
						data: revenue,
						color: '#667eea'
					},
					{
						name: 'Expenses',
						data: expenses,
						color: '#f093fb'
					},
					{
						name: 'Trading Profit',
						data: profit,
						color: '#4facfe'
					}
				],
				chart: {
					type: 'area',
					height: 300,
					toolbar: {
						show: false
					}
				},
				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: dates,
					labels: {
						style: {
							colors: '#8c8c8c'
						}
					}
				},
				yaxis: {
					labels: {
						formatter: function(value) {
							return '$' + value.toFixed(2);
						},
						style: {
							colors: '#8c8c8c'
						}
					}
				},
				legend: {
					position: 'top',
					horizontalAlign: 'right'
				},
				grid: {
					borderColor: '#f1f1f1'
				}
			};
			
			var chart = new ApexCharts(document.querySelector("#revenueExpenseChart"), options);
			chart.render();
		}
		
		// Revenue Breakdown Chart
		function loadRevenueBreakdownChart() {
			var subscriptionRevenue = <?php echo $financial_data['subscription_revenue']; ?>;
			var depositRevenue = <?php echo $financial_data['deposit_revenue']; ?>;
			var feeIncome = <?php echo $financial_data['fee_income']; ?>;
			var tradingProfit = <?php echo $financial_data['trading_profit']; ?>;
			
			var options = {
				series: [subscriptionRevenue, depositRevenue, feeIncome, tradingProfit],
				chart: {
					type: 'donut',
					height: 300
				},
				labels: ['Subscriptions', 'Deposits', 'Fee Income', 'Trading Profit'],
				colors: ['#667eea', '#f093fb', '#4facfe', '#43e97b'],
				legend: {
					position: 'bottom'
				},
				responsive: [{
					breakpoint: 480,
					options: {
						chart: {
							width: 200
						},
						legend: {
							position: 'bottom'
						}
					}
				}]
			};
			
			var chart = new ApexCharts(document.querySelector("#revenueBreakdownChart"), options);
			chart.render();
		}
		
		// Update Financial Stats
		function updateFinancialStats() {
			$.ajax({
				url: 'ajax/get_financial_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.net_profit);
						$('.bg-gradient-warning .fw-500').text('$' + stats.withdrawal_expenses);
						
						// Update profit margin
						var margin = stats.total_revenue > 0 ? (stats.net_profit / stats.total_revenue * 100).toFixed(2) : '0.00';
						$('.bg-gradient-info .fw-500').text(margin + '%');
						
						// Show notification
						showNotification('Financial stats updated', 'success');
					}
				}
			});
		}
		
		// Change Chart View
		function changeChartView(view) {
			// Implement chart view change logic
			showNotification('Switching to ' + view + ' view', 'info');
		}
		
		// Export Report
		function exportReport(format) {
			var date_from = '<?php echo $date_from; ?>';
			var date_to = '<?php echo $date_to; ?>';
			
			var url = 'export_financial_report.php?format=' + format + 
					 '&date_from=' + date_from + 
					 '&date_to=' + date_to;
			
			window.open(url, '_blank');
		}
		
		// Print Report
		function printReport() {
			window.print();
		}
		
		// Show Notification
		function showNotification(message, type) {
			var icon = type === 'success' ? 'fas fa-check-circle' : 
					   type === 'error' ? 'fas fa-exclamation-circle' : 
					   type === 'warning' ? 'fas fa-exclamation-triangle' : 
					   'fas fa-info-circle';
			
			var toast = '<div class="toast align-items-center text-bg-' + type + ' border-0" role="alert" aria-live="assertive" aria-atomic="true">' +
						'<div class="d-flex">' +
						'<div class="toast-body">' +
						'<i class="' + icon + ' me-2"></i>' + message +
						'</div>' +
						'<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>' +
						'</div>' +
						'</div>';
			
			$('.toast-container').append(toast);
			var toastEl = $('.toast').last();
			var bsToast = new bootstrap.Toast(toastEl, { delay: 3000 });
			bsToast.show();
			
			// Remove toast after hide
			toastEl.on('hidden.bs.toast', function () {
				$(this).remove();
			});
		}
		</script>
		
		<!-- Toast Container -->
		<div class="toast-container position-fixed top-20 end-0 p-3"></div>
		
		<style>
		/* Custom styles for financial summary */
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
			box-shadow: 0 5px 20px rgba(0,0,0,0.1);
		}
		.bg-white-20 {
			background-color: rgba(255, 255, 255, 0.2);
		}
		.bg-primary-light {
			background-color: rgba(102, 126, 234, 0.1);
		}
		.bg-success-light {
			background-color: rgba(40, 167, 69, 0.1);
		}
		.bg-warning-light {
			background-color: rgba(255, 193, 7, 0.1);
		}
		.bg-info-light {
			background-color: rgba(23, 162, 184, 0.1);
		}
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
		}
		/* Print styles */
		@media print {
			.header, .sidebar, .box-controls, .dropdown, 
			.nav-tabs, .dataTables_length, .dataTables_filter,
			.dataTables_info, .dataTables_paginate, .btn {
				display: none !important;
			}
			.box {
				border: 1px solid #ddd !important;
				box-shadow: none !important;
			}
			.box-header {
				border-bottom: 2px solid #333 !important;
			}
		}
		</style>
		
	</body>
</html>