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

// Check admin session
$admin_id = $_SESSION['admin_id'] ?: 1;
$admin_name = $_SESSION['admin_name'] ?: 'System Admin';
$admin_role = $_SESSION['admin_role'] ?: 'admin';

// Get admin email for notifications
$adminQuery = mysqli_query($conn, "SELECT email, first_name FROM users WHERE id='$admin_id'");
$adminData = mysqli_fetch_assoc($adminQuery);
$admin_email = $adminData['email'] ?? 'admin@system.com';
$admin_first_name = $adminData['first_name'] ?? 'Administrator';

// PIN for confirmation
$admin_pin = "1234"; // Change this to a secure PIN

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $action_type = isset($_POST['action_type']) ? $_POST['action_type'] : '';
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        switch ($action_type) {
            case 'update_settings':
                $old_settings = $settings;
                
                $signup_bonus_referrer = floatval($_POST['signup_bonus_referrer']);
                $signup_bonus_referred = floatval($_POST['signup_bonus_referred']);
                $bot_bonus = floatval($_POST['bot_bonus']);
                $max_referral_discount = floatval($_POST['max_referral_discount']);
                $discount_per_referral = floatval($_POST['discount_per_referral']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                $update_sql = "UPDATE referral_settings SET 
                              signup_bonus_referrer = $signup_bonus_referrer,
                              signup_bonus_referred = $signup_bonus_referred,
                              bot_bonus = $bot_bonus,
                              max_referral_discount = $max_referral_discount,
                              discount_per_referral = $discount_per_referral,
                              is_active = $is_active,
                              updated_at = NOW()
                              WHERE id = 1";
                
                if (mysqli_query($conn, $update_sql)) {
                    logAdminActivity(
                        'Referral Settings Updated',
                        "Updated referral program settings",
                        'Referrals',
                        1,
                        'referral_settings'
                    );
                    
                    // NOTIFICATION: Referral Settings Updated (ADMIN)
                    $mail_subject = "Referral Program Settings Updated";
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Referral Settings Updated</h2>
                                        
                                        <p class='message'>
                                            The referral program settings have been modified by an administrator.
                                        </p>

                                        <!-- Settings Changes -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                <strong>Update Time:</strong> " . date('F j, Y g:i A') . "<br>
                                                <strong>Program Status:</strong> " . ($is_active == 1 ? '<span style="color: #28a745;">Active</span>' : '<span style="color: #dc3545;">Inactive</span>') . "<br><br>
                                                
                                                <strong>New Settings:</strong><br>
                                                • Signup Bonus (Referrer): $" . number_format($signup_bonus_referrer, 2) . "<br>
                                                • Signup Bonus (Referred): $" . number_format($signup_bonus_referred, 2) . "<br>
                                                • Bot Subscription Bonus: $" . number_format($bot_bonus, 2) . "<br>
                                                • Max Referral Discount: " . ($max_referral_discount * 100) . "%<br>
                                                • Discount Per Referral: " . ($discount_per_referral * 100) . "%
                                            </div>
                                        </div>

                                        <!-- Changes Summary -->
                                        <div style='background: " . ($is_active == 1 ? '#e7f3ff' : '#fff3cd') . "; border: 1px solid " . ($is_active == 1 ? '#b3d7ff' : '#ffeaa7') . "; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                            <h4 style='color: " . ($is_active == 1 ? '#0056b3' : '#856404') . ";'>📊 Changes Summary</h4>
                                            <p style='color: " . ($is_active == 1 ? '#0056b3' : '#856404') . ";'>
                                                <strong>Referrer Bonus:</strong> $" . number_format($old_settings['signup_bonus_referrer'], 2) . " → $" . number_format($signup_bonus_referrer, 2) . "<br>
                                                <strong>Referred Bonus:</strong> $" . number_format($old_settings['signup_bonus_referred'], 2) . " → $" . number_format($signup_bonus_referred, 2) . "<br>
                                                <strong>Bot Bonus:</strong> $" . number_format($old_settings['bot_bonus'], 2) . " → $" . number_format($bot_bonus, 2) . "<br>
                                                <strong>Status Change:</strong> " . ($old_settings['is_active'] == 1 ? 'Active' : 'Inactive') . " → " . ($is_active == 1 ? 'Active' : 'Inactive') . "
                                            </p>
                                        </div>

                                        <!-- Impact Analysis -->
                                        <div class='next-steps'>
                                            <h3 style='color: #2c3e50;'>🎯 Impact on Users</h3>
                                            <p style='color: #6c757d;'>
                                                • New referrals will earn " . ($is_active == 1 ? 'updated bonus amounts' : 'no bonuses (program inactive)') . "<br>
                                                • Existing referrals and pending bonuses remain unaffected<br>
                                                • Users will " . ($is_active == 1 ? 'see active program status' : 'be notified program is paused') . "<br>
                                                • All future referrals will follow new rates
                                            </p>
                                        </div>

                                        <!-- Admin Actions -->
                                        <div style='text-align: center; margin: 30px 0;'>
                                            <a href='" . $myUrl . "/admin/referral-settings.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                View Settings
                                            </a>
                                            <a href='" . $myUrl . "/admin/referral-stats.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                View Statistics
                                            </a>
                                        </div>
                                    </div>";

                    require_once("../proccess/admin_mailer.php");
                    
                    $success = "Referral settings updated successfully!";
                } else {
                    $error = "Failed to update settings.";
                }
                break;
                
            case 'add_bonus':
                $user_id = intval($_POST['user_id']);
                $bonus_type = mysqli_real_escape_string($conn, $_POST['bonus_type']);
                $amount = floatval($_POST['amount']);
                $description = mysqli_real_escape_string($conn, $_POST['description']);
                
                // Get user info
                $user_sql = "SELECT username, email, first_name, referral_balance FROM users WHERE id = $user_id";
                $user_result = mysqli_query($conn, $user_sql);
                $user_data = mysqli_fetch_assoc($user_result);
                $username = $user_data['username'] ?: 'Unknown';
                $user_email = $user_data['email'] ?: '';
                $first_name = $user_data['first_name'] ?: $username;
                $old_balance = $user_data['referral_balance'] ?: 0;
                $new_balance = $old_balance + $amount;
                
                // Add bonus transaction
                $txn_sql = "INSERT INTO referral_transactions (referrer_id, referred_id, transaction_type, amount, description, created_at) 
                           VALUES ($user_id, 0, '$bonus_type', $amount, '$description', NOW())";
                
                if (mysqli_query($conn, $txn_sql)) {
                    $transaction_id = mysqli_insert_id($conn);
                    
                    // Update user's referral balance
                    $update_user = "UPDATE users SET referral_balance = referral_balance + $amount WHERE id = $user_id";
                    mysqli_query($conn, $update_user);
                    
                    // Log activity
                    logAdminActivity(
                        'Manual Bonus Added',
                        "Added $$amount $bonus_type bonus to user $username",
                        'Referrals',
                        $user_id,
                        'users'
                    );
                    
                    // NOTIFICATION: Manual Bonus Added (USER)
                    $mail_subject = "Referral Bonus Added to Your Account!";
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>! 🎉</h2>
                                        
                                        <p class='message'>
                                            A manual referral bonus has been added to your account by our admin team!
                                        </p>

                                        <!-- Bonus Details -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>Bonus Amount:</strong> <span style='color: #28a745; font-size: 24px; font-weight: bold;'>$" . number_format($amount, 2) . "</span><br>
                                                <strong>Bonus Type:</strong> " . ucwords(str_replace('_', ' ', $bonus_type)) . "<br>
                                                <strong>Description:</strong> " . $description . "<br>
                                                <strong>Previous Balance:</strong> $" . number_format($old_balance, 2) . "<br>
                                                <strong>New Balance:</strong> $" . number_format($new_balance, 2) . "<br>
                                                <strong>Date Added:</strong> " . date('F j, Y g:i A') . "<br>
                                                <strong>Transaction ID:</strong> REF-" . $transaction_id . "
                                            </div>
                                        </div>

                                        <!-- Why Bonus Was Added -->
                                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                            <h4 style='color: #0056b3;'>💡 About This Bonus</h4>
                                            <p style='color: #0056b3;'>
                                                This bonus was added manually by our administration team.<br>
                                                Common reasons include:<br>
                                                • Special promotion or event<br>
                                                • Compensation for platform issue<br>
                                                • Referral program adjustment<br>
                                                • Loyalty reward
                                            </p>
                                        </div>

                                        <!-- Action Buttons -->
                                        <div style='text-align: center; margin: 30px 0;'>
                                            <a href='" . $myUrl . "/referrals.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                View Referral Dashboard
                                            </a>
                                            <a href='" . $myUrl . "/withdraw.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #28a745; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                Withdraw Earnings
                                            </a>
                                        </div>

                                        <!-- Support Section -->
                                        <div class='support-section'>
                                            <p class='support-text'>Questions about this bonus?</p>
                                            <a href='" . $myUrl . "/support.php' class='support-link'>Contact Support</a>
                                        </div>
                                    </div>";

                    if ($user_email) {
                        require_once("../proccess/mail_sender.php");
                    }
                    
                    // NOTIFICATION: Manual Bonus Added (ADMIN)
                    $admin_mail_subject = "Manual Bonus Added - User: " . $username;
                    $admin_mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Manual Bonus Added</h2>
                                            
                                            <p class='message'>
                                                A manual referral bonus has been added to a user account.
                                            </p>

                                            <!-- Bonus Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>User ID:</strong> " . $user_id . "<br>
                                                    <strong>Username:</strong> " . $username . "<br>
                                                    <strong>Email:</strong> " . $user_email . "<br>
                                                    <strong>Bonus Amount:</strong> $" . number_format($amount, 2) . "<br>
                                                    <strong>Bonus Type:</strong> " . ucwords(str_replace('_', ' ', $bonus_type)) . "<br>
                                                    <strong>Description:</strong> " . $description . "<br>
                                                    <strong>Added By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                    <strong>Transaction ID:</strong> REF-" . $transaction_id . "<br>
                                                    <strong>Date Added:</strong> " . date('F j, Y g:i A') . "
                                                </div>
                                            </div>

                                            <!-- Admin Actions -->
                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/admin/users.php?id=" . $user_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                    View User Profile
                                                </a>
                                            </div>
                                        </div>";

                    require_once("../proccess/admin_mailer.php");
                    
                    $success = "Bonus added successfully!";
                } else {
                    $error = "Failed to add bonus.";
                }
                break;
                
            case 'process_payout':
                $user_id = intval($_POST['user_id']);
                $amount = floatval($_POST['amount']);
                
                // Get user info
                $user_sql = "SELECT username, email, first_name, referral_balance FROM users WHERE id = $user_id";
                $user_result = mysqli_query($conn, $user_sql);
                $user_data = mysqli_fetch_assoc($user_result);
                $username = $user_data['username'] ?: 'Unknown';
                $user_email = $user_data['email'] ?: '';
                $first_name = $user_data['first_name'] ?: $username;
                $current_balance = $user_data['referral_balance'] ?: 0;
                $new_balance = $current_balance - $amount;
                
                if ($amount <= $current_balance && $amount > 0) {
                    // Deduct from referral balance
                    $update_sql = "UPDATE users SET referral_balance = referral_balance - $amount WHERE id = $user_id";
                    
                    if (mysqli_query($conn, $update_sql)) {
                        // Record payout transaction
                        $txn_sql = "INSERT INTO transactions (user_id, amount, type, status, date, description, created_at) 
                                   VALUES ($user_id, $amount, 'withdrawal', 'completed', NOW(), 'Referral bonus payout', NOW())";
                        mysqli_query($conn, $txn_sql);
                        $transaction_id = mysqli_insert_id($conn);
                        
                        // Log referral transaction
                        $ref_sql = "INSERT INTO referral_transactions (referrer_id, referred_id, transaction_type, amount, description, created_at) 
                                   VALUES ($user_id, 0, 'payout', $amount, 'Referral bonus payout processed', NOW())";
                        mysqli_query($conn, $ref_sql);
                        
                        logAdminActivity(
                            'Referral Payout Processed',
                            "Processed $$amount referral payout for user $username",
                            'Referrals',
                            $user_id,
                            'users'
                        );
                        
                        // NOTIFICATION: Referral Payout Processed (USER)
                        $mail_subject = "Referral Payout Processed Successfully!";
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                                            
                                            <p class='message'>
                                                Your referral payout has been processed successfully! 🎉
                                            </p>

                                            <!-- Payout Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Payout Amount:</strong> <span style='color: #28a745; font-size: 24px; font-weight: bold;'>$" . number_format($amount, 2) . "</span><br>
                                                    <strong>Previous Balance:</strong> $" . number_format($current_balance, 2) . "<br>
                                                    <strong>New Balance:</strong> $" . number_format($new_balance, 2) . "<br>
                                                    <strong>Payout Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                    <strong>Transaction ID:</strong> TXN-" . $transaction_id . "<br>
                                                    <strong>Status:</strong> <span style='color: #28a745; font-weight: bold;'>COMPLETED</span>
                                                </div>
                                            </div>

                                            <!-- Action Buttons -->
                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/transactions.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                    View Transaction History
                                                </a>
                                            </div>
                                        </div>";

                        if ($user_email) {
                            require_once("../proccess/mail_sender.php");
                        }
                        
                        // NOTIFICATION: Referral Payout Processed (ADMIN)
                        $admin_mail_subject = "Referral Payout Processed - $" . number_format($amount, 2);
                        $admin_mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>Referral Payout Processed</h2>
                                                
                                                <p class='message'>
                                                    A referral payout has been processed for a user.
                                                </p>

                                                <!-- Payout Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>User ID:</strong> " . $user_id . "<br>
                                                        <strong>Username:</strong> " . $username . "<br>
                                                        <strong>Email:</strong> " . $user_email . "<br>
                                                        <strong>Payout Amount:</strong> $" . number_format($amount, 2) . "<br>
                                                        <strong>Previous Balance:</strong> $" . number_format($current_balance, 2) . "<br>
                                                        <strong>New Balance:</strong> $" . number_format($new_balance, 2) . "<br>
                                                        <strong>Processed By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                        <strong>Transaction ID:</strong> TXN-" . $transaction_id . "<br>
                                                        <strong>Date:</strong> " . date('F j, Y g:i A') . "
                                                    </div>
                                                </div>

                                                <!-- Admin Actions -->
                                                <div style='text-align: center; margin: 30px 0;'>
                                                    <a href='" . $myUrl . "/admin/users.php?id=" . $user_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                        View User Profile
                                                    </a>
                                                </div>
                                            </div>";

                        require_once("../proccess/admin_mailer.php");
                        
                        $success = "Payout processed successfully!";
                    } else {
                        $error = "Failed to process payout.";
                    }
                } else {
                    $error = "Invalid amount or insufficient balance.";
                }
                break;
        }
    }
}

