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

// Set default date to today
$report_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$prev_date = date('Y-m-d', strtotime($report_date . ' -1 day'));
$next_date = date('Y-m-d', strtotime($report_date . ' +1 day'));

// Calculate date ranges
$month_start = date('Y-m-01', strtotime($report_date));
$month_end = date('Y-m-t', strtotime($report_date));
$week_start = date('Y-m-d', strtotime('monday this week', strtotime($report_date)));
$week_end = date('Y-m-d', strtotime('sunday this week', strtotime($report_date)));

// Get daily statistics
function getDailyStats($date) {
    global $conn;
    
    $stats = array();
    
    // Total Users (all time)
    $sql = "SELECT COUNT(*) as total FROM users";
    $result = mysqli_query($conn, $sql);
    $stats['total_users'] = mysqli_fetch_assoc($result)['total'];
    
    // New Users Today
    $sql = "SELECT COUNT(*) as total FROM users WHERE DATE(registration_date) = '$date'";
    $result = mysqli_query($conn, $sql);
    $stats['new_users'] = mysqli_fetch_assoc($result)['total'];
    
    // Verified Users Today
    $sql = "SELECT COUNT(*) as total FROM users WHERE status = 'verified' AND DATE(verification_date) = '$date'";
    $result = mysqli_query($conn, $sql);
    $stats['verified_today'] = mysqli_fetch_assoc($result)['total'];
    
    // Active Subscriptions
    $sql = "SELECT COUNT(*) as total FROM user_bot_subscriptions WHERE status = 'active'";
    $result = mysqli_query($conn, $sql);
    $stats['active_subscriptions'] = mysqli_fetch_assoc($result)['total'];
    
    // New Subscriptions Today
    $sql = "SELECT COUNT(*) as total FROM user_bot_subscriptions WHERE DATE(subscription_start) = '$date'";
    $result = mysqli_query($conn, $sql);
    $stats['new_subscriptions'] = mysqli_fetch_assoc($result)['total'];
    
    // Deposits Today
    $sql = "SELECT COUNT(*) as count, COALESCE(SUM(amount), 0) as amount FROM deposits WHERE DATE(created_at) = '$date' AND status = 'confirmed'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $stats['deposits_count'] = $row['count'];
    $stats['deposits_amount'] = $row['amount'];
    
    // Withdrawals Today
    $sql = "SELECT COUNT(*) as count, COALESCE(SUM(amount), 0) as amount FROM withdrawals WHERE DATE(created_at) = '$date' AND status = 'completed'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $stats['withdrawals_count'] = $row['count'];
    $stats['withdrawals_amount'] = $row['amount'];
    
    // Pending Deposits
    $sql = "SELECT COUNT(*) as count, COALESCE(SUM(amount), 0) as amount FROM deposits WHERE status = 'pending'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $stats['pending_deposits'] = $row['count'];
    $stats['pending_deposits_amount'] = $row['amount'];
    
    // Pending Withdrawals
    $sql = "SELECT COUNT(*) as count, COALESCE(SUM(amount), 0) as amount FROM withdrawals WHERE status = 'pending'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $stats['pending_withdrawals'] = $row['count'];
    $stats['pending_withdrawals_amount'] = $row['amount'];
    
    // Total Profit (all time)
    $sql = "SELECT COALESCE(SUM(amount), 0) as total FROM transactions WHERE type = 'profit' AND status = 'completed'";
    $result = mysqli_query($conn, $sql);
    $stats['total_profit'] = mysqli_fetch_assoc($result)['total'];
    
    // Today's Profit
    $sql = "SELECT COALESCE(SUM(amount), 0) as total FROM transactions WHERE type = 'profit' AND status = 'completed' AND DATE(date) = '$date'";
    $result = mysqli_query($conn, $sql);
    $stats['today_profit'] = mysqli_fetch_assoc($result)['total'];
    
    // Bot Transactions Today
    $sql = "SELECT COUNT(*) as count, COALESCE(SUM(amount), 0) as amount FROM bot_transactions WHERE DATE(transaction_date) = '$date'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $stats['bot_transactions'] = $row['count'];
    $stats['bot_transactions_amount'] = $row['amount'];
    
    // Support Tickets
    $sql = "SELECT 
            COUNT(*) as total,
            SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) as open,
            SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
            SUM(CASE WHEN status = 'resolved' THEN 1 ELSE 0 END) as resolved
            FROM support_tickets WHERE DATE(created_at) = '$date'";
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_assoc($result);
    $stats['tickets_total'] = $row['total'];
    $stats['tickets_open'] = $row['open'];
    $stats['tickets_in_progress'] = $row['in_progress'];
    $stats['tickets_resolved'] = $row['resolved'];
    
    // Admin Activities Today
    $sql = "SELECT COUNT(*) as total FROM admin_activities WHERE DATE(created_at) = '$date'";
    $result = mysqli_query($conn, $sql);
    $stats['admin_activities'] = mysqli_fetch_assoc($result)['total'];
    
    return $stats;
}

