<?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';

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

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

if (mysqli_num_rows($settings_result) > 0) {
    $settings = mysqli_fetch_assoc($settings_result);
} else {
    // Default settings if not exists
    $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',
        'minimum_bot_subscription' => '1000.00',
        'bonus_payment_threshold' => '500.00',
        'referral_expiry_days' => '30',
        'is_active' => 1
    );
}

// Get referral statistics
$stats_sql = "SELECT 
    (SELECT COUNT(*) FROM referrals) as total_referrals,
    (SELECT COUNT(DISTINCT referred_by) FROM referrals WHERE referred_by IS NOT NULL) as total_referrers,
    (SELECT COUNT(*) FROM users WHERE referred_by IS NOT NULL) as referred_users,
    (SELECT COALESCE(SUM(amount), 0) FROM referral_transactions) as total_bonus_paid";

$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);

// 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. Changes not saved.";
    } else {
        switch ($action_type) {
            case 'update_settings':
                $old_settings = $settings; // Store old settings for comparison
                
                $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;
                $minimum_bot_subscription = floatval($_POST['minimum_bot_subscription']);
                $bonus_payment_threshold = floatval($_POST['bonus_payment_threshold']);
                $referral_expiry_days = intval($_POST['referral_expiry_days']);
                
                // Check if settings exist
                $check_sql = "SELECT id FROM referral_settings WHERE id = 1";
                $check_result = mysqli_query($conn, $check_sql);
                
                if (mysqli_num_rows($check_result) > 0) {
                    // Update existing settings
                    $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,
                            minimum_bot_subscription = '$minimum_bot_subscription',
                            bonus_payment_threshold = '$bonus_payment_threshold',
                            referral_expiry_days = $referral_expiry_days,
                            updated_at = NOW()
                            WHERE id = 1";
                } else {
                    // Insert new settings
                    $sql = "INSERT INTO referral_settings (id, signup_bonus_referrer, signup_bonus_referred, bot_bonus, max_referral_discount, discount_per_referral, is_active, minimum_bot_subscription, bonus_payment_threshold, referral_expiry_days, updated_at) 
                            VALUES (1, '$signup_bonus_referrer', '$signup_bonus_referred', '$bot_bonus', '$max_referral_discount', '$discount_per_referral', $is_active, '$minimum_bot_subscription', '$bonus_payment_threshold', $referral_expiry_days, NOW())";
                }
                
                if (mysqli_query($conn, $sql)) {
                    // Log admin activity
                    logAdminActivity(
                        'Referral Settings Updated',
                        "Updated referral program settings",
                        'Referral System',
                        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 updated by an administrator.
                                        </p>

                                        <!-- Settings Update Details -->
                                        <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>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                                <strong>Program Status:</strong> <span style='color: " . ($is_active ? '#28a745' : '#dc3545') . "; font-weight: bold;'>" . ($is_active ? 'ACTIVE' : 'DISABLED') . "</span>
                                            </div>
                                        </div>

                                        <!-- Settings Comparison Table -->
                                        <div class='settings-comparison'>
                                            <h3 style='color: #2c3e50;'>Settings Changes</h3>
                                            <table style='width: 100%; border-collapse: collapse; margin: 15px 0;'>
                                                <thead>
                                                    <tr style='background: #f8f9fa;'>
                                                        <th style='border: 1px solid #dee2e6; padding: 10px; text-align: left;'>Setting</th>
                                                        <th style='border: 1px solid #dee2e6; padding: 10px; text-align: left;'>Old Value</th>
                                                        <th style='border: 1px solid #dee2e6; padding: 10px; text-align: left;'>New Value</th>
                                                        <th style='border: 1px solid #dee2e6; padding: 10px; text-align: left;'>Change</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'><strong>Signup Bonus (Referrer)</strong></td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>$" . number_format($old_settings['signup_bonus_referrer'], 2) . "</td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>$" . number_format($signup_bonus_referrer, 2) . "</td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>" . 
                                                            ($signup_bonus_referrer > $old_settings['signup_bonus_referrer'] ? '<span style="color: #28a745;">↑ +$' . number_format($signup_bonus_referrer - $old_settings['signup_bonus_referrer'], 2) . '</span>' : 
                                                            ($signup_bonus_referrer < $old_settings['signup_bonus_referrer'] ? '<span style="color: #dc3545;">↓ -$' . number_format($old_settings['signup_bonus_referrer'] - $signup_bonus_referrer, 2) . '</span>' : 
                                                            '<span style="color: #6c757d;">Unchanged</span>')) . "
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'><strong>Signup Bonus (Referred)</strong></td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>$" . number_format($old_settings['signup_bonus_referred'], 2) . "</td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>$" . number_format($signup_bonus_referred, 2) . "</td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>" . 
                                                            ($signup_bonus_referred > $old_settings['signup_bonus_referred'] ? '<span style="color: #28a745;">↑ +$' . number_format($signup_bonus_referred - $old_settings['signup_bonus_referred'], 2) . '</span>' : 
                                                            ($signup_bonus_referred < $old_settings['signup_bonus_referred'] ? '<span style="color: #dc3545;">↓ -$' . number_format($old_settings['signup_bonus_referred'] - $signup_bonus_referred, 2) . '</span>' : 
                                                            '<span style="color: #6c757d;">Unchanged</span>')) . "
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'><strong>Bot Subscription Bonus</strong></td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>$" . number_format($old_settings['bot_bonus'], 2) . "</td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>$" . number_format($bot_bonus, 2) . "</td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>" . 
                                                            ($bot_bonus > $old_settings['bot_bonus'] ? '<span style="color: #28a745;">↑ +$' . number_format($bot_bonus - $old_settings['bot_bonus'], 2) . '</span>' : 
                                                            ($bot_bonus < $old_settings['bot_bonus'] ? '<span style="color: #dc3545;">↓ -$' . number_format($old_settings['bot_bonus'] - $bot_bonus, 2) . '</span>' : 
                                                            '<span style="color: #6c757d;">Unchanged</span>')) . "
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'><strong>Min Bot Subscription</strong></td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>$" . number_format($old_settings['minimum_bot_subscription'], 2) . "</td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>$" . number_format($minimum_bot_subscription, 2) . "</td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>" . 
                                                            ($minimum_bot_subscription > $old_settings['minimum_bot_subscription'] ? '<span style="color: #ffc107;">↑ Higher threshold</span>' : 
                                                            ($minimum_bot_subscription < $old_settings['minimum_bot_subscription'] ? '<span style="color: #17a2b8;">↓ Lower threshold</span>' : 
                                                            '<span style="color: #6c757d;">Unchanged</span>')) . "
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'><strong>Bonus Payment Threshold</strong></td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>$" . number_format($old_settings['bonus_payment_threshold'], 2) . "</td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>$" . number_format($bonus_payment_threshold, 2) . "</td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>" . 
                                                            ($bonus_payment_threshold > $old_settings['bonus_payment_threshold'] ? '<span style="color: #ffc107;">↑ Higher threshold</span>' : 
                                                            ($bonus_payment_threshold < $old_settings['bonus_payment_threshold'] ? '<span style="color: #17a2b8;">↓ Lower threshold</span>' : 
                                                            '<span style="color: #6c757d;">Unchanged</span>')) . "
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'><strong>Referral Expiry Days</strong></td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>" . $old_settings['referral_expiry_days'] . " days</td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>" . $referral_expiry_days . " days</td>
                                                        <td style='border: 1px solid #dee2e6; padding: 10px;'>" . 
                                                            ($referral_expiry_days > $old_settings['referral_expiry_days'] ? '<span style="color: #ffc107;">↑ +' . ($referral_expiry_days - $old_settings['referral_expiry_days']) . ' days</span>' : 
                                                            ($referral_expiry_days < $old_settings['referral_expiry_days'] ? '<span style="color: #17a2b8;">↓ -' . ($old_settings['referral_expiry_days'] - $referral_expiry_days) . ' days</span>' : 
                                                            '<span style="color: #6c757d;">Unchanged</span>')) . "
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>

                                        <!-- Program Impact Summary -->
                                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                            <h4 style='color: #0056b3;'>📊 Program Impact Summary</h4>
                                            <p style='color: #0056b3;'>
                                                <strong>Referral Program:</strong> " . ($is_active ? 'Active & Accepting New Referrals' : 'Disabled - No New Referrals') . "<br>
                                                <strong>Maximum Referrer Bonus:</strong> $" . number_format($signup_bonus_referrer + $bot_bonus, 2) . " per qualified referral<br>
                                                <strong>Bonus Eligibility:</strong> Referrals must subscribe to bot with $" . number_format($minimum_bot_subscription, 2) . "+<br>
                                                <strong>Bonus Withdrawal:</strong> Available once balance exceeds $" . number_format($bonus_payment_threshold, 2) . "<br>
                                                <strong>Referral Tracking:</strong> Links expire after " . $referral_expiry_days . " days of inactivity
                                            </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/referrals.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 Referrals
                                            </a>
                                        </div>
                                    </div>";

                    // Send admin notification
                    require_once("../proccess/admin_mailer.php");
                    
                    $success = "Referral settings updated successfully!";
                    
                    // Refresh settings
                    $settings_result = mysqli_query($conn, $settings_sql);
                    $settings = mysqli_fetch_assoc($settings_result);
                } else {
                    $error = "Failed to update settings: " . mysqli_error($conn);
                }
                break;
                
            case 'add_manual_bonus':
                $referrer_id = intval($_POST['referrer_id']);
                $bonus_type = mysqli_real_escape_string($conn, $_POST['bonus_type']);
                $amount = floatval($_POST['amount']);
                $description = mysqli_real_escape_string($conn, $_POST['description']);
                
                // Get referrer details
                $user_sql = "SELECT username, email, first_name, referral_balance FROM users WHERE id = $referrer_id";
                $user_result = mysqli_query($conn, $user_sql);
                
                if (mysqli_num_rows($user_result) > 0) {
                    $user_data = mysqli_fetch_assoc($user_result);
                    $username = $user_data['username'];
                    $user_email = $user_data['email'];
                    $first_name = $user_data['first_name'];
                    $old_balance = $user_data['referral_balance'];
                    $new_balance = $old_balance + $amount;
                    
                    // Add to referral transactions
                    $insert_sql = "INSERT INTO referral_transactions (referrer_id, referred_id, transaction_type, amount, description, created_at) 
                                   VALUES ($referrer_id, 0, '$bonus_type', $amount, '$description', NOW())";
                    
                    if (mysqli_query($conn, $insert_sql)) {
                        $transaction_id = mysqli_insert_id($conn);
                        
                        // Update user's referral balance
                        $update_sql = "UPDATE users SET referral_balance = referral_balance + $amount WHERE id = $referrer_id";
                        mysqli_query($conn, $update_sql);
                        
                        // Log admin activity
                        logAdminActivity(
                            'Manual Referral Bonus Added',
                            "Added manual $bonus_type bonus of $$amount to user $username (ID: $referrer_id)",
                            'Referral System',
                            $referrer_id,
                            'users'
                        );
                        
                        // NOTIFICATION: Manual Bonus Added (ADMIN)
                        $mail_subject = "Manual Referral Bonus Added";
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Manual Referral Bonus Added</h2>
                                            
                                            <p class='message'>
                                                A manual referral bonus has been added to a user's account by an administrator.
                                            </p>

                                            <!-- Bonus Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Transaction ID:</strong> BONUS-" . $transaction_id . "<br>
                                                    <strong>User ID:</strong> " . $referrer_id . "<br>
                                                    <strong>Username:</strong> " . $username . "<br>
                                                    <strong>Email:</strong> " . $user_email . "<br>
                                                    <strong>Bonus Type:</strong> " . ucfirst(str_replace('_', ' ', $bonus_type)) . "<br>
                                                    <strong>Amount:</strong> <span style='color: #28a745;'>+$" . number_format($amount, 2) . "</span><br>
                                                    <strong>Previous Balance:</strong> $" . number_format($old_balance, 2) . "<br>
                                                    <strong>New Balance:</strong> $" . number_format($new_balance, 2) . "<br>
                                                    <strong>Description:</strong> " . $description . "<br>
                                                    <strong>Added By:</strong> " . $admin_name . " (ID: " . $admin_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=" . $referrer_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>
                                                <a href='" . $myUrl . "/admin/referral-transactions.php?user_id=" . $referrer_id . "' 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 Transactions
                                                </a>
                                            </div>
                                        </div>";

                        // Send admin notification
                        require_once("../proccess/admin_mailer.php");
                        
                        // NOTIFICATION: Manual Bonus Received (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'>
                                                <strong>Good news!</strong> A referral bonus has been added to your account by the " . $sitename . " admin team.
                                            </p>

                                            <!-- Bonus Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Bonus Amount:</strong> <span style='color: #28a745;'>+$" . number_format($amount, 2) . "</span><br>
                                                    <strong>Bonus Type:</strong> " . ucfirst(str_replace('_', ' ', $bonus_type)) . "<br>
                                                    <strong>Description:</strong> " . $description . "<br>
                                                    <strong>Previous Balance:</strong> $" . number_format($old_balance, 2) . "<br>
                                                    <strong>New Referral Balance:</strong> $" . number_format($new_balance, 2) . "<br>
                                                    <strong>Date:</strong> " . date('F j, Y g:i A') . "
                                                </div>
                                            </div>

                                            <!-- How to Use -->
                                            <div class='next-steps'>
                                                <h3 style='color: #2c3e50;'>💰 How to Use Your Referral Balance</h3>
                                                <ul style='color: #6c757d;'>
                                                    <li>Subscribe to AI trading bots</li>
                                                    <li>Withdraw to your wallet (minimum: $" . number_format($settings['bonus_payment_threshold'], 2) . ")</li>
                                                    <li>Keep earning more through referrals</li>
                                                </ul>
                                            </div>

                                            <!-- Action Button -->
                                            <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;'>
                                                    View Your Referrals
                                                </a>
                                            </div>
                                        </div>";

                        // Send user notification
                        $user_email = $user_data['email'];
                        $first_name = $user_data['first_name'];
                        require_once("../proccess/mail_sender.php");
                        
                        $success = "Manual bonus added successfully!";
                    } else {
                        $error = "Failed to add bonus: " . mysqli_error($conn);
                    }
                } else {
                    $error = "Referrer not found!";
                }
                break;
        }
    }
}

// Get top referrers
$top_referrers_sql = "SELECT 
    u.id,
    u.username,
    u.email,
    u.first_name,
    u.last_name,
    u.referral_balance,
    COUNT(r.id) as total_referrals,
    (SELECT COUNT(*) FROM users WHERE referred_by = u.id AND status = 'verified') as verified_referrals,
    (SELECT COALESCE(SUM(amount), 0) FROM referral_transactions WHERE referrer_id = u.id) as total_earned
    FROM users u
    LEFT JOIN referrals r ON u.id = r.referred_by
    WHERE u.referral_balance > 0 OR EXISTS (SELECT 1 FROM referrals WHERE referred_by = u.id)
    GROUP BY u.id
    ORDER BY total_referrals DESC
    LIMIT 10";

$top_referrers_result = mysqli_query($conn, $top_referrers_sql);
?>

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

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

		  	<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<div class="container-full">
					<!-- Main content -->
					<section class="content">
						<div class="row">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h4 class="box-title"><i class="fas fa-user-plus me-2"></i>Referral Program Settings</h4>
									</div>
									<div class="box-body">
										
										<?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; ?>
										
										<!-- 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['total_referrals']; ?></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-success pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['total_referrers']; ?></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-warning pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['referred_users']; ?></h1>
														<p class="text-white mb-0">Referred Users</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-info pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500">$<?php echo number_format($stats['total_bonus_paid'], 2); ?></h1>
														<p class="text-white mb-0">Total Bonus Paid</p>
													</div>
												</div>
											</div>
										</div>
										
										<div class="row">
											<!-- Settings Form -->
											<div class="col-lg-8">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-cog me-2"></i>Program Configuration</h5>
													</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">
																	<h6 class="border-bottom pb-2 mb-3">Signup Bonuses</h6>
																	
																	<div class="mb-3">
																		<label class="form-label">Referrer Bonus ($) <span class="text-danger">*</span></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" required 
																				   value="<?php echo $settings['signup_bonus_referrer']; ?>">
																		</div>
																		<small class="text-mute">Bonus paid to referrer when someone signs up using their link</small>
																	</div>
																	
																	<div class="mb-3">
																		<label class="form-label">Referred User Bonus ($) <span class="text-danger">*</span></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" required 
																				   value="<?php echo $settings['signup_bonus_referred']; ?>">
																		</div>
																		<small class="text-mute">Bonus paid to new user when they sign up using a referral link</small>
																	</div>
																</div>
																
																<div class="col-md-6">
																	<h6 class="border-bottom pb-2 mb-3">Bot Subscription Bonuses</h6>
																	
																	<div class="mb-3">
																		<label class="form-label">Bot Subscription Bonus ($) <span class="text-danger">*</span></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" required 
																				   value="<?php echo $settings['bot_bonus']; ?>">
																		</div>
																		<small class="text-mute">Bonus paid to referrer when referred user subscribes to a bot</small>
																	</div>
																	
																	<div class="mb-3">
																		<label class="form-label">Minimum Bot Subscription ($)</label>
																		<div class="input-group">
																			<span class="input-group-text">$</span>
																			<input type="number" class="form-control" name="minimum_bot_subscription" 
																				   step="0.01" min="0" 
																				   value="<?php echo isset($settings['minimum_bot_subscription']) ? $settings['minimum_bot_subscription'] : '0.00'; ?>">
																		</div>
																		<small class="text-mute">Minimum bot subscription amount to qualify for bonus</small>
																	</div>
																</div>
															</div>
															
															<div class="row mt-3">
																<div class="col-md-6">
																	<h6 class="border-bottom pb-2 mb-3">Discount Settings</h6>
																	
																	<div class="mb-3">
																		<label class="form-label">Discount per Referral (%) <span class="text-danger">*</span></label>
																		<div class="input-group">
																			<input type="number" class="form-control" name="discount_per_referral" 
																				   step="0.01" min="0" max="100" required 
																				   value="<?php echo $settings['discount_per_referral']; ?>">
																			<span class="input-group-text">%</span>
																		</div>
																		<small class="text-mute">Discount percentage added per successful referral</small>
																	</div>
																	
																	<div class="mb-3">
																		<label class="form-label">Maximum Discount (%) <span class="text-danger">*</span></label>
																		<div class="input-group">
																			<input type="number" class="form-control" name="max_referral_discount" 
																				   step="0.01" min="0" max="100" required 
																				   value="<?php echo $settings['max_referral_discount']; ?>">
																			<span class="input-group-text">%</span>
																		</div>
																		<small class="text-mute">Maximum discount percentage a user can earn</small>
																	</div>
																</div>
																
																<div class="col-md-6">
																	<h6 class="border-bottom pb-2 mb-3">Program Rules</h6>
																	
																	<div class="mb-3">
																		<label class="form-label">Bonus Payment Threshold ($)</label>
																		<div class="input-group">
																			<span class="input-group-text">$</span>
																			<input type="number" class="form-control" name="bonus_payment_threshold" 
																				   step="0.01" min="0" 
																				   value="<?php echo isset($settings['bonus_payment_threshold']) ? $settings['bonus_payment_threshold'] : '50.00'; ?>">
																		</div>
																		<small class="text-mute">Minimum balance required to request bonus withdrawal</small>
																	</div>
																	
																	<div class="mb-3">
																		<label class="form-label">Referral Expiry (Days)</label>
																		<input type="number" class="form-control" name="referral_expiry_days" 
																			   min="0" 
																			   value="<?php echo isset($settings['referral_expiry_days']) ? $settings['referral_expiry_days'] : '30'; ?>">
																		<small class="text-mute">Number of days before referral link expires (0 = never expires)</small>
																	</div>
																	
																	<div class="mb-3">
																		<div class="form-check form-switch">
																			<input class="form-check-input" type="checkbox" name="is_active" id="isActive" 
																				   value="1" <?php echo $settings['is_active'] ? 'checked' : ''; ?>>
																			<label class="form-check-label" for="isActive">Enable Referral Program</label>
																		</div>
																		<small class="text-mute">Turn the referral program on or off globally</small>
																	</div>
																</div>
															</div>
															
															<div class="row mt-4">
																<div class="col-md-6">
																	<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="col-md-6 text-end">
																	<button type="submit" class="btn btn-primary btn-lg mt-4">
																		<i class="fas fa-save me-2"></i> Save Settings
																	</button>
																</div>
															</div>
														</form>
													</div>
												</div>
											</div>
											
											<!-- Top Referrers & Manual Bonus -->
											<div class="col-lg-4">
												<!-- 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 p-0">
														<div class="table-responsive">
															<table class="table table-hover mb-0">
																<thead>
																	<tr>
																		<th>User</th>
																		<th>Referrals</th>
																		<th>Balance</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($top_referrers_result) > 0): ?>
																		<?php while ($referrer = mysqli_fetch_assoc($top_referrers_result)): ?>
																			<tr>
																				<td>
																					<p class="mb-0 fw-500"><?php echo htmlspecialchars($referrer['username']); ?></p>
																					<small class="text-mute"><?php echo htmlspecialchars($referrer['email']); ?></small>
																				</td>
																				<td>
																					<span class="badge bg-primary"><?php echo $referrer['total_referrals']; ?></span>
																					<br><small class="text-mute"><?php echo $referrer['verified_referrals']; ?> verified</small>
																				</td>
																				<td>
																					<span class="fw-500 text-success">$<?php echo number_format($referrer['referral_balance'], 2); ?></span>
																				</td>
																			</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="3" class="text-center py-3">
																				<i class="fas fa-users text-mute me-2"></i> No referrers yet
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
												
												<!-- Manual Bonus Form -->
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-gift me-2"></i>Manual Bonus Award</h5>
													</div>
													<div class="box-body">
														<form method="POST">
															<input type="hidden" name="action_type" value="add_manual_bonus">
															
															<div class="mb-3">
																<label class="form-label">Referrer User ID <span class="text-danger">*</span></label>
																<input type="number" class="form-control" name="referrer_id" required 
																	   placeholder="Enter user ID">
																<small class="text-mute">Find user ID from Users page</small>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Bonus Type <span class="text-danger">*</span></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="manual_bonus">Manual Bonus</option>
																	<option value="special_bonus">Special Bonus</option>
																</select>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Amount ($) <span class="text-danger">*</span></label>
																<div class="input-group">
																	<span class="input-group-text">$</span>
																	<input type="number" class="form-control" name="amount" 
																		   step="0.01" min="0.01" required 
																		   placeholder="0.00">
																</div>
															</div>
															
															<div class="mb-3">
																<label class="form-label">Description <span class="text-danger">*</span></label>
																<textarea class="form-control" name="description" rows="3" required 
																		  placeholder="Reason for manual 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>
															
															<button type="submit" class="btn btn-success w-100">
																<i class="fas fa-gift me-2"></i> Award Bonus
															</button>
														</form>
													</div>
												</div>
												
												<!-- Program Status -->
												<div class="box mt-20">
													<div class="box-body text-center">
														<div class="mb-3">
															<i class="fas fa-user-plus fa-3x text-<?php echo $settings['is_active'] ? 'success' : 'danger'; ?>"></i>
														</div>
														<h4 class="fw-500">Program Status: 
															<span class="badge bg-<?php echo $settings['is_active'] ? 'success' : 'danger'; ?>">
																<?php echo $settings['is_active'] ? 'ACTIVE' : 'INACTIVE'; ?>
															</span>
														</h4>
														<p class="text-mute mb-0">
															Last Updated: 
															<?php echo isset($settings['updated_at']) ? date('M d, Y H:i', strtotime($settings['updated_at'])) : 'Never'; ?>
														</p>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Recent Referral Transactions -->
										<div class="row mt-20">
											<div class="col-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-exchange-alt me-2"></i>Recent Referral Transactions</h5>
														<a href="referral_transactions.php" class="btn btn-sm btn-light">View All</a>
													</div>
													<div class="box-body p-0">
														<div class="table-responsive">
															<?php
															$recent_txns_sql = "SELECT 
																rt.*,
																u1.username as referrer_name,
																u2.username as referred_name
																FROM referral_transactions rt
																LEFT JOIN users u1 ON rt.referrer_id = u1.id
																LEFT JOIN users u2 ON rt.referred_id = u2.id
																ORDER BY rt.created_at DESC 
																LIMIT 10";
															$recent_txns_result = mysqli_query($conn, $recent_txns_sql);
															?>
															
															<table class="table table-hover mb-0">
																<thead>
																	<tr>
																		<th>Date</th>
																		<th>Referrer</th>
																		<th>Referred</th>
																		<th>Type</th>
																		<th>Amount</th>
																		<th>Description</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($recent_txns_result) > 0): ?>
																		<?php while ($txn = mysqli_fetch_assoc($recent_txns_result)): ?>
																			<?php
																			$type_colors = array(
																				'signup_bonus' => 'success',
																				'bot_bonus' => 'primary',
																				'manual_bonus' => 'warning',
																				'special_bonus' => 'info'
																			);
																			$type_color = isset($type_colors[$txn['transaction_type']]) ? $type_colors[$txn['transaction_type']] : 'secondary';
																			?>
																			<tr>
																				<td><?php echo date('M d, H:i', strtotime($txn['created_at'])); ?></td>
																				<td>
																					<?php if ($txn['referrer_name']): ?>
																						<span class="fw-500"><?php echo htmlspecialchars($txn['referrer_name']); ?></span>
																					<?php else: ?>
																						<span class="text-mute">User #<?php echo $txn['referrer_id']; ?></span>
																					<?php endif; ?>
																				</td>
																				<td>
																					<?php if ($txn['referred_name']): ?>
																						<span class="fw-500"><?php echo htmlspecialchars($txn['referred_name']); ?></span>
																					<?php elseif ($txn['referred_id'] > 0): ?>
																						<span class="text-mute">User #<?php echo $txn['referred_id']; ?></span>
																					<?php else: ?>
																						<span class="text-mute">Manual</span>
																					<?php endif; ?>
																				</td>
																				<td>
																					<span class="badge bg-<?php echo $type_color; ?>">
																						<?php echo str_replace('_', ' ', ucfirst($txn['transaction_type'])); ?>
																					</span>
																				</td>
																				<td class="fw-500 text-success">$<?php echo number_format($txn['amount'], 2); ?></td>
																				<td><small><?php echo htmlspecialchars($txn['description']); ?></small></td>
																			</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="6" class="text-center py-3">
																				<i class="fas fa-exchange-alt text-mute me-2"></i> No referral transactions yet
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Program Summary -->
										<div class="row mt-20">
											<div class="col-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-bar me-2"></i>Program Summary</h5>
													</div>
													<div class="box-body">
														<div class="row">
															<div class="col-md-6">
																<h6 class="mb-3">Current Settings</h6>
																<table class="table table-sm">
																	<tr>
																		<td><strong>Referrer Signup Bonus:</strong></td>
																		<td class="text-end">$<?php echo number_format($settings['signup_bonus_referrer'], 2); ?></td>
																	</tr>
																	<tr>
																		<td><strong>Referred Signup Bonus:</strong></td>
																		<td class="text-end">$<?php echo number_format($settings['signup_bonus_referred'], 2); ?></td>
																	</tr>
																	<tr>
																		<td><strong>Bot Subscription Bonus:</strong></td>
																		<td class="text-end">$<?php echo number_format($settings['bot_bonus'], 2); ?></td>
																	</tr>
																	<tr>
																		<td><strong>Discount per Referral:</strong></td>
																		<td class="text-end"><?php echo number_format($settings['discount_per_referral'], 2); ?>%</td>
																	</tr>
																	<tr>
																		<td><strong>Maximum Discount:</strong></td>
																		<td class="text-end"><?php echo number_format($settings['max_referral_discount'], 2); ?>%</td>
																	</tr>
																	<tr>
																		<td><strong>Program Status:</strong></td>
																		<td class="text-end">
																			<span class="badge bg-<?php echo $settings['is_active'] ? 'success' : 'danger'; ?>">
																				<?php echo $settings['is_active'] ? 'Active' : 'Inactive'; ?>
																			</span>
																		</td>
																	</tr>
																</table>
															</div>
															<div class="col-md-6">
																<h6 class="mb-3">Program Performance</h6>
																<div class="progress-stacked mb-3">
																	<div class="progress" role="progressbar" style="width: <?php echo $stats['total_referrals'] > 0 ? '70%' : '0%'; ?>">
																		<div class="progress-bar bg-success">Total Referrals: <?php echo $stats['total_referrals']; ?></div>
																	</div>
																	<div class="progress" role="progressbar" style="width: <?php echo $stats['referred_users'] > 0 ? '30%' : '0%'; ?>">
																		<div class="progress-bar bg-primary">Active Users: <?php echo $stats['referred_users']; ?></div>
																	</div>
																</div>
																
																<div class="d-flex justify-content-between align-items-center mb-3">
																	<span>Conversion Rate:</span>
																	<span class="fw-500">
																		<?php 
																		if ($stats['total_referrals'] > 0) {
																			echo number_format(($stats['referred_users'] / $stats['total_referrals']) * 100, 2);
																		} else {
																			echo '0.00';
																		}
																		?>%
																	</span>
																</div>
																
																<div class="d-flex justify-content-between align-items-center mb-3">
																	<span>Average Bonus per Referrer:</span>
																	<span class="fw-500 text-success">
																		$<?php 
																		if ($stats['total_referrers'] > 0) {
																			echo number_format($stats['total_bonus_paid'] / $stats['total_referrers'], 2);
																		} else {
																			echo '0.00';
																		}
																		?>
																	</span>
																</div>
																
																<div class="d-flex justify-content-between align-items-center">
																	<span>Program ROI:</span>
																	<span class="fw-500 text-info">
																		<?php 
																		// Simplified ROI calculation
																		if ($stats['total_bonus_paid'] > 0) {
																			$estimated_revenue = $stats['referred_users'] * 100; // Assume $100 revenue per user
																			$roi = (($estimated_revenue - $stats['total_bonus_paid']) / $stats['total_bonus_paid']) * 100;
																			echo number_format($roi, 2) . '%';
																		} else {
																			echo 'N/A';
																		}
																		?>
																	</span>
																</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 -->
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<script>
		$(document).ready(function() {
			// Auto-refresh stats every 30 seconds
			setInterval(function() {
				$.ajax({
					url: 'ajax/get_referral_stats1.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.total_referrals);
							$('.bg-gradient-success .fw-500').text(stats.total_referrers);
							$('.bg-gradient-warning .fw-500').text(stats.referred_users);
							$('.bg-gradient-info .fw-500').text('$' + stats.total_bonus_paid);
							
							// Update program status
							if (stats.is_active) {
								$('#isActive').prop('checked', true);
								$('.fa-user-plus').removeClass('text-danger').addClass('text-success');
								$('.badge').removeClass('bg-danger').addClass('bg-success').text('ACTIVE');
							} else {
								$('#isActive').prop('checked', false);
								$('.fa-user-plus').removeClass('text-success').addClass('text-danger');
								$('.badge').removeClass('bg-success').addClass('bg-danger').text('INACTIVE');
							}
							
							// Show notification
							Swal.fire({
								toast: true,
								position: 'top-end',
								icon: 'success',
								title: 'Stats Updated',
								showConfirmButton: false,
								timer: 1500
							});
						}
					}
				});
			}, 30000); // 30 seconds
			
			// Form validation
			$('form').submit(function(e) {
				var pin = $(this).find('input[name="admin_pin"]').val();
				if (!pin || pin.length !== 4) {
					e.preventDefault();
					Swal.fire({
						icon: 'error',
						title: 'Invalid PIN',
						text: 'Please enter a valid 4-digit PIN'
					});
				}
			});
			
			// Settings change confirmation
			$('input[name="is_active"]').change(function() {
				var status = $(this).is(':checked') ? 'activate' : 'deactivate';
				Swal.fire({
					title: 'Confirm Program ' + (status === 'activate' ? 'Activation' : 'Deactivation'),
					text: 'Are you sure you want to ' + status + ' the referral program?',
					icon: 'warning',
					showCancelButton: true,
					confirmButtonText: 'Yes, ' + status + ' it!',
					cancelButtonText: 'Cancel'
				}).then((result) => {
					if (!result.isConfirmed) {
						$(this).prop('checked', !$(this).is(':checked'));
					}
				});
			});
		});
		
		// Preview calculations
		function previewReferralEarnings() {
			var referrerBonus = parseFloat($('input[name="signup_bonus_referrer"]').val()) || 0;
			var referredBonus = parseFloat($('input[name="signup_bonus_referred"]').val()) || 0;
			var botBonus = parseFloat($('input[name="bot_bonus"]').val()) || 0;
			
			var totalPerReferral = referrerBonus + referredBonus + botBonus;
			
			Swal.fire({
				title: 'Referral Earnings Preview',
				html: `
					<div class="text-start">
						<p><strong>Per Successful Referral:</strong></p>
						<ul>
							<li>Referrer gets: <span class="text-success">$${referrerBonus.toFixed(2)}</span></li>
							<li>Referred user gets: <span class="text-success">$${referredBonus.toFixed(2)}</span></li>
							<li>When bot subscribed: <span class="text-success">+$${botBonus.toFixed(2)}</span></li>
						</ul>
						<p class="mt-3"><strong>Total potential earnings per referral:</strong> <span class="fw-500 text-primary">$${totalPerReferral.toFixed(2)}</span></p>
					</div>
				`,
				icon: 'info',
				confirmButtonText: 'OK'
			});
		}
		</script>
		
		<style>
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		.form-check-input:checked {
			background-color: #28a745;
			border-color: #28a745;
		}
		.form-check-input {
			width: 3em;
			height: 1.5em;
		}
		.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;
		}
		.progress {
			height: 20px;
		}
		</style>
		
	</body>
</html>