// Get current settings
$settings_sql = "SELECT * FROM referral_settings WHERE id = 1";
$settings_result = mysqli_query($conn, $settings_sql);
$settings = mysqli_fetch_assoc($settings_result);

// If no settings exist, create default
if (!$settings) {
    $create_sql = "INSERT INTO referral_settings (signup_bonus_referrer, signup_bonus_referred, bot_bonus, max_referral_discount, discount_per_referral, is_active) 
                   VALUES (100.00, 50.00, 200.00, 1.00, 0.10, 1)";
    mysqli_query($conn, $create_sql);
    $settings = array(
        'signup_bonus_referrer' => 100.00,
        'signup_bonus_referred' => 50.00,
        'bot_bonus' => 200.00,
        'max_referral_discount' => 1.00,
        'discount_per_referral' => 0.10,
        'is_active' => 1
    );
}

// Get filter parameters
$filter_type = isset($_GET['type']) ? $_GET['type'] : '';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';

// Build referral query
$referral_sql = "SELECT r.*, 
                 u1.username as referrer_name, u1.email as referrer_email,
                 u2.username as referred_name, u2.email as referred_email
                 FROM referrals r
                 LEFT JOIN users u1 ON r.user_id = u1.id
                 LEFT JOIN users u2 ON r.referred_by = u2.id
                 WHERE 1=1";