// Get comparison with previous day
$today_stats = getDailyStats($report_date);
$yesterday_stats = getDailyStats($prev_date);

// Calculate changes
function calculateChange($today, $yesterday) {
    if ($yesterday == 0) {
        return $today > 0 ? 100 : 0;
    }
    return round((($today - $yesterday) / $yesterday) * 100, 2);
}

$changes = array();
foreach ($today_stats as $key => $value) {
    if (is_numeric($value) && isset($yesterday_stats[$key]) && is_numeric($yesterday_stats[$key])) {
        $changes[$key] = calculateChange($value, $yesterday_stats[$key]);
    }
}

// Get top performers for the day
function getTopPerformers($date) {
    global $conn;
    
    $performers = array();
    
    // Top Depositors
    $sql = "SELECT u.username, u.email, SUM(d.amount) as total 
            FROM deposits d 
            JOIN users u ON d.user_id = u.id 
            WHERE DATE(d.created_at) = '$date' AND d.status = 'confirmed'
            GROUP BY d.user_id 
            ORDER BY total DESC 
            LIMIT 5";
    $result = mysqli_query($conn, $sql);
    $performers['top_depositors'] = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $performers['top_depositors'][] = $row;
    }
    
    // Top Profit Makers
    $sql = "SELECT u.username, u.email, SUM(t.amount) as total 
            FROM transactions t 
            JOIN users u ON t.user_id = u.id 
            WHERE DATE(t.date) = '$date' AND t.type = 'profit' AND t.status = 'completed'
            GROUP BY t.user_id 
            ORDER BY total DESC 
            LIMIT 5";
    $result = mysqli_query($conn, $sql);
    $performers['top_profit'] = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $performers['top_profit'][] = $row;
    }
    
    // Most Active Bots
    $sql = "SELECT u.username, p.plan_name, s.trading_balance, s.total_profit 
            FROM user_bot_subscriptions s 
            JOIN users u ON s.user_id = u.id 
            JOIN trading_bot_plans p ON s.bot_plan_id = p.id 
            WHERE s.status = 'active'
            ORDER BY s.total_profit DESC 
            LIMIT 5";
    $result = mysqli_query($conn, $sql);
    $performers['active_bots'] = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $performers['active_bots'][] = $row;
    }
    
    return $performers;
}

$top_performers = getTopPerformers($report_date);

// Get hourly data for charts
function getHourlyData($date, $type) {
    global $conn;
    
    $data = array_fill(0, 24, 0);
    
    if ($type == 'deposits') {
        $sql = "SELECT HOUR(created_at) as hour, SUM(amount) as total 
                FROM deposits 
                WHERE DATE(created_at) = '$date' AND status = 'confirmed'
                GROUP BY HOUR(created_at)";
    } elseif ($type == 'withdrawals') {
        $sql = "SELECT HOUR(created_at) as hour, SUM(amount) as total 
                FROM withdrawals 
                WHERE DATE(created_at) = '$date' AND status = 'completed'
                GROUP BY HOUR(created_at)";
    } elseif ($type == 'profit') {
        $sql = "SELECT HOUR(date) as hour, SUM(amount) as total 
                FROM transactions 
                WHERE DATE(date) = '$date' AND type = 'profit' AND status = 'completed'
                GROUP BY HOUR(date)";
    } elseif ($type == 'users') {
        $sql = "SELECT HOUR(registration_date) as hour, COUNT(*) as total 
                FROM users 
                WHERE DATE(registration_date) = '$date'
                GROUP BY HOUR(registration_date)";
    }
    
    $result = mysqli_query($conn, $sql);
    while ($row = mysqli_fetch_assoc($result)) {
        $hour = intval($row['hour']);
        $data[$hour] = floatval($row['total']);
    }
    
    return $data;
}

