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

// Default date range (last 30 days)
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$bot_plan_id = isset($_GET['bot_plan_id']) ? intval($_GET['bot_plan_id']) : 0;
$type = isset($_GET['type']) ? $_GET['type'] : 'all';

// Validate dates
if ($start_date > $end_date) {
    $temp = $start_date;
    $start_date = $end_date;
    $end_date = $temp;
}

// Get bot plans for filter dropdown
$bot_plans = array();
$plan_sql = "SELECT id, plan_name FROM trading_bot_plans WHERE is_active = 1 ORDER BY sort_order";
$plan_result = mysqli_query($conn, $plan_sql);
while ($plan = mysqli_fetch_assoc($plan_result)) {
    $bot_plans[$plan['id']] = $plan['plan_name'];
}

// Get top referrers for filter
$top_referrers = array();
$referrer_sql = "SELECT u.id, u.username, u.email, COUNT(r.id) as referral_count 
                 FROM users u 
                 LEFT JOIN referrals r ON u.id = r.user_id 
                 WHERE u.status = 'verified'
                 GROUP BY u.id 
                 ORDER BY referral_count DESC 
                 LIMIT 20";
$referrer_result = mysqli_query($conn, $referrer_sql);
while ($referrer = mysqli_fetch_assoc($referrer_result)) {
    $top_referrers[$referrer['id']] = $referrer['username'] . ' (' . $referrer['email'] . ') - ' . $referrer['referral_count'] . ' referrals';
}

// Calculate commission statistics
$stats = array(
    'total_commission' => 0,
    'total_referral_bonus' => 0,
    'total_bot_commission' => 0,
    'total_signup_bonus' => 0,
    'unique_referrers' => 0,
    'total_referred_users' => 0
);

// Build commission query
$commission_sql = "SELECT 
                    rt.*,
                    u1.username as referrer_username,
                    u1.email as referrer_email,
                    u2.username as referred_username,
                    u2.email as referred_email,
                    s.bot_plan_id,
                    p.plan_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
                  LEFT JOIN user_bot_subscriptions s ON rt.referred_id = s.user_id AND rt.transaction_type = 'bot_bonus'
                  LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
                  WHERE rt.created_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59'";

if ($user_id > 0) {
    $commission_sql .= " AND rt.referrer_id = $user_id";
}

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

if ($type != 'all') {
    $commission_sql .= " AND rt.transaction_type = '$type'";
}

$commission_sql .= " ORDER BY rt.created_at DESC";

$commission_result = mysqli_query($conn, $commission_sql);

// Calculate stats from result
$temp_result = mysqli_query($conn, $commission_sql);
$referrers = array();
while ($row = mysqli_fetch_assoc($temp_result)) {
    $stats['total_commission'] += $row['amount'];
    
    if ($row['transaction_type'] == 'signup_bonus') {
        $stats['total_signup_bonus'] += $row['amount'];
    } elseif ($row['transaction_type'] == 'bot_bonus') {
        $stats['total_bot_commission'] += $row['amount'];
    } elseif ($row['transaction_type'] == 'interest_discount') {
        $stats['total_referral_bonus'] += $row['amount'];
    }
    
    if (!in_array($row['referrer_id'], $referrers)) {
        $referrers[] = $row['referrer_id'];
        $stats['unique_referrers']++;
    }
    
    $stats['total_referred_users']++;
}

// Get referral settings for commission rates
$settings_sql = "SELECT * FROM referral_settings LIMIT 1";
$settings_result = mysqli_query($conn, $settings_sql);
$settings = mysqli_fetch_assoc($settings_result);
?>

