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

// Get filter parameters
$period = isset($_GET['period']) ? $_GET['period'] : 'this_month';
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;

// Date ranges
$today = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));
$week_start = date('Y-m-d', strtotime('monday this week'));
$week_end = date('Y-m-d', strtotime('sunday this week'));
$month_start = date('Y-m-01');
$month_end = date('Y-m-t');
$last_month_start = date('Y-m-01', strtotime('-1 month'));
$last_month_end = date('Y-m-t', strtotime('-1 month'));

// Build WHERE clause based on period
$where_clause = "";
switch ($period) {
    case 'today':
        $where_clause = "AND DATE(r.created_at) = '$today'";
        break;
    case 'yesterday':
        $where_clause = "AND DATE(r.created_at) = '$yesterday'";
        break;
    case 'this_week':
        $where_clause = "AND DATE(r.created_at) BETWEEN '$week_start' AND '$week_end'";
        break;
    case 'last_week':
        $last_week_start = date('Y-m-d', strtotime('monday last week'));
        $last_week_end = date('Y-m-d', strtotime('sunday last week'));
        $where_clause = "AND DATE(r.created_at) BETWEEN '$last_week_start' AND '$last_week_end'";
        break;
    case 'this_month':
        $where_clause = "AND DATE(r.created_at) BETWEEN '$month_start' AND '$month_end'";
        break;
    case 'last_month':
        $where_clause = "AND DATE(r.created_at) BETWEEN '$last_month_start' AND '$last_month_end'";
        break;
    case 'all_time':
        $where_clause = "";
        break;
}

// Get top referrers
$sql = "SELECT 
            u.id,
            u.username,
            u.email,
            u.first_name,
            u.last_name,
            u.status,
            COUNT(DISTINCT r.referred_id) as total_referrals,
            SUM(CASE WHEN DATE(r.created_at) = '$today' THEN 1 ELSE 0 END) as today_referrals,
            SUM(CASE WHEN DATE(r.created_at) BETWEEN '$month_start' AND '$month_end' THEN 1 ELSE 0 END) as month_referrals,
            COALESCE(SUM(rt.amount), 0) as total_earnings,
            COALESCE(SUM(CASE WHEN rt.transaction_type = 'bot_bonus' THEN rt.amount ELSE 0 END), 0) as bot_bonus,
            COALESCE(SUM(CASE WHEN rt.transaction_type = 'signup_bonus' THEN rt.amount ELSE 0 END), 0) as signup_bonus,
            u.referral_balance,
            MAX(r.created_at) as last_referral
        FROM users u
        LEFT JOIN referrals r ON u.id = r.user_id
        LEFT JOIN referral_transactions rt ON u.id = rt.referrer_id
        WHERE u.id IN (SELECT DISTINCT user_id FROM referrals)
        GROUP BY u.id, u.username, u.email, u.first_name, u.last_name, u.status, u.referral_balance
        ORDER BY total_referrals DESC
        LIMIT $limit";

$result = mysqli_query($conn, $sql);

// Get overall referral stats
$stats_sql = "SELECT 
                COUNT(DISTINCT r.user_id) as total_referrers,
                COUNT(DISTINCT r.referred_id) as total_referred_users,
                COUNT(DISTINCT CASE WHEN u.status = 'verified' THEN r.referred_id END) as verified_referred,
                COALESCE(SUM(rt.amount), 0) as total_paid_out,
                COALESCE(AVG(rt.amount), 0) as avg_earning_per_referrer
              FROM referrals r
              LEFT JOIN users u ON r.referred_id = u.id
              LEFT JOIN referral_transactions rt ON r.user_id = rt.referrer_id";
$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);

// Get recent referral transactions
$recent_txns_sql = "SELECT rt.*, 
                           u1.username as referrer_name,
                           u2.username as referred_name
                    FROM referral_transactions rt
                    LEFT JOIN users u1 ON rt.referrer_id = u1.id
                    LEFT JOIN users u2 ON rt.referred_id = u2.id
                    ORDER BY rt.created_at DESC
                    LIMIT 10";