$hourly_deposits = getHourlyData($report_date, 'deposits');
$hourly_withdrawals = getHourlyData($report_date, 'withdrawals');
$hourly_profit = getHourlyData($report_date, 'profit');
$hourly_users = getHourlyData($report_date, 'users');

// Get bot plan distribution for the day
function getBotPlanDistribution($date) {
    global $conn;
    
    $sql = "SELECT p.plan_name, COUNT(s.id) as count, SUM(s.trading_balance) as balance
            FROM user_bot_subscriptions s 
            JOIN trading_bot_plans p ON s.bot_plan_id = p.id 
            WHERE DATE(s.subscription_start) = '$date' OR DATE(s.subscription_end) = '$date'
            GROUP BY p.id
            ORDER BY count DESC";
    
    $result = mysqli_query($conn, $sql);
    $distribution = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $distribution[] = $row;
    }
    
    return $distribution;
}

$bot_distribution = getBotPlanDistribution($report_date);
?>

<!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-line me-2"></i>
													Daily Report: <?php echo date('F d, Y', strtotime($report_date)); ?>
												</h4>
												<p class="mb-0 text-mute">Comprehensive daily performance analysis</p>
											</div>
											<div class="d-flex align-items-center">
												<a href="daily_report.php?date=<?php echo $prev_date; ?>" class="btn btn-light me-2">
													<i class="fas fa-chevron-left"></i> Previous
												</a>
												
												<div class="input-group me-3" style="width: 200px;">
													<input type="date" class="form-control" id="datePicker" value="<?php echo $report_date; ?>">
													<button class="btn btn-primary" onclick="goToDate()">Go</button>
												</div>
												
												<a href="daily_report.php?date=<?php echo $next_date; ?>" class="btn btn-light me-3">
													Next <i class="fas fa-chevron-right"></i>
												</a>
												
												<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
													</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</a>
														<a class="dropdown-item" href="#" onclick="exportReport('csv')"><i class="fas fa-file-csv"></i> CSV</a>
														<a class="dropdown-item" href="#" onclick="printReport()"><i class="fas fa-print"></i> Print</a>
													</div>
												</div>
											</div>
										</div>
									</div>
									<div class="box-body">
										
										<!-- Quick Stats Row -->
										<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 Users</h5>
																<h2 class="text-white fw-500 mb-0"><?php echo number_format($today_stats['total_users']); ?></h2>
																<p class="text-white-50 mb-0">New: <?php echo number_format($today_stats['new_users']); ?></p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-users fa-2x text-white"></i>
															</div>
														</div>
														<div class="mt-10">
															<span class="text-white-50">
																<?php 
																$change = isset($changes['new_users']) ? $changes['new_users'] : 0;
																$arrow = $change >= 0 ? '<i class="fas fa-arrow-up"></i>' : '<i class="fas fa-arrow-down"></i>';
																$color = $change >= 0 ? 'text-success' : 'text-danger';
																echo "<span class='$color'>$arrow " . abs($change) . "%</span> from yesterday";
																?>
															</span>
														</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">Today's Profit</h5>
																<h2 class="text-white fw-500 mb-0">$<?php echo number_format($today_stats['today_profit'], 2); ?></h2>
																<p class="text-white-50 mb-0">Total: $<?php echo number_format($today_stats['total_profit'], 2); ?></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-10">
															<span class="text-white-50">
																<?php 
																$change = isset($changes['today_profit']) ? $changes['today_profit'] : 0;
																$arrow = $change >= 0 ? '<i class="fas fa-arrow-up"></i>' : '<i class="fas fa-arrow-down"></i>';
																$color = $change >= 0 ? 'text-success' : 'text-danger';
																echo "<span class='$color'>$arrow " . abs($change) . "%</span> from yesterday";
																?>
															</span>
														</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">Deposits</h5>
																<h2 class="text-white fw-500 mb-0">$<?php echo number_format($today_stats['deposits_amount'], 2); ?></h2>
																<p class="text-white-50 mb-0"><?php echo number_format($today_stats['deposits_count']); ?> transactions</p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-download fa-2x text-white"></i>
															</div>
														</div>
														<div class="mt-10">
															<span class="text-white-50">
																<?php 
																$change = isset($changes['deposits_amount']) ? $changes['deposits_amount'] : 0;
																$arrow = $change >= 0 ? '<i class="fas fa-arrow-up"></i>' : '<i class="fas fa-arrow-down"></i>';
																$color = $change >= 0 ? 'text-success' : 'text-danger';
																echo "<span class='$color'>$arrow " . abs($change) . "%</span> from yesterday";
																?>
															</span>
														</div>
													</div>
												</div>
											</div>
											
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-danger pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Withdrawals</h5>
																<h2 class="text-white fw-500 mb-0">$<?php echo number_format($today_stats['withdrawals_amount'], 2); ?></h2>
																<p class="text-white-50 mb-0"><?php echo number_format($today_stats['withdrawals_count']); ?> transactions</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-10">
															<span class="text-white-50">
																<?php 
																$change = isset($changes['withdrawals_amount']) ? $changes['withdrawals_amount'] : 0;
																$arrow = $change >= 0 ? '<i class="fas fa-arrow-up"></i>' : '<i class="fas fa-arrow-down"></i>';
																$color = $change >= 0 ? 'text-success' : 'text-danger';
																echo "<span class='$color'>$arrow " . abs($change) . "%</span> from yesterday";
																?>
															</span>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Charts Row -->
										<div class="row mb-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>Hourly Activity</h5>
														<div class="dropdown">
															<button class="btn btn-sm btn-light dropdown-toggle" type="button" data-bs-toggle="dropdown">
																Show: All
															</button>
															<div class="dropdown-menu">
																<a class="dropdown-item" href="javascript:void(0)" onclick="updateChart('all')">All</a>
																<a class="dropdown-item" href="javascript:void(0)" onclick="updateChart('deposits')">Deposits</a>
																<a class="dropdown-item" href="javascript:void(0)" onclick="updateChart('withdrawals')">Withdrawals</a>
																<a class="dropdown-item" href="javascript:void(0)" onclick="updateChart('profit')">Profit</a>
																<a class="dropdown-item" href="javascript:void(0)" onclick="updateChart('users')">New Users</a>
															</div>
														</div>
													</div>
													<div class="box-body">
														<div id="hourlyChart" 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-robot me-2"></i>Bot Plan Distribution</h5>
													</div>
													<div class="box-body">
														<div id="botPlanChart" style="height: 300px;"></div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Detailed Statistics -->
										<div class="row">
											<div class="col-xl-6 col-lg-6">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-cogs me-2"></i>Platform Statistics</h5>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover">
																<thead>
																	<tr>
																		<th>Metric</th>
																		<th class="text-end">Today</th>
																		<th class="text-end">Yesterday</th>
																		<th class="text-end">Change</th>
																	</tr>
																</thead>
																<tbody>
																	<tr>
																		<td>New Users</td>
																		<td class="text-end"><?php echo number_format($today_stats['new_users']); ?></td>
																		<td class="text-end"><?php echo number_format($yesterday_stats['new_users']); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['new_users']) ? $changes['new_users'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																	<tr>
																		<td>Verified Users</td>
																		<td class="text-end"><?php echo number_format($today_stats['verified_today']); ?></td>
																		<td class="text-end"><?php echo number_format($yesterday_stats['verified_today']); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['verified_today']) ? $changes['verified_today'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																	<tr>
																		<td>New Subscriptions</td>
																		<td class="text-end"><?php echo number_format($today_stats['new_subscriptions']); ?></td>
																		<td class="text-end"><?php echo number_format($yesterday_stats['new_subscriptions']); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['new_subscriptions']) ? $changes['new_subscriptions'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																	<tr>
																		<td>Active Subscriptions</td>
																		<td class="text-end"><?php echo number_format($today_stats['active_subscriptions']); ?></td>
																		<td class="text-end"><?php echo number_format($yesterday_stats['active_subscriptions']); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['active_subscriptions']) ? $changes['active_subscriptions'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																	<tr>
																		<td>Bot Transactions</td>
																		<td class="text-end"><?php echo number_format($today_stats['bot_transactions']); ?></td>
																		<td class="text-end"><?php echo number_format($yesterday_stats['bot_transactions']); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['bot_transactions']) ? $changes['bot_transactions'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																	<tr>
																		<td>Support Tickets</td>
																		<td class="text-end"><?php echo number_format($today_stats['tickets_total']); ?></td>
																		<td class="text-end"><?php echo number_format($yesterday_stats['tickets_total']); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['tickets_total']) ? $changes['tickets_total'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																	<tr>
																		<td>Admin Activities</td>
																		<td class="text-end"><?php echo number_format($today_stats['admin_activities']); ?></td>
																		<td class="text-end"><?php echo number_format($yesterday_stats['admin_activities']); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['admin_activities']) ? $changes['admin_activities'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
											
											<div class="col-xl-6 col-lg-6">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-money-bill-wave me-2"></i>Financial Statistics</h5>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover">
																<thead>
																	<tr>
																		<th>Metric</th>
																		<th class="text-end">Today</th>
																		<th class="text-end">Yesterday</th>
																		<th class="text-end">Change</th>
																	</tr>
																</thead>
																<tbody>
																	<tr>
																		<td>Deposit Amount</td>
																		<td class="text-end">$<?php echo number_format($today_stats['deposits_amount'], 2); ?></td>
																		<td class="text-end">$<?php echo number_format($yesterday_stats['deposits_amount'], 2); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['deposits_amount']) ? $changes['deposits_amount'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																	<tr>
																		<td>Withdrawal Amount</td>
																		<td class="text-end">$<?php echo number_format($today_stats['withdrawals_amount'], 2); ?></td>
																		<td class="text-end">$<?php echo number_format($yesterday_stats['withdrawals_amount'], 2); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['withdrawals_amount']) ? $changes['withdrawals_amount'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																	<tr>
																		<td>Profit Amount</td>
																		<td class="text-end">$<?php echo number_format($today_stats['today_profit'], 2); ?></td>
																		<td class="text-end">$<?php echo number_format($yesterday_stats['today_profit'], 2); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['today_profit']) ? $changes['today_profit'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																	<tr>
																		<td>Bot Transactions Amount</td>
																		<td class="text-end">$<?php echo number_format($today_stats['bot_transactions_amount'], 2); ?></td>
																		<td class="text-end">$<?php echo number_format($yesterday_stats['bot_transactions_amount'], 2); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['bot_transactions_amount']) ? $changes['bot_transactions_amount'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																	<tr>
																		<td>Pending Deposits</td>
																		<td class="text-end">$<?php echo number_format($today_stats['pending_deposits_amount'], 2); ?></td>
																		<td class="text-end">$<?php echo number_format($yesterday_stats['pending_deposits_amount'], 2); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['pending_deposits_amount']) ? $changes['pending_deposits_amount'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																	<tr>
																		<td>Pending Withdrawals</td>
																		<td class="text-end">$<?php echo number_format($today_stats['pending_withdrawals_amount'], 2); ?></td>
																		<td class="text-end">$<?php echo number_format($yesterday_stats['pending_withdrawals_amount'], 2); ?></td>
																		<td class="text-end">
																			<?php 
																			$change = isset($changes['pending_withdrawals_amount']) ? $changes['pending_withdrawals_amount'] : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs($change) . '%';
																			?>
																		</td>
																	</tr>
																	<tr class="table-primary">
																		<td><strong>Net Flow (Deposits - Withdrawals)</strong></td>
																		<td class="text-end"><strong>$<?php echo number_format($today_stats['deposits_amount'] - $today_stats['withdrawals_amount'], 2); ?></strong></td>
																		<td class="text-end"><strong>$<?php echo number_format($yesterday_stats['deposits_amount'] - $yesterday_stats['withdrawals_amount'], 2); ?></strong></td>
																		<td class="text-end">
																			<?php 
																			$today_net = $today_stats['deposits_amount'] - $today_stats['withdrawals_amount'];
																			$yesterday_net = $yesterday_stats['deposits_amount'] - $yesterday_stats['withdrawals_amount'];
																			$change = $yesterday_net != 0 ? (($today_net - $yesterday_net) / $yesterday_net) * 100 : 0;
																			$arrow = $change >= 0 ? '<i class="fas fa-arrow-up text-success"></i>' : '<i class="fas fa-arrow-down text-danger"></i>';
																			echo $arrow . ' ' . abs(round($change, 2)) . '%';
																			?>
																		</td>
																	</tr>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Top Performers -->
										<div class="row">
											<div class="col-xl-4 col-lg-6">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-trophy me-2"></i>Top Depositors</h5>
													</div>
													<div class="box-body p-0">
														<div class="table-responsive">
															<table class="table table-hover mb-0">
																<thead>
																	<tr>
																		<th>User</th>
																		<th class="text-end">Amount</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (!empty($top_performers['top_depositors'])): ?>
																		<?php foreach ($top_performers['top_depositors'] as $depositor): ?>
																			<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 fs-12"></i>
																							</div>
																						</div>
																						<div>
																							<p class="mb-0 fw-500"><?php echo htmlspecialchars($depositor['username']); ?></p>
																							<small class="text-mute"><?php echo htmlspecialchars($depositor['email']); ?></small>
																						</div>
																					</div>
																				</td>
																				<td class="text-end fw-500">$<?php echo number_format($depositor['total'], 2); ?></td>
																			</tr>
																		<?php endforeach; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="2" class="text-center py-20">No deposits today</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
											
											<div class="col-xl-4 col-lg-6">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-line me-2"></i>Top Profit Makers</h5>
													</div>
													<div class="box-body p-0">
														<div class="table-responsive">
															<table class="table table-hover mb-0">
																<thead>
																	<tr>
																		<th>User</th>
																		<th class="text-end">Profit</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (!empty($top_performers['top_profit'])): ?>
																		<?php foreach ($top_performers['top_profit'] as $profit_maker): ?>
																			<tr>
																				<td>
																					<div class="d-flex align-items-center">
																						<div class="me-10">
																							<div class="bg-success rounded-circle w-30 h-30 d-flex align-items-center justify-content-center">
																								<i class="fas fa-user text-white fs-12"></i>
																							</div>
																						</div>
																						<div>
																							<p class="mb-0 fw-500"><?php echo htmlspecialchars($profit_maker['username']); ?></p>
																							<small class="text-mute"><?php echo htmlspecialchars($profit_maker['email']); ?></small>
																						</div>
																					</div>
																				</td>
																				<td class="text-end fw-500 text-success">$<?php echo number_format($profit_maker['total'], 2); ?></td>
																			</tr>
																		<?php endforeach; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="2" class="text-center py-20">No profits today</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
											
											<div class="col-xl-4 col-lg-6">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-robot me-2"></i>Most Active Bots</h5>
													</div>
													<div class="box-body p-0">
														<div class="table-responsive">
															<table class="table table-hover mb-0">
																<thead>
																	<tr>
																		<th>User</th>
																		<th>Plan</th>
																		<th class="text-end">Profit</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (!empty($top_performers['active_bots'])): ?>
																		<?php foreach ($top_performers['active_bots'] as $bot): ?>
																			<tr>
																				<td>
																					<div class="d-flex align-items-center">
																						<div class="me-10">
																							<div class="bg-info rounded-circle w-30 h-30 d-flex align-items-center justify-content-center">
																								<i class="fas fa-user text-white fs-12"></i>
																							</div>
																						</div>
																		<div>
																			<p class="mb-0 fw-500"><?php echo htmlspecialchars($bot['username']); ?></p>
																			<small class="text-mute">$<?php echo number_format($bot['trading_balance'], 2); ?></small>
																		</div>
																	</div>
																</td>
																<td><span class="badge bg-primary"><?php echo htmlspecialchars($bot['plan_name']); ?></span></td>
																<td class="text-end fw-500 text-info">$<?php echo number_format($bot['total_profit'], 2); ?></td>
															</tr>
														<?php endforeach; ?>
													<?php else: ?>
														<tr>
															<td colspan="3" class="text-center py-20">No active bots</td>
														</tr>
													<?php endif; ?>
												</tbody>
											</table>
										</div>
									</div>
								</div>
							</div>
						</div>
						
						<!-- Support Tickets Summary -->
						<div class="row mt-20">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h5 class="box-title"><i class="fas fa-ticket-alt me-2"></i>Support Tickets Summary</h5>
									</div>
									<div class="box-body">
										<div class="row">
											<div class="col-md-3 col-6">
												<div class="box bg-light">
													<div class="box-body text-center">
														<h2 class="fw-500 text-primary"><?php echo $today_stats['tickets_total']; ?></h2>
														<p class="text-mute mb-0">Total Tickets</p>
													</div>
												</div>
											</div>
											<div class="col-md-3 col-6">
												<div class="box bg-light">
													<div class="box-body text-center">
														<h2 class="fw-500 text-warning"><?php echo $today_stats['tickets_open']; ?></h2>
														<p class="text-mute mb-0">Open</p>
													</div>
												</div>
											</div>
											<div class="col-md-3 col-6">
												<div class="box bg-light">
													<div class="box-body text-center">
														<h2 class="fw-500 text-info"><?php echo $today_stats['tickets_in_progress']; ?></h2>
														<p class="text-mute mb-0">In Progress</p>
													</div>
												</div>
											</div>
											<div class="col-md-3 col-6">
												<div class="box bg-light">
													<div class="box-body text-center">
														<h2 class="fw-500 text-success"><?php echo $today_stats['tickets_resolved']; ?></h2>
														<p class="text-mute mb-0">Resolved</p>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
						
						<!-- Admin Activities Summary -->
						<div class="row mt-20">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h5 class="box-title"><i class="fas fa-history me-2"></i>Recent Admin Activities</h5>
									</div>
									<div class="box-body p-0">
										<div class="table-responsive">
											<table class="table table-hover mb-0">
												<thead>
													<tr>
														<th>Admin</th>
														<th>Action</th>
														<th>Description</th>
														<th>Time</th>
													</tr>
												</thead>
												<tbody>
													<?php
													$activity_sql = "SELECT * FROM admin_activities 
																	WHERE DATE(created_at) = '$report_date' 
																	ORDER BY created_at DESC 
																	LIMIT 10";
													$activity_result = mysqli_query($conn, $activity_sql);
													
													if (mysqli_num_rows($activity_result) > 0):
														while ($activity = mysqli_fetch_assoc($activity_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-shield text-white fs-12"></i>
																			</div>
																		</div>
																		<div>
																			<p class="mb-0 fw-500"><?php echo htmlspecialchars($activity['admin_name']); ?></p>
																			<small class="text-mute"><?php echo ucfirst($activity['admin_role']); ?></small>
																		</div>
																	</div>
																</td>
																<td><span class="badge bg-light text-dark"><?php echo htmlspecialchars($activity['action']); ?></span></td>
																<td><small><?php echo htmlspecialchars($activity['description']); ?></small></td>
																<td><?php echo date('H:i:s', strtotime($activity['created_at'])); ?></td>
															</tr>
													<?php 
														endwhile;
													else:
													?>
														<tr>
															<td colspan="4" class="text-center py-20">No admin activities today</td>
														</tr>
													<?php endif; ?>
												</tbody>
											</table>
										</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>

<script>
$(document).ready(function() {
	// Initialize charts
	initHourlyChart();
	initBotPlanChart();
	
	// Auto-refresh stats every 60 seconds
	setInterval(function() {
		refreshStats();
	}, 60000);
});

// Date navigation
function goToDate() {
	var date = $('#datePicker').val();
	if (date) {
		window.location.href = 'daily_report.php?date=' + date;
	}
}

// Export functions
function exportReport(format) {
	var date = '<?php echo $report_date; ?>';
	var url = 'export_daily_report.php?date=' + date + '&format=' + format;
	window.open(url, '_blank');
}

function printReport() {
	window.print();
}

// Initialize Hourly Chart
var hourlyChart;
function initHourlyChart() {
	var hours = [];
	for (var i = 0; i < 24; i++) {
		hours.push(i.toString().padStart(2, '0') + ':00');
	}
	
	var options = {
		series: [{
			name: 'Deposits',
			data: <?php echo json_encode($hourly_deposits); ?>
		}, {
			name: 'Withdrawals',
			data: <?php echo json_encode($hourly_withdrawals); ?>
		}, {
			name: 'Profit',
			data: <?php echo json_encode($hourly_profit); ?>
		}, {
			name: 'New Users',
			data: <?php echo json_encode($hourly_users); ?>
		}],
		chart: {
			type: 'area',
			height: 300,
			stacked: false,
			toolbar: {
				show: false
			}
		},
		colors: ['#667eea', '#f093fb', '#4facfe', '#43e97b'],
		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: hours,
			labels: {
				style: {
					colors: '#8c8c8c'
				}
			}
		},
		yaxis: {
			labels: {
				formatter: function(value) {
					return '$' + value.toFixed(2);
				},
				style: {
					colors: '#8c8c8c'
				}
			}
		},
		legend: {
			position: 'top',
			horizontalAlign: 'right'
		},
		grid: {
			borderColor: '#f1f1f1'
		}
	};
	
	hourlyChart = new ApexCharts(document.querySelector("#hourlyChart"), options);
	hourlyChart.render();
}

// Initialize Bot Plan Chart
var botPlanChart;
function initBotPlanChart() {
	var labels = [];
	var series = [];
	
	<?php if (!empty($bot_distribution)): ?>
		<?php foreach ($bot_distribution as $plan): ?>
			labels.push("<?php echo $plan['plan_name']; ?>");
			series.push(<?php echo $plan['count']; ?>);
		<?php endforeach; ?>
	<?php else: ?>
		labels = ['No Data'];
		series = [1];
	<?php endif; ?>
	
	var options = {
		series: series,
		chart: {
			type: 'donut',
			height: 300
		},
		labels: labels,
		colors: ['#667eea', '#f093fb', '#4facfe', '#43e97b', '#fa709a'],
		legend: {
			position: 'bottom'
		},
		responsive: [{
			breakpoint: 480,
			options: {
				chart: {
					width: 200
				},
				legend: {
					position: 'bottom'
				}
			}
		}]
	};
	
	botPlanChart = new ApexCharts(document.querySelector("#botPlanChart"), options);
	botPlanChart.render();
}

// Update chart data
function updateChart(type) {
	// This would ideally fetch new data via AJAX
	// For now, we'll just show/hide series
	switch(type) {
		case 'deposits':
			hourlyChart.updateSeries([{
				name: 'Deposits',
				data: <?php echo json_encode($hourly_deposits); ?>
			}, {
				name: 'Withdrawals',
				data: []
			}, {
				name: 'Profit',
				data: []
			}, {
				name: 'New Users',
				data: []
			}]);
			break;
		case 'withdrawals':
			hourlyChart.updateSeries([{
				name: 'Deposits',
				data: []
			}, {
				name: 'Withdrawals',
				data: <?php echo json_encode($hourly_withdrawals); ?>
			}, {
				name: 'Profit',
				data: []
			}, {
				name: 'New Users',
				data: []
			}]);
			break;
		case 'profit':
			hourlyChart.updateSeries([{
				name: 'Deposits',
				data: []
			}, {
				name: 'Withdrawals',
				data: []
			}, {
				name: 'Profit',
				data: <?php echo json_encode($hourly_profit); ?>
			}, {
				name: 'New Users',
				data: []
			}]);
			break;
		case 'users':
			hourlyChart.updateSeries([{
				name: 'Deposits',
				data: []
			}, {
				name: 'Withdrawals',
				data: []
			}, {
				name: 'Profit',
				data: []
			}, {
				name: 'New Users',
				data: <?php echo json_encode($hourly_users); ?>
			}]);
			break;
		default:
			hourlyChart.updateSeries([{
				name: 'Deposits',
				data: <?php echo json_encode($hourly_deposits); ?>
			}, {
				name: 'Withdrawals',
				data: <?php echo json_encode($hourly_withdrawals); ?>
			}, {
				name: 'Profit',
				data: <?php echo json_encode($hourly_profit); ?>
			}, {
				name: 'New Users',
				data: <?php echo json_encode($hourly_users); ?>
			}]);
	}
}

// Refresh stats (live update)
function refreshStats() {
	var date = '<?php echo $report_date; ?>';
	
	$.ajax({
		url: 'ajax/get_daily_stats.php',
		type: 'GET',
		data: { date: date },
		success: function(data) {
			var stats = JSON.parse(data);
			if (stats.success) {
				// Update main stat cards
				$('.bg-gradient-primary .fw-500').text(stats.total_users.toLocaleString());
				$('.bg-gradient-primary .text-white-50').html('New: ' + stats.new_users.toLocaleString());
				
				$('.bg-gradient-success .fw-500').text('$' + stats.today_profit.toFixed(2));
				$('.bg-gradient-success .text-white-50').html('Total: $' + stats.total_profit.toFixed(2));
				
				$('.bg-gradient-warning .fw-500').text('$' + stats.deposits_amount.toFixed(2));
				$('.bg-gradient-warning .text-white-50').html(stats.deposits_count.toLocaleString() + ' transactions');
				
				$('.bg-gradient-danger .fw-500').text('$' + stats.withdrawals_amount.toFixed(2));
				$('.bg-gradient-danger .text-white-50').html(stats.withdrawals_count.toLocaleString() + ' transactions');
				
				// Show notification
				Swal.fire({
					toast: true,
					position: 'top-end',
					icon: 'success',
					title: 'Stats Updated',
					showConfirmButton: false,
					timer: 1500
				});
			}
		}
	});
}
</script>

<style>
.box {
	border-radius: 10px;
	overflow: hidden;
}
.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);
}
@media print {
	.box-header, .btn, .dropdown, .input-group {
		display: none !important;
	}
	.box {
		border: 1px solid #ddd !important;
		box-shadow: none !important;
	}
}
</style>

<!-- SweetAlert2 for notifications -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

</body>
</html>