if ($filter_type == 'has_referrals') {
    $referral_sql .= " AND r.referred_by IS NOT NULL";
} elseif ($filter_type == 'no_referrals') {
    $referral_sql .= " AND r.referred_by IS NULL";
}

if ($search) {
    $referral_sql .= " AND (u1.username LIKE '%$search%' OR u1.email LIKE '%$search%' OR u2.username LIKE '%$search%' OR u2.email LIKE '%$search%')";
}

$referral_sql .= " ORDER BY r.created_at DESC";
$referral_result = mysqli_query($conn, $referral_sql);

// Get top referrers
$top_referrers_sql = "SELECT u.id, u.username, u.email, COUNT(r.id) as referral_count,
                      COALESCE(SUM(rt.amount), 0) as total_earnings,
                      u.referral_balance as current_balance
                      FROM users u
                      LEFT JOIN referrals r ON u.id = r.referred_by
                      LEFT JOIN referral_transactions rt ON u.id = rt.referrer_id AND rt.transaction_type IN ('signup_bonus', 'bot_bonus')
                      GROUP BY u.id
                      HAVING referral_count > 0
                      ORDER BY referral_count DESC, total_earnings DESC
                      LIMIT 10";
$top_referrers_result = mysqli_query($conn, $top_referrers_sql);