$recent_txns_result = mysqli_query($conn, $recent_txns_sql);
?>

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

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

		  	<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<div class="container-full">
					<!-- Main content -->
					<section class="content">
						<div class="row">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h4 class="box-title"><i class="fas fa-trophy me-2"></i>Top Referrers Leaderboard</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#referralReportModal">
												<i class="fas fa-chart-bar me-1"></i> Generate Report
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Stats 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 Referrers</h5>
																<h2 class="text-white fw-500 mb-0"><?php echo $stats['total_referrers']; ?></h2>
																<p class="text-white-50 mb-0">Active referrers</p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-users 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">Total Referred</h5>
																<h2 class="text-white fw-500 mb-0"><?php echo $stats['total_referred_users']; ?></h2>
																<p class="text-white-50 mb-0">New users via referral</p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-user-plus 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">Verified Referred</h5>
																<h2 class="text-white fw-500 mb-0"><?php echo $stats['verified_referred']; ?></h2>
																<p class="text-white-50 mb-0">Successfully verified</p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-user-check 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-danger pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Total Paid Out</h5>
																<h2 class="text-white fw-500 mb-0">$<?php echo number_format($stats['total_paid_out'], 2); ?></h2>
																<p class="text-white-50 mb-0">Referral bonuses paid</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>
										
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-8">
												<form method="GET" class="row">
													<div class="col-md-4">
														<div class="form-group">
															<label>Time Period</label>
															<select class="form-control" name="period" onchange="this.form.submit()">
																<option value="today" <?php echo $period == 'today' ? 'selected' : ''; ?>>Today</option>
																<option value="yesterday" <?php echo $period == 'yesterday' ? 'selected' : ''; ?>>Yesterday</option>
																<option value="this_week" <?php echo $period == 'this_week' ? 'selected' : ''; ?>>This Week</option>
																<option value="last_week" <?php echo $period == 'last_week' ? 'selected' : ''; ?>>Last Week</option>
																<option value="this_month" <?php echo $period == 'this_month' ? 'selected' : ''; ?>>This Month</option>
																<option value="last_month" <?php echo $period == 'last_month' ? 'selected' : ''; ?>>Last Month</option>
																<option value="all_time" <?php echo $period == 'all_time' ? 'selected' : ''; ?>>All Time</option>
															</select>
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label>Show Top</label>
															<select class="form-control" name="limit" onchange="this.form.submit()">
																<option value="10" <?php echo $limit == 10 ? 'selected' : ''; ?>>Top 10</option>
																<option value="20" <?php echo $limit == 20 ? 'selected' : ''; ?>>Top 20</option>
																<option value="50" <?php echo $limit == 50 ? 'selected' : ''; ?>>Top 50</option>
																<option value="100" <?php echo $limit == 100 ? 'selected' : ''; ?>>Top 100</option>
															</select>
														</div>
													</div>
													<div class="col-md-5">
														<div class="form-group">
															<label>&nbsp;</label>
															<div class="d-flex">
																<button type="submit" class="btn btn-primary me-2"><i class="fas fa-filter me-1"></i> Apply Filters</button>
																<a href="top_referrers.php" class="btn btn-secondary">Reset</a>
															</div>
														</div>
													</div>
												</form>
											</div>
											<div class="col-md-4 text-end">
												<div class="btn-group mt-4">
													<button type="button" class="btn btn-light dropdown-toggle" data-bs-toggle="dropdown">
														<i class="fas fa-download me-1"></i> Export
													</button>
													<div class="dropdown-menu">
														<a class="dropdown-item" href="export_referrers.php?format=csv&period=<?php echo $period; ?>&limit=<?php echo $limit; ?>"><i class="fas fa-file-csv"></i> CSV</a>
														<a class="dropdown-item" href="export_referrers.php?format=excel&period=<?php echo $period; ?>&limit=<?php echo $limit; ?>"><i class="fas fa-file-excel"></i> Excel</a>
														<a class="dropdown-item" href="export_referrers.php?format=pdf&period=<?php echo $period; ?>&limit=<?php echo $limit; ?>"><i class="fas fa-file-pdf"></i> PDF</a>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Leaderboard -->
										<div class="row">
											<div class="col-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title">
															<i class="fas fa-crown me-2"></i>
															Top Referrers Leaderboard 
															<small class="text-mute">(<?php echo ucfirst(str_replace('_', ' ', $period)); ?>)</small>
														</h5>
													</div>
													<div class="box-body p-0">
														<div class="table-responsive">
															<table class="table table-hover mb-0">
																<thead class="bg-light">
																	<tr>
																		<th width="60">Rank</th>
																		<th>Referrer</th>
																		<th class="text-center">Total Referrals</th>
																		<th class="text-center">Today</th>
																		<th class="text-center">This Month</th>
																		<th class="text-center">Total Earnings</th>
																		<th class="text-center">Balance</th>
																		<th class="text-center">Last Referral</th>
																		<th>Actions</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($result) > 0): ?>
																		<?php 
																		$rank = 1;
																		while ($referrer = mysqli_fetch_assoc($result)): 
																			$status_color = $referrer['status'] == 'verified' ? 'success' : ($referrer['status'] == 'pending' ? 'warning' : 'danger');
																			$last_referral = $referrer['last_referral'] ? date('M d, Y', strtotime($referrer['last_referral'])) : 'Never';
																			$rank_class = '';
																			if ($rank == 1) $rank_class = 'bg-warning text-dark';
																			if ($rank == 2) $rank_class = 'bg-light';
																			if ($rank == 3) $rank_class = 'bg-secondary text-white';
																		?>
																			<tr>
																				<td>
																					<div class="text-center">
																						<?php if ($rank <= 3): ?>
																							<span class="badge <?php echo $rank_class; ?> fs-16" style="width: 30px; height: 30px; line-height: 30px;">
																								<?php echo $rank; ?>
																							</span>
																						<?php else: ?>
																							<span class="text-mute fw-500">#<?php echo $rank; ?></span>
																						<?php endif; ?>
																					</div>
																				</td>
																				<td>
																					<div class="d-flex align-items-center">
																						<div class="me-10">
																							<div class="bg-primary rounded-circle w-40 h-40 d-flex align-items-center justify-content-center">
																								<i class="fas fa-user text-white"></i>
																							</div>
																						</div>
																						<div>
																							<p class="mb-0 fw-500"><?php echo htmlspecialchars($referrer['username']); ?></p>
																							<small class="text-mute"><?php echo htmlspecialchars($referrer['email']); ?></small>
																							<br>
																							<span class="badge bg-<?php echo $status_color; ?>"><?php echo ucfirst($referrer['status']); ?></span>
																						</div>
																					</div>
																				</td>
																				<td class="text-center">
																					<h4 class="fw-500 text-primary mb-0"><?php echo $referrer['total_referrals']; ?></h4>
																					<small class="text-mute">Total</small>
																				</td>
																				<td class="text-center">
																					<span class="badge <?php echo $referrer['today_referrals'] > 0 ? 'bg-success' : 'bg-light text-dark'; ?>">
																						<?php echo $referrer['today_referrals']; ?> today
																					</span>
																				</td>
																				<td class="text-center">
																					<span class="badge <?php echo $referrer['month_referrals'] > 0 ? 'bg-info' : 'bg-light text-dark'; ?>">
																						<?php echo $referrer['month_referrals']; ?> this month
																					</span>
																				</td>
																				<td class="text-center">
																					<h5 class="fw-500 text-success mb-0">$<?php echo number_format($referrer['total_earnings'], 2); ?></h5>
																					<small class="text-mute">
																						Signup: $<?php echo number_format($referrer['signup_bonus'], 2); ?> | 
																						Bot: $<?php echo number_format($referrer['bot_bonus'], 2); ?>
																					</small>
																				</td>
																				<td class="text-center">
																					<h5 class="fw-500 text-warning mb-0">$<?php echo number_format($referrer['referral_balance'], 2); ?></h5>
																					<small class="text-mute">Available balance</small>
																				</td>
																				<td class="text-center">
																					<small class="text-mute"><?php echo $last_referral; ?></small>
																				</td>
																				<td>
																					<div class="btn-group">
																						<button type="button" class="btn btn-light btn-sm dropdown-toggle" data-bs-toggle="dropdown">
																							<i class="fas fa-cog"></i>
																						</button>
																						<div class="dropdown-menu">
																							<a class="dropdown-item" href="view_user.php?id=<?php echo $referrer['id']; ?>"><i class="fas fa-eye me-2"></i> View Profile</a>
																							<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#referrerDetailsModal" data-referrer-id="<?php echo $referrer['id']; ?>"><i class="fas fa-chart-pie me-2"></i> View Details</a>
																							<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#addBonusModal" data-referrer-id="<?php echo $referrer['id']; ?>"><i class="fas fa-gift me-2"></i> Add Bonus</a>
																							<div class="dropdown-divider"></div>
																							<a class="dropdown-item text-success" href="#" onclick="payReferralBonus(<?php echo $referrer['id']; ?>)"><i class="fas fa-money-bill-wave me-2"></i> Pay Bonus</a>
																						</div>
																					</div>
																				</td>
																			</tr>
																			<?php $rank++; ?>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="9" class="text-center py-20">
																				<i class="fas fa-trophy fa-2x text-mute mb-3"></i>
																				<h5>No referrers found</h5>
																				<p class="text-mute">No referral activity for the selected period</p>
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Recent Referral Transactions -->
										<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 Referral Transactions</h5>
													</div>
													<div class="box-body p-0">
														<div class="table-responsive">
															<table class="table table-hover mb-0">
																<thead class="bg-light">
																	<tr>
																		<th>Date</th>
																		<th>Referrer</th>
																		<th>Referred User</th>
																		<th>Type</th>
																		<th>Amount</th>
																		<th>Description</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($recent_txns_result) > 0): ?>
																		<?php while ($txn = mysqli_fetch_assoc($recent_txns_result)): ?>
																			<?php
																			$type_color = $txn['transaction_type'] == 'bot_bonus' ? 'success' : 'primary';
																			$type_icon = $txn['transaction_type'] == 'bot_bonus' ? 'fas fa-robot' : 'fas fa-user-plus';
																			?>
																			<tr>
																				<td>
																					<small class="text-mute"><?php echo date('M d, Y', strtotime($txn['created_at'])); ?></small>
																					<br>
																					<small class="text-mute"><?php echo date('H:i', strtotime($txn['created_at'])); ?></small>
																				</td>
																				<td>
																					<p class="mb-0 fw-500"><?php echo htmlspecialchars($txn['referrer_name']); ?></p>
																					<small class="text-mute">ID: <?php echo $txn['referrer_id']; ?></small>
																				</td>
																				<td>
																					<p class="mb-0 fw-500"><?php echo htmlspecialchars($txn['referred_name']); ?></p>
																					<small class="text-mute">ID: <?php echo $txn['referred_id']; ?></small>
																				</td>
																				<td>
																					<span class="badge bg-<?php echo $type_color; ?>">
																						<i class="<?php echo $type_icon; ?> me-1"></i>
																						<?php echo str_replace('_', ' ', ucfirst($txn['transaction_type'])); ?>
																					</span>
																				</td>
																				<td class="fw-500 text-success">$<?php echo number_format($txn['amount'], 2); ?></td>
																				<td><small><?php echo htmlspecialchars($txn['description']); ?></small></td>
																			</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="6" class="text-center py-20">
																				<i class="fas fa-exchange-alt fa-2x text-mute mb-3"></i>
																				<p class="text-mute">No referral transactions yet</p>
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Referral Performance Chart -->
										<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-line me-2"></i>Referral Performance Trend</h5>
													</div>
													<div class="box-body">
														<div id="referralChart" style="height: 300px;"></div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Referrer Details -->
		<div class="modal fade" id="referrerDetailsModal" tabindex="-1" aria-labelledby="referrerDetailsModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="referrerDetailsModalLabel">Referrer Details</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body" id="referrerDetailsContent">
						<!-- Content will be loaded via AJAX -->
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- Modal for Add Bonus -->
		<div class="modal fade" id="addBonusModal" tabindex="-1" aria-labelledby="addBonusModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST" action="add_referral_bonus.php">
						<div class="modal-header">
							<h5 class="modal-title" id="addBonusModalLabel">Add Manual Bonus</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="referrer_id" id="bonusReferrerId">
							
							<div class="mb-3">
								<label class="form-label">Bonus Type</label>
								<select class="form-control" name="bonus_type" required>
									<option value="signup_bonus">Signup Bonus</option>
									<option value="bot_bonus">Bot Bonus</option>
									<option value="manual_bonus">Manual Bonus</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Amount ($)</label>
								<input type="number" class="form-control" name="amount" step="0.01" min="0.01" required>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Description</label>
								<textarea class="form-control" name="description" rows="3" required placeholder="Enter reason for bonus..."></textarea>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Referred User ID (Optional)</label>
								<input type="number" class="form-control" name="referred_id" placeholder="Enter referred user ID if applicable">
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Add Bonus</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Generate Report -->
		<div class="modal fade" id="referralReportModal" tabindex="-1" aria-labelledby="referralReportModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST" action="generate_referral_report.php" target="_blank">
						<div class="modal-header">
							<h5 class="modal-title" id="referralReportModalLabel">Generate Referral Report</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<div class="mb-3">
								<label class="form-label">Report Type</label>
								<select class="form-control" name="report_type" required>
									<option value="leaderboard">Top Referrers Leaderboard</option>
									<option value="transactions">Referral Transactions</option>
									<option value="performance">Performance Analysis</option>
									<option value="detailed">Detailed Report</option>
								</select>
							</div>
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Start Date</label>
										<input type="date" class="form-control" name="start_date">
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">End Date</label>
										<input type="date" class="form-control" name="end_date">
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Format</label>
								<select class="form-control" name="format" required>
									<option value="pdf">PDF</option>
									<option value="excel">Excel</option>
									<option value="csv">CSV</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Include Top</label>
								<input type="number" class="form-control" name="top_n" min="1" max="100" value="10">
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Generate Report</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Hidden form for paying referral bonus -->
		<form method="POST" action="pay_referral_bonus.php" id="payBonusForm" style="display: none;">
			<input type="hidden" name="referrer_id" id="payReferrerId">
			<input type="hidden" name="admin_pin" id="payAdminPin">
		</form>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- Apex Charts -->
		<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<script>
		$(document).ready(function() {
			// Initialize chart
			loadReferralChart();
			
			// Referrer Details Modal
			$('#referrerDetailsModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var referrerId = button.data('referrer-id');
				
				$.ajax({
					url: 'ajax/get_referrer_details.php',
					type: 'GET',
					data: { id: referrerId },
					success: function(data) {
						$('#referrerDetailsContent').html(data);
					}
				});
			});
			
			// Add Bonus Modal
			$('#addBonusModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var referrerId = button.data('referrer-id');
				$('#bonusReferrerId').val(referrerId);
			});
			
			// Auto-refresh stats every 30 seconds
			setInterval(function() {
				refreshReferralStats();
			}, 30000);
		});
		
		// Load Referral Chart
		function loadReferralChart() {
			$.ajax({
				url: 'ajax/get_referral_chart_data.php',
				type: 'GET',
				data: { period: '<?php echo $period; ?>' },
				dataType: 'json',
				success: function(data) {
					if (data.success) {
						var options = {
							series: [{
								name: 'Referrals',
								data: data.referrals
							}, {
								name: 'Earnings',
								data: data.earnings
							}],
							chart: {
								type: 'area',
								height: 300,
								toolbar: {
									show: false
								}
							},
							colors: ['#667eea', '#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: data.labels,
								labels: {
									style: {
										colors: '#8c8c8c'
									}
								}
							},
							yaxis: [{
								title: {
									text: 'Referrals',
									style: {
										color: '#667eea'
									}
								},
								labels: {
									style: {
										colors: '#8c8c8c'
									}
								}
							}, {
								opposite: true,
								title: {
									text: 'Earnings ($)',
									style: {
										color: '#43e97b'
									}
								},
								labels: {
									formatter: function(value) {
										return '$' + value;
									},
									style: {
										colors: '#8c8c8c'
									}
								}
							}],
							legend: {
								position: 'top',
								horizontalAlign: 'right'
							},
							grid: {
								borderColor: '#f1f1f1'
							}
						};
						
						var chart = new ApexCharts(document.querySelector("#referralChart"), options);
						chart.render();
					}
				}
			});
		}
		
		// Refresh Stats
		function refreshReferralStats() {
			$.ajax({
				url: 'ajax/get_referral_stats2.php',
				type: 'GET',
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update stat cards
						$('.bg-gradient-primary .fw-500').text(stats.total_referrers);
						$('.bg-gradient-success .fw-500').text(stats.total_referred_users);
						$('.bg-gradient-warning .fw-500').text(stats.verified_referred);
						$('.bg-gradient-danger .fw-500').text('$' + stats.total_paid_out);
						
						// Show toast notification
						Swal.fire({
							toast: true,
							position: 'top-end',
							icon: 'success',
							title: 'Stats Updated',
							showConfirmButton: false,
							timer: 1500
						});
					}
				}
			});
		}
		
		// Pay Referral Bonus with PIN confirmation
		function payReferralBonus(referrerId) {
			Swal.fire({
				title: 'Pay Referral Bonus',
				html: `
					<p>This will transfer the referral balance to the user's main account.</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="swalBonusPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'question',
				showCancelButton: true,
				confirmButtonColor: '#28a745',
				cancelButtonColor: '#6c757d',
				confirmButtonText: 'Pay Bonus',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('swalBonusPin').value;
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					return { pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					// Submit the form
					document.getElementById('payReferrerId').value = referrerId;
					document.getElementById('payAdminPin').value = result.value.pin;
					document.getElementById('payBonusForm').submit();
				}
			});
		}
		
		// Export function
		function exportReferrers(format) {
			window.open('export_referrers.php?format=' + format + '&period=<?php echo $period; ?>&limit=<?php echo $limit; ?>', '_blank');
		}
		</script>
		
		<style>
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
		}
		.badge {
			padding: 5px 10px;
			border-radius: 20px;
			font-size: 12px;
			font-weight: 600;
		}
		.bg-gradient-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important; }
		.bg-gradient-success { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important; }
		.bg-gradient-warning { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%) !important; }
		.bg-gradient-danger { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%) !important; }
		
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		
		.bg-white-20 {
			background-color: rgba(255, 255, 255, 0.2);
		}
		
		.rank-1 {
			background-color: #FFD700 !important;
			color: #000 !important;
			font-weight: bold;
		}
		.rank-2 {
			background-color: #C0C0C0 !important;
			color: #000 !important;
			font-weight: bold;
		}
		.rank-3 {
			background-color: #CD7F32 !important;
			color: #fff !important;
			font-weight: bold;
		}
		</style>
		
	</body>
</html>