<!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-money-bill-wave me-2"></i>Commission Report</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" onclick="exportCommissionReport()">
												<i class="fas fa-download me-1"></i> Export Report
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-12">
												<form method="GET" class="row">
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">Start Date</label>
															<input type="date" class="form-control" name="start_date" value="<?php echo $start_date; ?>" required>
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">End Date</label>
															<input type="date" class="form-control" name="end_date" value="<?php echo $end_date; ?>" required>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label class="form-label">Commission Type</label>
															<select class="form-control" name="type">
																<option value="all" <?php echo $type == 'all' ? 'selected' : ''; ?>>All Types</option>
																<option value="signup_bonus" <?php echo $type == 'signup_bonus' ? 'selected' : ''; ?>>Signup Bonus</option>
																<option value="bot_bonus" <?php echo $type == 'bot_bonus' ? 'selected' : ''; ?>>Bot Commission</option>
																<option value="interest_discount" <?php echo $type == 'interest_discount' ? 'selected' : ''; ?>>Interest Discount</option>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label class="form-label">Referrer</label>
															<select class="form-control" name="user_id">
																<option value="0">All Referrers</option>
																<?php foreach ($top_referrers as $id => $label): ?>
																	<option value="<?php echo $id; ?>" <?php echo $user_id == $id ? 'selected' : ''; ?>><?php echo $label; ?></option>
																<?php endforeach; ?>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label class="form-label">Bot Plan</label>
															<select class="form-control" name="bot_plan_id">
																<option value="0">All Plans</option>
																<?php foreach ($bot_plans as $id => $name): ?>
																	<option value="<?php echo $id; ?>" <?php echo $bot_plan_id == $id ? 'selected' : ''; ?>><?php echo $name; ?></option>
																<?php endforeach; ?>
															</select>
														</div>
													</div>
													<div class="col-md-12 mt-3">
														<button type="submit" class="btn btn-primary">
															<i class="fas fa-filter me-1"></i> Apply Filters
														</button>
														<a href="commission_report.php" class="btn btn-secondary">
															<i class="fas fa-redo me-1"></i> Reset Filters
														</a>
														<button type="button" class="btn btn-success" onclick="showCommissionSettings()">
															<i class="fas fa-cog me-1"></i> Commission Settings
														</button>
													</div>
												</form>
											</div>
										</div>
										
										<!-- Commission Statistics -->
										<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 text-center">
														<h1 class="text-white fw-500">$<?php echo number_format($stats['total_commission'], 2); ?></h1>
														<p class="text-white mb-0">Total Commission</p>
														<small class="text-white-50"><?php echo date('M d', strtotime($start_date)); ?> - <?php echo date('M d, Y', strtotime($end_date)); ?></small>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-success pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['unique_referrers']; ?></h1>
														<p class="text-white mb-0">Active Referrers</p>
														<small class="text-white-50"><?php echo $stats['total_referred_users']; ?> referred users</small>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-warning pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500">$<?php echo number_format($stats['total_signup_bonus'], 2); ?></h1>
														<p class="text-white mb-0">Signup Bonuses</p>
														<small class="text-white-50">$<?php echo number_format($settings['signup_bonus_referrer'] ?: 0, 2); ?> per signup</small>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-danger pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500">$<?php echo number_format($stats['total_bot_commission'], 2); ?></h1>
														<p class="text-white mb-0">Bot Commissions</p>
														<small class="text-white-50">$<?php echo number_format($settings['bot_bonus'] ?: 0, 2); ?> per bot subscription</small>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Top Referrers -->
										<div class="row mb-20">
											<div class="col-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-trophy me-2"></i>Top Referrers</h5>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover">
																<thead>
																	<tr>
																		<th>Rank</th>
																		<th>Referrer</th>
																		<th>Total Commission</th>
																		<th>Signup Bonuses</th>
																		<th>Bot Commissions</th>
																		<th>Total Referrals</th>
																		<th>Actions</th>
																	</tr>
																</thead>
																<tbody>
																	<?php
																	$top_sql = "SELECT 
																				u.id,
																				u.username,
																				u.email,
																				COUNT(DISTINCT rt.referred_id) as total_referrals,
																				SUM(CASE WHEN rt.transaction_type = 'signup_bonus' THEN rt.amount ELSE 0 END) as signup_bonus,
																				SUM(CASE WHEN rt.transaction_type = 'bot_bonus' THEN rt.amount ELSE 0 END) as bot_commission,
																				SUM(rt.amount) as total_commission
																			  FROM users u
																			  LEFT JOIN referral_transactions rt ON u.id = rt.referrer_id
																			  WHERE rt.created_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59'
																			  GROUP BY u.id
																			  HAVING total_commission > 0
																			  ORDER BY total_commission DESC
																			  LIMIT 10";
																	$top_result = mysqli_query($conn, $top_sql);
																	
																	$rank = 1;
																	if (mysqli_num_rows($top_result) > 0):
																		while ($top = mysqli_fetch_assoc($top_result)):
																			$badge_color = '';
																			if ($rank == 1) $badge_color = 'bg-warning text-dark';
																			elseif ($rank == 2) $badge_color = 'bg-secondary';
																			elseif ($rank == 3) $badge_color = 'bg-danger';
																			else $badge_color = 'bg-light text-dark';
																	?>
																		<tr>
																			<td>
																				<span class="badge <?php echo $badge_color; ?> p-2 fs-16">#<?php echo $rank; ?></span>
																			</td>
																			<td>
																				<div class="d-flex align-items-center">
																					<div class="me-10">
																						<div class="bg-primary rounded-circle w-40 h-40 d-flex align-items-center justify-content-center">
																							<i class="fas fa-user text-white"></i>
																						</div>
																					</div>
																					<div>
																						<p class="mb-0 fw-500"><?php echo htmlspecialchars($top['username']); ?></p>
																						<small class="text-mute"><?php echo htmlspecialchars($top['email']); ?></small>
																					</div>
																				</div>
																			</td>
																			<td class="fw-500 text-success">$<?php echo number_format($top['total_commission'], 2); ?></td>
																			<td>$<?php echo number_format($top['signup_bonus'], 2); ?></td>
																			<td>$<?php echo number_format($top['bot_commission'], 2); ?></td>
																			<td><?php echo $top['total_referrals']; ?></td>
																			<td>
																				<a href="commission_report.php?user_id=<?php echo $top['id']; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>" class="btn btn-sm btn-light">
																					<i class="fas fa-eye"></i>
																				</a>
																				<a href="view_user.php?id=<?php echo $top['id']; ?>" class="btn btn-sm btn-light">
																					<i class="fas fa-user"></i>
																				</a>
																			</td>
																		</tr>
																	<?php 
																			$rank++;
																		endwhile;
																	else:
																	?>
																		<tr>
																			<td colspan="7" class="text-center py-20">
																				<i class="fas fa-users fa-2x text-mute mb-3"></i>
																				<h5>No commission data found</h5>
																				<p class="text-mute">Try adjusting your date range</p>
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Commission Details -->
										<div class="row">
											<div class="col-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-list me-2"></i>Commission Details</h5>
														<div class="box-controls pull-right">
															<button class="btn btn-sm btn-light" onclick="printCommissionDetails()">
																<i class="fas fa-print me-1"></i> Print
															</button>
														</div>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover table-bordered" id="commissionTable">
																<thead class="bg-light">
																	<tr>
																		<th>Date</th>
																		<th>Referrer</th>
																		<th>Referred User</th>
																		<th>Type</th>
																		<th>Bot Plan</th>
																		<th>Amount</th>
																		<th>Description</th>
																		<th>Actions</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($commission_result) > 0): ?>
																		<?php while ($commission = mysqli_fetch_assoc($commission_result)): ?>
																			<?php
																			$type_color = '';
																			$type_icon = '';
																			switch ($commission['transaction_type']) {
																				case 'signup_bonus':
																					$type_color = 'success';
																					$type_icon = 'fas fa-user-plus';
																					break;
																				case 'bot_bonus':
																					$type_color = 'primary';
																					$type_icon = 'fas fa-robot';
																					break;
																				case 'interest_discount':
																					$type_color = 'warning';
																					$type_icon = 'fas fa-percentage';
																					break;
																			}
																			?>
																			<tr>
																				<td><?php echo date('M d, Y H:i', strtotime($commission['created_at'])); ?></td>
																				<td>
																					<?php if ($commission['referrer_username']): ?>
																						<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($commission['referrer_username']); ?></p>
																								<small class="text-mute"><?php echo htmlspecialchars($commission['referrer_email']); ?></small>
																							</div>
																						</div>
																					<?php else: ?>
																						<span class="text-mute">N/A</span>
																					<?php endif; ?>
																				</td>
																				<td>
																					<?php if ($commission['referred_username']): ?>
																						<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-plus text-white fs-12"></i>
																								</div>
																							</div>
																							<div>
																								<p class="mb-0 fw-500"><?php echo htmlspecialchars($commission['referred_username']); ?></p>
																								<small class="text-mute"><?php echo htmlspecialchars($commission['referred_email']); ?></small>
																							</div>
																						</div>
																					<?php else: ?>
																						<span class="text-mute">N/A</span>
																					<?php endif; ?>
																				</td>
																				<td>
																					<span class="badge bg-<?php echo $type_color; ?>">
																						<i class="<?php echo $type_icon; ?> me-1"></i>
																						<?php echo ucfirst(str_replace('_', ' ', $commission['transaction_type'])); ?>
																					</span>
																				</td>
																				<td>
																					<?php if ($commission['plan_name']): ?>
																						<span class="badge bg-info"><?php echo htmlspecialchars($commission['plan_name']); ?></span>
																					<?php else: ?>
																						<span class="text-mute">N/A</span>
																					<?php endif; ?>
																				</td>
																				<td class="fw-500 text-success">$<?php echo number_format($commission['amount'], 2); ?></td>
																				<td><?php echo htmlspecialchars($commission['description']); ?></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">
																							<?php if ($commission['referrer_id']): ?>
																								<a class="dropdown-item" href="view_user.php?id=<?php echo $commission['referrer_id']; ?>">
																									<i class="fas fa-eye me-2"></i> View Referrer
																								</a>
																							<?php endif; ?>
																							<?php if ($commission['referred_id']): ?>
																								<a class="dropdown-item" href="view_user.php?id=<?php echo $commission['referred_id']; ?>">
																									<i class="fas fa-eye me-2"></i> View Referred
																								</a>
																							<?php endif; ?>
																							<div class="dropdown-divider"></div>
																							<a class="dropdown-item text-danger" href="#" onclick="confirmDeleteCommission(<?php echo $commission['id']; ?>)">
																								<i class="fas fa-trash me-2"></i> Delete
																							</a>
																						</div>
																					</div>
																				</td>
																			</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="8" class="text-center py-20">
																				<i class="fas fa-money-bill-wave fa-2x text-mute mb-3"></i>
																				<h5>No commission records found</h5>
																				<p class="text-mute">Try adjusting your filters or date range</p>
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Commission Summary 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-bar me-2"></i>Commission Summary</h5>
													</div>
													<div class="box-body">
														<div class="row">
															<div class="col-md-8">
																<canvas id="commissionChart" height="300"></canvas>
															</div>
															<div class="col-md-4">
																<div class="p-20">
																	<h6>Commission Breakdown</h6>
																	<div class="mt-3">
																		<div class="d-flex justify-content-between mb-2">
																			<span>Signup Bonuses:</span>
																			<strong class="text-success">$<?php echo number_format($stats['total_signup_bonus'], 2); ?></strong>
																		</div>
																		<div class="d-flex justify-content-between mb-2">
																			<span>Bot Commissions:</span>
																			<strong class="text-primary">$<?php echo number_format($stats['total_bot_commission'], 2); ?></strong>
																		</div>
																		<div class="d-flex justify-content-between mb-2">
																			<span>Interest Discounts:</span>
																			<strong class="text-warning">$<?php echo number_format($stats['total_referral_bonus'], 2); ?></strong>
																		</div>
																		<hr>
																		<div class="d-flex justify-content-between mb-2">
																			<span><strong>Total Commission:</strong></span>
																			<strong class="text-success fs-16">$<?php echo number_format($stats['total_commission'], 2); ?></strong>
																		</div>
																	</div>
																	
																	<div class="mt-20">
																		<h6>Quick Stats</h6>
																		<div class="mt-3">
																			<p><i class="fas fa-user me-2 text-primary"></i> Active Referrers: <?php echo $stats['unique_referrers']; ?></p>
																			<p><i class="fas fa-users me-2 text-success"></i> Referred Users: <?php echo $stats['total_referred_users']; ?></p>
																			<p><i class="fas fa-robot me-2 text-warning"></i> Bot Subscriptions: <?php echo mysqli_num_rows(mysqli_query($conn, "SELECT COUNT(DISTINCT referred_id) as count FROM referral_transactions WHERE transaction_type = 'bot_bonus' AND created_at BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59'")); ?></p>
																			<p><i class="fas fa-calendar me-2 text-info"></i> Date Range: <?php echo date('M d', strtotime($start_date)); ?> - <?php echo date('M d, Y', strtotime($end_date)); ?></p>
																		</div>
																	</div>
																</div>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Commission Settings -->
		<div class="modal fade" id="commissionSettingsModal" tabindex="-1" aria-labelledby="commissionSettingsModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST" action="update_commission_settings.php">
						<div class="modal-header">
							<h5 class="modal-title" id="commissionSettingsModalLabel">Commission Settings</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">Signup Bonus (Referrer)</label>
								<div class="input-group">
									<span class="input-group-text">$</span>
									<input type="number" class="form-control" name="signup_bonus_referrer" value="<?php echo number_format($settings['signup_bonus_referrer'] ?: 0, 2); ?>" step="0.01" min="0">
								</div>
								<small class="text-mute">Amount referrer gets when someone signs up</small>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Signup Bonus (Referred)</label>
								<div class="input-group">
									<span class="input-group-text">$</span>
									<input type="number" class="form-control" name="signup_bonus_referred" value="<?php echo number_format($settings['signup_bonus_referred'] ?: 0, 2); ?>" step="0.01" min="0">
								</div>
								<small class="text-mute">Amount new user gets when signing up with referral</small>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Bot Subscription Bonus</label>
								<div class="input-group">
									<span class="input-group-text">$</span>
									<input type="number" class="form-control" name="bot_bonus" value="<?php echo number_format($settings['bot_bonus'] ?: 0, 2); ?>" step="0.01" min="0">
								</div>
								<small class="text-mute">Amount referrer gets when referred user subscribes to a bot</small>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Discount per Referral (%)</label>
								<div class="input-group">
									<input type="number" class="form-control" name="discount_per_referral" value="<?php echo number_format($settings['discount_per_referral'] ?: 0, 2); ?>" step="0.01" min="0" max="100">
									<span class="input-group-text">%</span>
								</div>
								<small class="text-mute">Interest discount per successful referral</small>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Max Referral Discount (%)</label>
								<div class="input-group">
									<input type="number" class="form-control" name="max_referral_discount" value="<?php echo number_format($settings['max_referral_discount'] ?: 0, 2); ?>" step="0.01" min="0" max="100">
									<span class="input-group-text">%</span>
								</div>
								<small class="text-mute">Maximum total interest discount</small>
							</div>
							
							<div class="mb-3">
								<div class="form-check">
									<input class="form-check-input" type="checkbox" name="is_active" id="is_active" <?php echo ($settings['is_active'] ?: 1) ? 'checked' : ''; ?>>
									<label class="form-check-label" for="is_active">
										Enable Referral System
									</label>
								</div>
							</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">Save Settings</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Hidden form for deleting commission records -->
		<form method="POST" id="deleteCommissionForm" style="display: none;">
			<input type="hidden" name="action_type" value="delete_commission">
			<input type="hidden" name="commission_id" id="deleteCommissionId">
			<input type="hidden" name="admin_pin" id="deleteCommissionPin">
		</form>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- Chart.js -->
		<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></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
			$('#commissionTable').DataTable({
				"pageLength": 25,
				"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 Commission Chart
			initCommissionChart();
		});
		
		// Show Commission Settings Modal
		function showCommissionSettings() {
			$('#commissionSettingsModal').modal('show');
		}
		
		// Initialize Commission Chart
		function initCommissionChart() {
			var ctx = document.getElementById('commissionChart').getContext('2d');
			
			// Get daily commission data via AJAX
			$.ajax({
				url: 'ajax/get_daily_commission.php',
				type: 'GET',
				data: {
					start_date: '<?php echo $start_date; ?>',
					end_date: '<?php echo $end_date; ?>',
					user_id: <?php echo $user_id; ?>,
					type: '<?php echo $type; ?>'
				},
				success: function(data) {
					var chartData = JSON.parse(data);
					
					if (chartData.success) {
						var chart = new Chart(ctx, {
							type: 'bar',
							data: {
								labels: chartData.labels,
								datasets: [{
									label: 'Daily Commission',
									data: chartData.amounts,
									backgroundColor: 'rgba(54, 162, 235, 0.5)',
									borderColor: 'rgba(54, 162, 235, 1)',
									borderWidth: 1
								}]
							},
							options: {
								responsive: true,
								plugins: {
									legend: {
										position: 'top',
									},
									title: {
										display: true,
										text: 'Daily Commission Breakdown'
									}
								},
								scales: {
									y: {
										beginAtZero: true,
										ticks: {
											callback: function(value) {
												return '$' + value;
											}
										}
									}
								}
							}
						});
					}
				}
			});
		}
		
		// Export Commission Report
		function exportCommissionReport() {
			var params = new URLSearchParams({
				start_date: '<?php echo $start_date; ?>',
				end_date: '<?php echo $end_date; ?>',
				user_id: <?php echo $user_id; ?>,
				bot_plan_id: <?php echo $bot_plan_id; ?>,
				type: '<?php echo $type; ?>',
				format: 'excel'
			});
			
			window.open('export_commission.php?' + params.toString(), '_blank');
		}
		
		// Print Commission Details
		function printCommissionDetails() {
			var printContent = document.getElementById('commissionTable').outerHTML;
			var printWindow = window.open('', '_blank');
			printWindow.document.write('<html><head><title>Commission Report</title>');
			printWindow.document.write('<style>');
			printWindow.document.write('body { font-family: Arial, sans-serif; }');
			printWindow.document.write('table { width: 100%; border-collapse: collapse; }');
			printWindow.document.write('th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }');
			printWindow.document.write('th { background-color: #f2f2f2; }');
			printWindow.document.write('@media print { @page { size: landscape; } }');
			printWindow.document.write('</style>');
			printWindow.document.write('</head><body>');
			printWindow.document.write('<h2>Commission Report</h2>');
			printWindow.document.write('<p>Date Range: <?php echo date("M d, Y", strtotime($start_date)); ?> to <?php echo date("M d, Y", strtotime($end_date)); ?></p>');
			printWindow.document.write(printContent);
			printWindow.document.write('</body></html>');
			printWindow.document.close();
			printWindow.print();
		}
		
		// Confirm Delete Commission
		function confirmDeleteCommission(commissionId) {
			Swal.fire({
				title: 'Delete Commission Record?',
				html: `
					<p>This action cannot be undone. The commission record will be permanently deleted.</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="swalCommissionPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#d33',
				cancelButtonColor: '#3085d6',
				confirmButtonText: 'Delete Record',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('swalCommissionPin').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 delete form
					document.getElementById('deleteCommissionId').value = commissionId;
					document.getElementById('deleteCommissionPin').value = result.value.pin;
					document.getElementById('deleteCommissionForm').submit();
				}
			});
		}
		
		// Auto-refresh stats every 60 seconds
		setInterval(function() {
			$.ajax({
				url: 'ajax/get_commission_stats.php',
				type: 'GET',
				data: {
					start_date: '<?php echo $start_date; ?>',
					end_date: '<?php echo $end_date; ?>',
					user_id: <?php echo $user_id; ?>,
					bot_plan_id: <?php echo $bot_plan_id; ?>,
					type: '<?php echo $type; ?>'
				},
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update the stat cards
						$('.bg-gradient-primary .fw-500').text('$' + stats.total_commission);
						$('.bg-gradient-success .fw-500').text(stats.unique_referrers);
						$('.bg-gradient-warning .fw-500').text('$' + stats.total_signup_bonus);
						$('.bg-gradient-danger .fw-500').text('$' + stats.total_bot_commission);
						
						// Show notification
						Swal.fire({
							toast: true,
							position: 'top-end',
							icon: 'success',
							title: 'Commission Stats Updated',
							showConfirmButton: false,
							timer: 1500
						});
					}
				}
			});
		}, 60000); // 60 seconds
		</script>
		
		<style>
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		.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;
		}
		</style>
		
	</body>
</html>