// Get referral transactions
$transaction_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 20";
$transaction_result = mysqli_query($conn, $transaction_sql);

// Get stats
$stats_sql = "SELECT 
              COUNT(DISTINCT r.referred_by) as active_referrers,
              COUNT(r.id) as total_referrals,
              COUNT(DISTINCT r.user_id) as users_with_code,
              COALESCE(SUM(rt.amount), 0) as total_bonus_paid
              FROM referrals r
              LEFT JOIN referral_transactions rt ON rt.transaction_type IN ('signup_bonus', 'bot_bonus')";
$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_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-user-plus me-2"></i>Referral System Management</h4>
									</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 text-center">
														<h1 class="text-white fw-500"><?php echo $stats['active_referrers'] ?: 0; ?></h1>
														<p class="text-white mb-0">Active Referrers</p>
													</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['total_referrals'] ?: 0; ?></h1>
														<p class="text-white mb-0">Total Referrals</p>
													</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 $stats['users_with_code'] ?: 0; ?></h1>
														<p class="text-white mb-0">Users with Code</p>
													</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_bonus_paid'] ?: 0, 2); ?></h1>
														<p class="text-white mb-0">Total Bonus Paid</p>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Settings Card -->
										<div class="box mb-20">
											<div class="box-header">
												<h5 class="box-title"><i class="fas fa-cog me-2"></i>Referral Program Settings</h5>
												<span class="badge bg-<?php echo $settings['is_active'] ? 'success' : 'danger'; ?>">
													<?php echo $settings['is_active'] ? 'Active' : 'Inactive'; ?>
												</span>
											</div>
											<div class="box-body">
												<form method="POST">
													<input type="hidden" name="action_type" value="update_settings">
													
													<div class="row">
														<div class="col-md-6">
															<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" step="0.01" min="0" value="<?php echo $settings['signup_bonus_referrer']; ?>" required>
																	<span class="input-group-text">per referral</span>
																</div>
																<small class="text-mute">Amount referrer gets when someone signs up using their code</small>
															</div>
														</div>
														<div class="col-md-6">
															<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" step="0.01" min="0" value="<?php echo $settings['signup_bonus_referred']; ?>" required>
																	<span class="input-group-text">on signup</span>
																</div>
																<small class="text-mute">Amount new user gets when signing up with a referral code</small>
															</div>
														</div>
													</div>
													
													<div class="row">
														<div class="col-md-6">
															<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" step="0.01" min="0" value="<?php echo $settings['bot_bonus']; ?>" required>
																	<span class="input-group-text">per bot subscription</span>
																</div>
																<small class="text-mute">Bonus when referred user subscribes to a bot</small>
															</div>
														</div>
														<div class="col-md-6">
															<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" step="0.01" min="0" max="100" value="<?php echo $settings['max_referral_discount']; ?>" required>
																	<span class="input-group-text">%</span>
																</div>
																<small class="text-mute">Maximum discount percentage from referrals</small>
															</div>
														</div>
													</div>
													
													<div class="row">
														<div class="col-md-6">
															<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" step="0.01" min="0" max="10" value="<?php echo $settings['discount_per_referral']; ?>" required>
																	<span class="input-group-text">%</span>
																</div>
																<small class="text-mute">Discount percentage added per successful referral</small>
															</div>
														</div>
														<div class="col-md-6">
															<div class="mb-3">
																<label class="form-label">Program Status</label>
																<div class="form-check form-switch mt-2">
																	<input class="form-check-input" type="checkbox" name="is_active" value="1" <?php echo $settings['is_active'] ? 'checked' : ''; ?>>
																	<label class="form-check-label">Enable referral program</label>
																</div>
															</div>
														</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>
													
													<button type="submit" class="btn btn-primary">
														<i class="fas fa-save me-1"></i> Update Settings
													</button>
												</form>
											</div>
										</div>
										
										<?php if (isset($success)): ?>
											<div class="alert alert-success alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
											</div>
										<?php endif; ?>
										
										<?php if (isset($error)): ?>
											<div class="alert alert-danger alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
											</div>
										<?php endif; ?>
										
										<!-- Top Referrers -->
										<div class="box mb-20">
											<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>User</th>
																<th>Referrals</th>
																<th>Total Earnings</th>
																<th>Current Balance</th>
																<th>Actions</th>
															</tr>
														</thead>
														<tbody>
															<?php if (mysqli_num_rows($top_referrers_result) > 0): ?>
																<?php $rank = 1; ?>
																<?php while ($referrer = mysqli_fetch_assoc($top_referrers_result)): ?>
																	<tr>
																		<td>
																			<?php if ($rank == 1): ?>
																				<span class="badge bg-warning"><i class="fas fa-crown"></i> 1st</span>
																			<?php elseif ($rank == 2): ?>
																				<span class="badge bg-secondary">2nd</span>
																			<?php elseif ($rank == 3): ?>
																				<span class="badge bg-danger">3rd</span>
																			<?php else: ?>
																				<span class="badge bg-light text-dark"><?php echo $rank; ?>th</span>
																			<?php endif; ?>
																		</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">ID: <?php echo $referrer['id']; ?></small>
																				</div>
																			</div>
																		</td>
																		<td>
																			<h4 class="fw-500"><?php echo $referrer['referral_count']; ?></h4>
																			<small class="text-mute">successful referrals</small>
																		</td>
																		<td>
																			<h4 class="fw-500 text-success">$<?php echo number_format($referrer['total_earnings'], 2); ?></h4>
																			<small class="text-mute">lifetime earnings</small>
																		</td>
																		<td>
																			<h4 class="fw-500 text-primary">$<?php echo number_format($referrer['current_balance'], 2); ?></h4>
																			<small class="text-mute">available for payout</small>
																		</td>
																		<td>
																			<button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addBonusModal" data-user-id="<?php echo $referrer['id']; ?>" data-username="<?php echo htmlspecialchars($referrer['username']); ?>">
																				<i class="fas fa-gift me-1"></i> Add Bonus
																			</button>
																			<?php if ($referrer['current_balance'] > 0): ?>
																				<button class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#payoutModal" data-user-id="<?php echo $referrer['id']; ?>" data-username="<?php echo htmlspecialchars($referrer['username']); ?>" data-balance="<?php echo $referrer['current_balance']; ?>">
																					<i class="fas fa-money-bill-wave me-1"></i> Payout
																				</button>
																			<?php endif; ?>
																		</td>
																	</tr>
																	<?php $rank++; ?>
																<?php endwhile; ?>
															<?php else: ?>
																<tr>
																	<td colspan="6" class="text-center py-20">
																		<i class="fas fa-users fa-2x text-mute mb-3"></i>
																		<h5>No referrers yet</h5>
																		<p class="text-mute">No users have made referrals yet</p>
																	</td>
																</tr>
															<?php endif; ?>
														</tbody>
													</table>
												</div>
											</div>
										</div>
										
										<!-- Tabs for more details -->
										<div class="row">
											<div class="col-12">
												<ul class="nav nav-tabs" role="tablist">
													<li class="nav-item">
														<a class="nav-link active" data-bs-toggle="tab" href="#referrals">All Referrals</a>
													</li>
													<li class="nav-item">
														<a class="nav-link" data-bs-toggle="tab" href="#transactions">Bonus Transactions</a>
													</li>
												</ul>
												
												<div class="tab-content mt-3">
													<!-- Referrals Tab -->
													<div class="tab-pane fade show active" id="referrals">
														<!-- Filters -->
														<div class="row mb-3">
															<div class="col-md-8">
																<form method="GET" class="row">
																	<div class="col-md-4">
																		<div class="form-group">
																			<select class="form-control" name="type" onchange="this.form.submit()">
																				<option value="">All Referrals</option>
																				<option value="has_referrals" <?php echo $filter_type == 'has_referrals' ? 'selected' : ''; ?>>With Referrers</option>
																				<option value="no_referrals" <?php echo $filter_type == 'no_referrals' ? 'selected' : ''; ?>>Without Referrers</option>
																			</select>
																		</div>
																	</div>
																	<div class="col-md-5">
																		<div class="form-group">
																			<input type="text" class="form-control" name="search" placeholder="Search users..." value="<?php echo htmlspecialchars($search); ?>">
																		</div>
																	</div>
																	<div class="col-md-3">
																		<button type="submit" class="btn btn-primary"><i class="fas fa-search me-1"></i> Search</button>
																		<?php if ($search || $filter_type): ?>
																			<a href="referrals.php" class="btn btn-secondary">Clear</a>
																		<?php endif; ?>
																	</div>
																</form>
															</div>
														</div>
														
														<div class="table-responsive">
															<table class="table table-hover" id="referralsTable">
																<thead>
																	<tr>
																		<th>ID</th>
																		<th>User</th>
																		<th>Referral Code</th>
																		<th>Referred By</th>
																		<th>Created Date</th>
																		<th>Actions</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($referral_result) > 0): ?>
																		<?php while ($ref = mysqli_fetch_assoc($referral_result)): ?>
																			<tr>
																				<td><?php echo $ref['id']; ?></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($ref['referrer_name']); ?></p>
																							<small class="text-mute"><?php echo htmlspecialchars($ref['referrer_email']); ?></small>
																						</div>
																					</div>
																				</td>
																				<td>
																					<code class="bg-light p-2 rounded"><?php echo htmlspecialchars($ref['referral_code']); ?></code>
																				</td>
																				<td>
																					<?php if ($ref['referred_name']): ?>
																						<div class="d-flex align-items-center">
																							<div class="me-10">
																								<div class="bg-success rounded-circle w-40 h-40 d-flex align-items-center justify-content-center">
																									<i class="fas fa-user-friends text-white"></i>
																								</div>
																							</div>
																							<div>
																								<p class="mb-0 fw-500"><?php echo htmlspecialchars($ref['referred_name']); ?></p>
																								<small class="text-mute"><?php echo htmlspecialchars($ref['referred_email']); ?></small>
																							</div>
																						</div>
																					<?php else: ?>
																						<span class="text-mute">No referrer</span>
																					<?php endif; ?>
																				</td>
																				<td>
																					<p class="mb-0"><?php echo date('M d, Y', strtotime($ref['created_at'])); ?></p>
																					<small class="text-mute"><?php echo date('H:i', strtotime($ref['created_at'])); ?></small>
																				</td>
																				<td>
																					<button class="btn btn-sm btn-light" data-bs-toggle="modal" data-bs-target="#addBonusModal" data-user-id="<?php echo $ref['user_id']; ?>" data-username="<?php echo htmlspecialchars($ref['referrer_name']); ?>">
																						<i class="fas fa-gift"></i>
																					</button>
																				</td>
																			</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="6" class="text-center py-20">
																				<i class="fas fa-user-plus fa-2x text-mute mb-3"></i>
																				<h5>No referrals found</h5>
																				<p class="text-mute">No referral records yet</p>
																			</td>
																		</tr>
																	<?php endif; ?>
												</tbody>
											</table>
										</div>
									</div>
									
									<!-- Transactions Tab -->
									<div class="tab-pane fade" id="transactions">
										<div class="table-responsive">
											<table class="table table-hover" id="transactionsTable">
												<thead>
													<tr>
														<th>ID</th>
														<th>Referrer</th>
														<th>Referred</th>
														<th>Type</th>
														<th>Amount</th>
														<th>Description</th>
														<th>Date</th>
													</tr>
												</thead>
												<tbody>
													<?php if (mysqli_num_rows($transaction_result) > 0): ?>
														<?php while ($txn = mysqli_fetch_assoc($transaction_result)): ?>
															<?php
															$type_colors = array(
																'signup_bonus' => 'success',
																'bot_bonus' => 'primary',
																'interest_discount' => 'info',
																'payout' => 'warning'
															);
															$type_color = $type_colors[$txn['transaction_type']] ?: 'secondary';
															?>
															<tr>
																<td><?php echo $txn['id']; ?></td>
																<td>
																	<?php if ($txn['referrer_name']): ?>
																		<p class="mb-0 fw-500"><?php echo htmlspecialchars($txn['referrer_name']); ?></p>
																		<small class="text-mute">ID: <?php echo $txn['referrer_id']; ?></small>
																	<?php else: ?>
																		<span class="text-mute">System</span>
																	<?php endif; ?>
																</td>
																<td>
																	<?php if ($txn['referred_name']): ?>
																		<p class="mb-0"><?php echo htmlspecialchars($txn['referred_name']); ?></p>
																		<small class="text-mute">ID: <?php echo $txn['referred_id']; ?></small>
																	<?php else: ?>
																		<span class="text-mute">-</span>
																	<?php endif; ?>
																</td>
																<td>
																	<span class="badge bg-<?php echo $type_color; ?>">
																		<?php echo str_replace('_', ' ', ucfirst($txn['transaction_type'])); ?>
																	</span>
																</td>
																<td>
																	<h5 class="fw-500 <?php echo $txn['transaction_type'] == 'payout' ? 'text-danger' : 'text-success'; ?>">
																		<?php echo $txn['transaction_type'] == 'payout' ? '-' : ''; ?>$<?php echo number_format($txn['amount'], 2); ?>
																	</h5>
																</td>
																<td><?php echo htmlspecialchars($txn['description']); ?></td>
																<td>
																	<p class="mb-0"><?php echo date('M d, Y', strtotime($txn['created_at'])); ?></p>
																	<small class="text-mute"><?php echo date('H:i', strtotime($txn['created_at'])); ?></small>
																</td>
															</tr>
														<?php endwhile; ?>
													<?php else: ?>
														<tr>
															<td colspan="7" class="text-center py-20">
																<i class="fas fa-exchange-alt fa-2x text-mute mb-3"></i>
																<h5>No transactions yet</h5>
																<p class="text-mute">No referral transactions recorded</p>
															</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 -->
		
		<!-- Modal for Adding 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">
						<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="action_type" value="add_bonus">
							<input type="hidden" name="user_id" id="bonusUserId">
							
							<div class="mb-3">
								<label class="form-label">User</label>
								<input type="text" class="form-control" id="bonusUsername" readonly>
							</div>
							
							<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 Subscription Bonus</option>
									<option value="interest_discount">Interest Discount</option>
									<option value="manual">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 placeholder="0.00">
							</div>
							
							<div class="mb-3">
								<label class="form-label">Description (Optional)</label>
								<textarea class="form-control" name="description" rows="3" placeholder="Enter reason for bonus..."></textarea>
							</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 Processing Payout -->
		<div class="modal fade" id="payoutModal" tabindex="-1" aria-labelledby="payoutModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="payoutModalLabel">Process Referral Payout</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="process_payout">
							<input type="hidden" name="user_id" id="payoutUserId">
							
							<div class="mb-3">
								<label class="form-label">User</label>
								<input type="text" class="form-control" id="payoutUsername" readonly>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Available Balance</label>
								<input type="text" class="form-control" id="availableBalance" readonly>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Payout Amount ($) <span class="text-danger">*</span></label>
								<input type="number" class="form-control" name="amount" step="0.01" min="0.01" required placeholder="0.00">
								<small class="text-mute">Enter amount to payout from referral balance</small>
							</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">Process Payout</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- 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 DataTables
			$('#referralsTable, #transactionsTable').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"
					}
				}
			});
			
			// Add Bonus Modal
			$('#addBonusModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var userId = button.data('user-id');
				var username = button.data('username');
				var modal = $(this);
				
				modal.find('#bonusUserId').val(userId);
				modal.find('#bonusUsername').val(username);
				modal.find('.modal-title').text('Add Bonus to ' + username);
			});
			
			// Payout Modal
			$('#payoutModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var userId = button.data('user-id');
				var username = button.data('username');
				var balance = button.data('balance');
				var modal = $(this);
				
				modal.find('#payoutUserId').val(userId);
				modal.find('#payoutUsername').val(username);
				modal.find('#availableBalance').val('$' + balance);
				modal.find('input[name="amount"]').attr('max', balance);
				modal.find('.modal-title').text('Process Payout for ' + username);
			});
			
			// Auto-refresh stats every 30 seconds
			setInterval(function() {
				$.ajax({
					url: 'ajax/get_referral_stats.php',
					type: 'GET',
					success: function(data) {
						var stats = JSON.parse(data);
						if (stats.success) {
							// Update the stat cards
							$('.bg-gradient-primary .fw-500').text(stats.active_referrers);
							$('.bg-gradient-success .fw-500').text(stats.total_referrals);
							$('.bg-gradient-warning .fw-500').text(stats.users_with_code);
							$('.bg-gradient-danger .fw-500').text('$' + stats.total_bonus_paid);
						}
					}
				});
			}, 30000); // 30 seconds
		});
		</script>
		
		<style>
		.nav-tabs .nav-link.active {
			background-color: #f8f9fa;
			border-color: #dee2e6 #dee2e6 #f8f9fa;
		}
		.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);
		}
		code {
			font-family: 'Courier New', monospace;
			font-size: 14px;
		}
		</style>
		
	</body>
</html>