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

// Admin info
$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";

// Handle actions
$action = isset($_GET['action']) ? $_GET['action'] : '';
$bonus_id = isset($_GET['id']) ? intval($_GET['bonus_id']) : 0;

// 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'] : '';
    $target_id = isset($_POST['bonus_id']) ? intval($_POST['bonus_id']) : 0;
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        switch ($action_type) {
            case 'pay_bonus':
                $bonus_id = isset($_POST['bonus_id']) ? intval($_POST['bonus_id']) : 0;
                $payment_method = isset($_POST['payment_method']) ? mysqli_real_escape_string($conn, $_POST['payment_method']) : '';
                $transaction_id = isset($_POST['transaction_id']) ? mysqli_real_escape_string($conn, $_POST['transaction_id']) : '';
                $notes = isset($_POST['notes']) ? mysqli_real_escape_string($conn, $_POST['notes']) : '';
                
                if ($bonus_id > 0) {
                    // Get bonus details
                    $bonus_sql = "SELECT b.*, 
                                         u1.first_name as referrer_first, u1.last_name as referrer_last, u1.email as referrer_email,
                                         u2.first_name as referred_first, u2.last_name as referred_last, u2.email as referred_email
                                  FROM referral_bonuses b
                                  LEFT JOIN users u1 ON b.referrer_id = u1.id
                                  LEFT JOIN users u2 ON b.referred_id = u2.id
                                  WHERE b.id = $bonus_id";
                    $bonus_result = mysqli_query($conn, $bonus_sql);
                    $bonus_data = mysqli_fetch_assoc($bonus_result);
                    
                    if ($bonus_data) {
                        $referrer_id = $bonus_data['referrer_id'];
                        $referred_id = $bonus_data['referred_id'];
                        $amount = $bonus_data['amount'];
                        $bonus_type = $bonus_data['bonus_type'];
                        $referrer_name = $bonus_data['referrer_first'] ?: $bonus_data['referrer_name'] ?? 'User';
                        $referrer_email = $bonus_data['referrer_email'];
                        $referred_name = $bonus_data['referred_first'] ?: $bonus_data['referred_name'] ?? 'User';
                        
                        // Get old balance for notification
                        $balance_sql = "SELECT fund_balance, available_balance, referral_balance FROM users WHERE id = $referrer_id";
                        $balance_result = mysqli_query($conn, $balance_sql);
                        $balance_data = mysqli_fetch_assoc($balance_result);
                        $old_fund_balance = $balance_data['fund_balance'] ?? 0;
                        $old_available_balance = $balance_data['available_balance'] ?? 0;
                        $old_referral_balance = $balance_data['referral_balance'] ?? 0;
                        
                        // Update bonus status
                        $update_sql = "UPDATE referral_bonuses SET 
                                      status = 'paid',
                                      paid_date = NOW(),
                                      payment_method = '$payment_method',
                                      transaction_id = '$transaction_id',
                                      admin_notes = CONCAT(IFNULL(admin_notes, ''), '\nPayment processed: $notes'),
                                      processed_by = '$admin_name'
                                      WHERE id = $bonus_id";
                        
                        if (mysqli_query($conn, $update_sql)) {
                            // Add to user's balance
                            mysqli_query($conn, "UPDATE users SET 
                                               fund_balance = fund_balance + $amount,
                                               available_balance = available_balance + $amount,
                                               referral_balance = referral_balance + $amount
                                               WHERE id = $referrer_id");
                            
                            // Get new balances for notification
                            $new_fund_balance = $old_fund_balance + $amount;
                            $new_available_balance = $old_available_balance + $amount;
                            $new_referral_balance = $old_referral_balance + $amount;
                            
                            // Add transaction record
                            $txn_sql = "INSERT INTO transactions (user_id, amount, type, status, date, description, created_at) 
                                       VALUES ($referrer_id, $amount, 'referral', 'completed', NOW(), 'Referral bonus payment - Bonus ID: $bonus_id', NOW())";
                            mysqli_query($conn, $txn_sql);
                            $transaction_id_new = mysqli_insert_id($conn);
                            
                            // Log activity
                            logAdminActivity(
                                'Referral Bonus Paid',
                                "Paid referral bonus of $$amount to user ID $referrer_id (Bonus ID: $bonus_id)",
                                'Referrals',
                                $bonus_id,
                                'referral_bonuses'
                            );
                            
                            // NOTIFICATION: Bonus Paid (USER - Referrer)
                            $mail_subject = "Referral Bonus Paid - $$amount";
                            $mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>Congratulations <span class='user-name'>" . $referrer_name . "</span>! 🎉</h2>
                                                
                                                <p class='message'>
                                                    Your referral bonus of <strong>$" . number_format($amount, 2) . "</strong> has been successfully processed and added to your account!
                                                </p>

                                                <!-- Bonus Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Bonus ID:</strong> BONUS-" . $bonus_id . "<br>
                                                        <strong>Amount Received:</strong> <span style='color: #28a745; font-weight: bold;'>$" . number_format($amount, 2) . "</span><br>
                                                        <strong>Bonus Type:</strong> " . ucfirst(str_replace('_', ' ', $bonus_type)) . "<br>
                                                        <strong>Payment Method:</strong> " . $payment_method . "<br>
                                                        <strong>Transaction ID:</strong> " . ($transaction_id ?: 'REF-' . $bonus_id) . "<br>
                                                        <strong>Processed Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                        <strong>Processed By:</strong> Admin Team<br>
                                                        <strong>Status:</strong> <span style='color: #28a745; font-weight: bold;'>PAID</span>
                                                    </div>
                                                </div>

                                                <!-- Referred User Info -->
                                                " . ($referred_id ? "
                                                <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                    <h4 style='color: #495057;'>👤 Referred User</h4>
                                                    <p style='color: #495057;'>
                                                        <strong>Name:</strong> " . $referred_name . "<br>
                                                        <strong>Email:</strong> " . $bonus_data['referred_email'] . "<br>
                                                        <strong>User ID:</strong> " . $referred_id . "
                                                    </p>
                                                </div>
                                                " : "") . "

                                                <!-- Balance Update -->
                                                <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                    <h4 style='color: #155724;'>💰 Your Balance Updated</h4>
                                                    <p style='color: #155724;'>
                                                        <strong>Previous Fund Balance:</strong> $" . number_format($old_fund_balance, 2) . "<br>
                                                        <strong>Amount Added:</strong> +$" . number_format($amount, 2) . "<br>
                                                        <strong>New Fund Balance:</strong> $" . number_format($new_fund_balance, 2) . "<br><br>
                                                        <strong>Previous Referral Balance:</strong> $" . number_format($old_referral_balance, 2) . "<br>
                                                        <strong>New Referral Balance:</strong> $" . number_format($new_referral_balance, 2) . "
                                                    </p>
                                                </div>

                                                <!-- How to Use Your Bonus -->
                                                <div class='next-steps'>
                                                    <h3 style='color: #2c3e50;'>💡 How to Use Your Bonus</h3>
                                                    <p style='color: #6c757d;'>Your bonus is now available in your fund balance. You can:</p>
                                                    <ul style='color: #6c757d;'>
                                                        <li>Subscribe to AI trading bots</li>
                                                        <li>Withdraw to your wallet</li>
                                                        <li>Reinvest for more earnings</li>
                                                        <li>Refer more users to earn more!</li>
                                                    </ul>
                                                </div>

                                                <!-- Action Buttons -->
                                                <div style='text-align: center; margin: 30px 0;'>
                                                    <a href='" . $myUrl . "/wallet.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 Your Wallet
                                                    </a>
                                                    <a href='" . $myUrl . "/referrals.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;'>
                                                        Refer More Users
                                                    </a>
                                                </div>

                                                <!-- Referral Program Info -->
                                                <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                    <h4 style='color: #856404;'>🎁 Referral Program</h4>
                                                    <p style='color: #856404;'>
                                                        <strong>Earn more with our referral program!</strong><br>
                                                        • Invite friends using your referral link<br>
                                                        • Earn bonuses when they subscribe<br>
                                                        • No limit on how much you can earn<br>
                                                        • Monthly top referrer rewards
                                                    </p>
                                                </div>

                                                <!-- Support Section -->
                                                <div class='support-section'>
                                                    <p class='support-text'>Questions about this bonus?</p>
                                                    <a href='" . $myUrl . "/support.php?subject=Referral%20Bonus%20ID%3A%20" . $bonus_id . "' class='support-link'>Contact Support</a>
                                                </div>
                                            </div>";

                            // Send user notification
                            $user_email = $referrer_email;
                            $first_name = $referrer_name;
                            require_once("../proccess/mail_sender.php");
                            
                            // NOTIFICATION: Bonus Paid (ADMIN)
                            $admin_mail_subject = "Referral Bonus Processed - $" . $amount;
                            $admin_mail_message = "<!-- Content Section -->
                                                <div class='email-content'>
                                                    <h2 class='greeting'>Referral Bonus Paid</h2>
                                                    
                                                    <p class='message'>
                                                        A referral bonus has been successfully processed by an administrator.
                                                    </p>

                                                    <!-- Payment Details -->
                                                    <div class='details-section'>
                                                        <div class='detail-box'>
                                                            <strong>Bonus ID:</strong> " . $bonus_id . "<br>
                                                            <strong>Amount:</strong> $" . number_format($amount, 2) . "<br>
                                                            <strong>Bonus Type:</strong> " . $bonus_type . "<br>
                                                            <strong>Payment Method:</strong> " . $payment_method . "<br>
                                                            <strong>Transaction ID:</strong> " . ($transaction_id ?: 'TX-REF-' . $bonus_id) . "<br>
                                                            <strong>Processed By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                            <strong>Processed Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                            <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "
                                                        </div>
                                                    </div>

                                                    <!-- Referrer Info -->
                                                    <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                        <h4 style='color: #495057;'>👤 Referrer Information</h4>
                                                        <p style='color: #495057;'>
                                                            <strong>User ID:</strong> " . $referrer_id . "<br>
                                                            <strong>Name:</strong> " . $referrer_name . " " . ($bonus_data['referrer_last'] ?? '') . "<br>
                                                            <strong>Email:</strong> " . $referrer_email . "<br>
                                                            <strong>Old Fund Balance:</strong> $" . number_format($old_fund_balance, 2) . "<br>
                                                            <strong>New Fund Balance:</strong> $" . number_format($new_fund_balance, 2) . "<br>
                                                            <strong>Old Referral Balance:</strong> $" . number_format($old_referral_balance, 2) . "<br>
                                                            <strong>New Referral Balance:</strong> $" . number_format($new_referral_balance, 2) . "
                                                        </p>
                                                    </div>

                                                    <!-- Admin Notes -->
                                                    <div class='next-steps'>
                                                        <h3 style='color: #2c3e50;'>📝 Admin Notes</h3>
                                                        <p style='color: #6c757d;'>" . ($notes ?: 'No additional notes provided') . "</p>
                                                    </div>

                                                    <!-- Admin Actions -->
                                                    <div style='text-align: center; margin: 30px 0;'>
                                                        <a href='" . $myUrl . "/admin/referral-bonuses.php?id=" . $bonus_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 Bonus Details
                                                        </a>
                                                        <a href='" . $myUrl . "/admin/users.php?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 User Profile
                                                        </a>
                                                    </div>
                                                </div>";

                            // Send admin notification
                            require_once("../proccess/admin_mailer.php");
                            
                            $success = "Bonus paid successfully!";
                        } else {
                            $error = "Failed to process bonus payment.";
                        }
                    } else {
                        $error = "Bonus not found.";
                    }
                }
                break;
                
            case 'reject_bonus':
                $bonus_id = isset($_POST['bonus_id']) ? intval($_POST['bonus_id']) : 0;
                $reason = isset($_POST['reason']) ? mysqli_real_escape_string($conn, $_POST['reason']) : '';
                
                if ($bonus_id > 0) {
                    // Get bonus details for notification
                    $bonus_sql = "SELECT b.*, u1.first_name as referrer_first, u1.email as referrer_email 
                                  FROM referral_bonuses b
                                  LEFT JOIN users u1 ON b.referrer_id = u1.id
                                  WHERE b.id = $bonus_id";
                    $bonus_result = mysqli_query($conn, $bonus_sql);
                    $bonus_data = mysqli_fetch_assoc($bonus_result);
                    
                    if ($bonus_data) {
                        $referrer_name = $bonus_data['referrer_first'] ?: 'User';
                        $referrer_email = $bonus_data['referrer_email'];
                        $amount = $bonus_data['amount'];
                    }
                    
                    $update_sql = "UPDATE referral_bonuses SET 
                                  status = 'rejected',
                                  admin_notes = CONCAT(IFNULL(admin_notes, ''), '\nRejected: $reason'),
                                  processed_by = '$admin_name'
                                  WHERE id = $bonus_id";
                    
                    if (mysqli_query($conn, $update_sql)) {
                        // Log activity
                        logAdminActivity(
                            'Referral Bonus Rejected',
                            "Rejected referral bonus ID $bonus_id. Reason: $reason",
                            'Referrals',
                            $bonus_id,
                            'referral_bonuses'
                        );
                        
                        // NOTIFICATION: Bonus Rejected (USER)
                        if ($bonus_data) {
                            $mail_subject = "Referral Bonus Update";
                            $mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>Hello <span class='user-name'>" . $referrer_name . "</span>,</h2>
                                                
                                                <p class='message'>
                                                    We have an update regarding your referral bonus request.
                                                </p>

                                                <!-- Rejection Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Bonus ID:</strong> BONUS-" . $bonus_id . "<br>
                                                        <strong>Amount:</strong> $" . number_format($amount, 2) . "<br>
                                                        <strong>Status:</strong> <span style='color: #dc3545; font-weight: bold;'>REJECTED</span><br>
                                                        <strong>Rejection Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                        <strong>Reason:</strong> " . $reason . "
                                                    </div>
                                                </div>

                                                <!-- Next Steps -->
                                                <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                    <h4 style='color: #856404;'>📋 What You Can Do</h4>
                                                    <p style='color: #856404;'>
                                                        If you believe this was a mistake or have questions about this decision, please contact our support team.
                                                    </p>
                                                </div>

                                                <!-- Support Section -->
                                                <div class='support-section'>
                                                    <p class='support-text'>Questions about this decision?</p>
                                                    <a href='" . $myUrl . "/support.php?subject=Rejected%20Bonus%20ID%3A%20" . $bonus_id . "' class='support-link'>Contact Support</a>
                                                </div>
                                            </div>";

                            // Send user notification
                            $user_email = $referrer_email;
                            $first_name = $referrer_name;
                            require_once("../proccess/mail_sender.php");
                        }
                        
                        $success = "Bonus rejected successfully!";
                    } else {
                        $error = "Failed to reject bonus.";
                    }
                }
                break;
                
            case 'add_bonus':
                $referrer_id = isset($_POST['referrer_id']) ? intval($_POST['referrer_id']) : 0;
                $referred_id = isset($_POST['referred_id']) ? intval($_POST['referred_id']) : 0;
                $bonus_type = isset($_POST['bonus_type']) ? mysqli_real_escape_string($conn, $_POST['bonus_type']) : '';
                $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
                $description = isset($_POST['description']) ? mysqli_real_escape_string($conn, $_POST['description']) : '';
                
                if ($referrer_id > 0 && $amount > 0) {
                    $insert_sql = "INSERT INTO referral_bonuses (referrer_id, referred_id, bonus_type, amount, description, status, created_by) 
                                  VALUES ($referrer_id, $referred_id, '$bonus_type', $amount, '$description', 'pending', '$admin_name')";
                    
                    if (mysqli_query($conn, $insert_sql)) {
                        $bonus_id = mysqli_insert_id($conn);
                        
                        // Log activity
                        logAdminActivity(
                            'Manual Bonus Added',
                            "Added manual referral bonus of $$amount for user ID $referrer_id. Type: $bonus_type",
                            'Referrals',
                            $bonus_id,
                            'referral_bonuses'
                        );
                        
                        // Get user details for notification
                        $user_sql = "SELECT first_name, email FROM users WHERE id = $referrer_id";
                        $user_result = mysqli_query($conn, $user_sql);
                        $user_data = mysqli_fetch_assoc($user_result);
                        $user_name = $user_data['first_name'] ?? 'User';
                        $user_email = $user_data['email'] ?? '';
                        
                        // NOTIFICATION: Manual Bonus Added (USER)
                        if ($user_email) {
                            $mail_subject = "Referral Bonus Added to Your Account";
                            $mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>Hello <span class='user-name'>" . $user_name . "</span>,</h2>
                                                
                                                <p class='message'>
                                                    A referral bonus has been manually added to your account by our admin team!
                                                </p>

                                                <!-- Bonus Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Bonus ID:</strong> BONUS-" . $bonus_id . "<br>
                                                        <strong>Amount:</strong> <span style='color: #28a745; font-weight: bold;'>$" . number_format($amount, 2) . "</span><br>
                                                        <strong>Bonus Type:</strong> " . ucfirst(str_replace('_', ' ', $bonus_type)) . "<br>
                                                        <strong>Description:</strong> " . $description . "<br>
                                                        <strong>Status:</strong> <span style='color: #ffc107; font-weight: bold;'>PENDING</span><br>
                                                        <strong>Added By:</strong> Admin Team<br>
                                                        <strong>Date Added:</strong> " . date('F j, Y g:i A') . "
                                                    </div>
                                                </div>

                                                <!-- Next Steps -->
                                                <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                    <h4 style='color: #856404;'>⏳ Pending Approval</h4>
                                                    <p style='color: #856404;'>
                                                        This bonus is currently pending review and will be processed shortly. You will receive another notification once it's approved and added to your balance.
                                                    </p>
                                                </div>

                                                <!-- Support Section -->
                                                <div class='support-section'>
                                                    <p class='support-text'>Questions about this bonus?</p>
                                                    <a href='" . $myUrl . "/support.php?subject=Manual%20Bonus%20ID%3A%20" . $bonus_id . "' class='support-link'>Contact Support</a>
                                                </div>
                                            </div>";

                            // Send user notification
                            require_once("../proccess/mail_sender.php");
                        }
                        
                        $success = "Manual bonus added successfully!";
                    } else {
                        $error = "Failed to add manual bonus.";
                    }
                } else {
                    $error = "Please provide valid referrer and amount.";
                }
                break;
        }
    }
}

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

// Build query
$sql = "SELECT b.*, 
               u1.username as referrer_name, 
               u1.email as referrer_email,
               u2.username as referred_name,
               u2.email as referred_email
        FROM referral_bonuses b
        LEFT JOIN users u1 ON b.referrer_id = u1.id
        LEFT JOIN users u2 ON b.referred_id = u2.id
        WHERE 1=1";
        
$count_sql = "SELECT COUNT(*) as total FROM referral_bonuses b WHERE 1=1";

// Apply filters
if ($filter_status) {
    $sql .= " AND b.status = '$filter_status'";
    $count_sql .= " AND b.status = '$filter_status'";
}

if ($filter_type) {
    $sql .= " AND b.bonus_type = '$filter_type'";
    $count_sql .= " AND b.bonus_type = '$filter_type'";
}

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

if ($date_from && $date_to) {
    $sql .= " AND DATE(b.created_at) BETWEEN '$date_from' AND '$date_to'";
    $count_sql .= " AND DATE(b.created_at) BETWEEN '$date_from' AND '$date_to'";
} elseif ($date_from) {
    $sql .= " AND DATE(b.created_at) >= '$date_from'";
    $count_sql .= " AND DATE(b.created_at) >= '$date_from'";
} elseif ($date_to) {
    $sql .= " AND DATE(b.created_at) <= '$date_to'";
    $count_sql .= " AND DATE(b.created_at) <= '$date_to'";
}

// Get counts for stats
$total_result = mysqli_query($conn, "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) as paid,
    SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected,
    SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) as total_paid,
    SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) as pending_amount
    FROM referral_bonuses");
    
$stats = mysqli_fetch_assoc($total_result);

// Add sorting
$sql .= " ORDER BY b.created_at DESC";

// Execute query
$result = mysqli_query($conn, $sql);

// Get distinct bonus types
$type_sql = "SELECT DISTINCT bonus_type FROM referral_bonuses WHERE bonus_type IS NOT NULL";
$type_result = mysqli_query($conn, $type_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-gift me-2"></i>Referral Bonus Management</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addBonusModal">
												<i class="fas fa-plus-circle me-1"></i> Add Manual Bonus
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Stats Cards -->
										<div class="row mb-20">
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-primary pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Total Bonuses</h5>
																<h2 class="text-white fw-500 mb-0"><?php echo $stats['total'] ?: 0; ?></h2>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-gift fa-2x text-white"></i>
															</div>
														</div>
														<div class="mt-10">
															<small class="text-white-50">All time bonuses issued</small>
														</div>
													</div>
												</div>
											</div>
											
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-warning pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Pending</h5>
																<h2 class="text-white fw-500 mb-0"><?php echo $stats['pending'] ?: 0; ?></h2>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-clock fa-2x text-white"></i>
															</div>
														</div>
														<div class="mt-10">
															<small class="text-white-50">Value: $<?php echo number_format($stats['pending_amount'] ?: 0, 2); ?></small>
														</div>
													</div>
												</div>
											</div>
											
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-success pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Paid</h5>
																<h2 class="text-white fw-500 mb-0"><?php echo $stats['paid'] ?: 0; ?></h2>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-check-circle fa-2x text-white"></i>
															</div>
														</div>
														<div class="mt-10">
															<small class="text-white-50">Value: $<?php echo number_format($stats['total_paid'] ?: 0, 2); ?></small>
														</div>
													</div>
												</div>
											</div>
											
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-danger pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Rejected</h5>
																<h2 class="text-white fw-500 mb-0"><?php echo $stats['rejected'] ?: 0; ?></h2>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-times-circle fa-2x text-white"></i>
															</div>
														</div>
														<div class="mt-10">
															<small class="text-white-50">Rejected bonuses</small>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-10">
												<form method="GET" class="row">
													<div class="col-md-3">
														<div class="form-group">
															<label>Status</label>
															<select class="form-control" name="status">
																<option value="">All Status</option>
																<option value="pending" <?php echo $filter_status == 'pending' ? 'selected' : ''; ?>>Pending</option>
																<option value="paid" <?php echo $filter_status == 'paid' ? 'selected' : ''; ?>>Paid</option>
																<option value="rejected" <?php echo $filter_status == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
															</select>
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label>Bonus Type</label>
															<select class="form-control" name="type">
																<option value="">All Types</option>
																<?php while ($type = mysqli_fetch_assoc($type_result)): ?>
																	<option value="<?php echo $type['bonus_type']; ?>" <?php echo $filter_type == $type['bonus_type'] ? 'selected' : ''; ?>>
																		<?php echo ucfirst(str_replace('_', ' ', $type['bonus_type'])); ?>
																	</option>
																<?php endwhile; ?>
															</select>
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label>Date From</label>
															<input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label>Date To</label>
															<input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
														</div>
													</div>
													<div class="col-md-8">
														<div class="form-group">
															<label>Search</label>
															<input type="text" class="form-control" name="search" placeholder="Search by referrer/referred name or email..." value="<?php echo htmlspecialchars($search); ?>">
														</div>
													</div>
													<div class="col-md-4">
														<div class="form-group" style="margin-top: 28px;">
															<button type="submit" class="btn btn-primary"><i class="fas fa-search me-1"></i> Filter</button>
															<?php if ($filter_status || $filter_type || $search || $date_from || $date_to): ?>
																<a href="referral_bonuses.php" class="btn btn-secondary">Clear</a>
															<?php endif; ?>
														</div>
													</div>
												</form>
											</div>
											<div class="col-md-2 text-end">
												<div class="form-group" style="margin-top: 28px;">
													<div class="dropdown">
														<button class="btn btn-light dropdown-toggle" type="button" data-bs-toggle="dropdown">
															<i class="fas fa-download me-1"></i> Export
														</button>
														<div class="dropdown-menu">
															<a class="dropdown-item" href="export_bonuses.php?format=csv&status=<?php echo $filter_status; ?>&type=<?php echo $filter_type; ?>&search=<?php echo urlencode($search); ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
																<i class="fas fa-file-csv"></i> CSV
															</a>
															<a class="dropdown-item" href="export_bonuses.php?format=excel&status=<?php echo $filter_status; ?>&type=<?php echo $filter_type; ?>&search=<?php echo urlencode($search); ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
																<i class="fas fa-file-excel"></i> Excel
															</a>
														</div>
													</div>
												</div>
											</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; ?>
										
										<!-- Bonuses Table -->
										<div class="table-responsive">
											<table class="table table-hover table-bordered" id="bonusesTable">
												<thead class="bg-light">
													<tr>
														<th>ID</th>
														<th>Referrer</th>
														<th>Referred User</th>
														<th>Bonus Type</th>
														<th>Amount</th>
														<th>Status</th>
														<th>Created</th>
														<th>Actions</th>
													</tr>
												</thead>
												<tbody>
													<?php if (mysqli_num_rows($result) > 0): ?>
														<?php while ($bonus = mysqli_fetch_assoc($result)): ?>
															<?php
															$status = $bonus['status'];
															$status_color = $status == 'paid' ? 'success' : ($status == 'pending' ? 'warning' : 'danger');
															$created = date('M d, Y H:i', strtotime($bonus['created_at']));
															$paid_date = $bonus['paid_date'] ? date('M d, Y', strtotime($bonus['paid_date'])) : 'Not paid';
															?>
															<tr>
																<td><?php echo $bonus['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($bonus['referrer_name']); ?></p>
																			<small class="text-mute"><?php echo htmlspecialchars($bonus['referrer_email']); ?></small>
																			<br>
																			<small class="text-mute">ID: <?php echo $bonus['referrer_id']; ?></small>
																		</div>
																	</div>
																</td>
																<td>
																	<?php if ($bonus['referred_id']): ?>
																		<div class="d-flex align-items-center">
																			<div class="me-10">
																				<div class="bg-info rounded-circle w-40 h-40 d-flex align-items-center justify-content-center">
																					<i class="fas fa-user-plus text-white"></i>
																				</div>
																			</div>
																			<div>
																				<p class="mb-0"><?php echo htmlspecialchars($bonus['referred_name']); ?></p>
																				<small class="text-mute"><?php echo htmlspecialchars($bonus['referred_email']); ?></small>
																			</div>
																		</div>
																	<?php else: ?>
																		<span class="text-mute">N/A (Manual Bonus)</span>
																	<?php endif; ?>
																</td>
																<td>
																	<span class="badge bg-light text-dark">
																		<?php echo ucfirst(str_replace('_', ' ', $bonus['bonus_type'])); ?>
																	</span>
																	<?php if ($bonus['description']): ?>
																		<br><small class="text-mute"><?php echo htmlspecialchars($bonus['description']); ?></small>
																	<?php endif; ?>
																</td>
																<td class="fw-500">$<?php echo number_format($bonus['amount'], 2); ?></td>
																<td>
																	<span class="badge bg-<?php echo $status_color; ?>">
																		<?php echo ucfirst($status); ?>
																	</span>
																	<?php if ($status == 'paid'): ?>
																		<br><small class="text-mute"><?php echo $paid_date; ?></small>
																		<br><small class="text-mute">By: <?php echo htmlspecialchars($bonus['processed_by']); ?></small>
																	<?php endif; ?>
																</td>
																<td>
																	<p class="mb-0"><?php echo $created; ?></p>
																	<small class="text-mute"><?php echo time_ago($bonus['created_at']); ?> ago</small>
																</td>
																<td>
																	<div class="btn-group">
																		<button type="button" class="btn btn-light btn-sm dropdown-toggle" data-bs-toggle="dropdown">
																			<i class="fas fa-cog"></i>
																		</button>
																		<div class="dropdown-menu">
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#viewBonusModal" data-bonus-id="<?php echo $bonus['id']; ?>">
																				<i class="fas fa-eye me-2"></i> View Details
																			</a>
																			<?php if ($status == 'pending'): ?>
																				<a class="dropdown-item text-success" href="#" data-bs-toggle="modal" data-bs-target="#payBonusModal" data-bonus-id="<?php echo $bonus['id']; ?>">
																					<i class="fas fa-money-bill-wave me-2"></i> Pay Bonus
																				</a>
																				<a class="dropdown-item text-danger" href="#" data-bs-toggle="modal" data-bs-target="#rejectBonusModal" data-bonus-id="<?php echo $bonus['id']; ?>">
																					<i class="fas fa-times-circle me-2"></i> Reject Bonus
																				</a>
																			<?php endif; ?>
																		</div>
																	</div>
																</td>
															</tr>
														<?php endwhile; ?>
													<?php else: ?>
														<tr>
															<td colspan="8" class="text-center py-20">
																<i class="fas fa-gift fa-2x text-mute mb-3"></i>
																<h5>No referral bonuses found</h5>
																<p class="text-mute">Try adjusting your filters or add a new bonus</p>
															</td>
														</tr>
													<?php endif; ?>
												</tbody>
											</table>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Viewing Bonus Details -->
		<div class="modal fade" id="viewBonusModal" tabindex="-1" aria-labelledby="viewBonusModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="viewBonusModalLabel">Bonus Details</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body" id="bonusDetails">
						<!-- Details will be loaded via JavaScript -->
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- Modal for Paying Bonus -->
		<div class="modal fade" id="payBonusModal" tabindex="-1" aria-labelledby="payBonusModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="payBonusModalLabel">Pay Referral 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="pay_bonus">
							<input type="hidden" name="bonus_id" id="payBonusId">
							
							<div class="mb-3">
								<label class="form-label">Payment Method <span class="text-danger">*</span></label>
								<select class="form-control" name="payment_method" required>
									<option value="">Select Method</option>
									<option value="crypto">Cryptocurrency (USDT)</option>
									<option value="bank_transfer">Bank Transfer</option>
									<option value="wallet">E-Wallet</option>
									<option value="manual">Manual Adjustment</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Transaction ID (Optional)</label>
								<input type="text" class="form-control" name="transaction_id" placeholder="Enter transaction reference...">
							</div>
							
							<div class="mb-3">
								<label class="form-label">Payment Notes (Optional)</label>
								<textarea class="form-control" name="notes" rows="3" placeholder="Add any payment notes..."></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-success">Confirm Payment</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Rejecting Bonus -->
		<div class="modal fade" id="rejectBonusModal" tabindex="-1" aria-labelledby="rejectBonusModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="rejectBonusModalLabel">Reject Referral 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="reject_bonus">
							<input type="hidden" name="bonus_id" id="rejectBonusId">
							
							<div class="mb-3">
								<label class="form-label">Reason for Rejection <span class="text-danger">*</span></label>
								<textarea class="form-control" name="reason" rows="4" required placeholder="Explain why this bonus is being rejected..."></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-danger">Confirm Rejection</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Adding Manual Bonus -->
		<div class="modal fade" id="addBonusModal" tabindex="-1" aria-labelledby="addBonusModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="addBonusModalLabel">Add Manual Referral 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">
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Referrer User <span class="text-danger">*</span></label>
										<select class="form-control" name="referrer_id" id="referrerSelect" required>
											<option value="">Select Referrer</option>
											<?php
											$users_sql = "SELECT id, username, email FROM users ORDER BY username";
											$users_result = mysqli_query($conn, $users_sql);
											while ($user = mysqli_fetch_assoc($users_result)) {
												echo "<option value='{$user['id']}'>{$user['username']} ({$user['email']})</option>";
											}
											?>
										</select>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Referred User (Optional)</label>
										<select class="form-control" name="referred_id" id="referredSelect">
											<option value="">Select Referred User</option>
											<?php
											mysqli_data_seek($users_result, 0);
											while ($user = mysqli_fetch_assoc($users_result)) {
												echo "<option value='{$user['id']}'>{$user['username']} ({$user['email']})</option>";
											}
											?>
										</select>
									</div>
								</div>
							</div>
							
							<div class="row">
								<div class="col-md-6">
									<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="trading_bonus">Trading Bonus</option>
											<option value="manual">Manual Bonus</option>
											<option value="other">Other</option>
										</select>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">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">
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Description (Optional)</label>
								<textarea class="form-control" name="description" rows="3" placeholder="Enter bonus description..."></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>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<!-- DataTables -->
		<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
		<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
		<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
		
		<!-- Select2 for better dropdowns -->
		<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
		<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
		
		<script>
		$(document).ready(function() {
			// Initialize DataTable
			$('#bonusesTable').DataTable({
				"pageLength": 25,
				"order": [[0, 'desc']],
				"language": {
					"search": "Search:",
					"lengthMenu": "Show _MENU_ entries",
					"info": "Showing _START_ to _END_ of _TOTAL_ entries",
					"paginate": {
						"first": "First",
						"last": "Last",
						"next": "Next",
						"previous": "Previous"
					}
				}
			});
			
			// Initialize Select2
			$('#referrerSelect, #referredSelect').select2({
				placeholder: "Select user...",
				allowClear: true
			});
			
			// Pay Bonus Modal
			$('#payBonusModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var bonusId = button.data('bonus-id');
				var modal = $(this);
				
				modal.find('#payBonusId').val(bonusId);
				modal.find('.modal-title').text('Pay Bonus #' + bonusId);
			});
			
			// Reject Bonus Modal
			$('#rejectBonusModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var bonusId = button.data('bonus-id');
				var modal = $(this);
				
				modal.find('#rejectBonusId').val(bonusId);
				modal.find('.modal-title').text('Reject Bonus #' + bonusId);
			});
			
			// View Bonus Modal
			$('#viewBonusModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var bonusId = button.data('bonus-id');
				var modal = $(this);
				
				modal.find('.modal-title').text('Bonus Details #' + bonusId);
				
				// Load bonus details via AJAX
				$.ajax({
					url: 'ajax/get_bonus_details.php',
					type: 'GET',
					data: { bonus_id: bonusId },
					success: function(data) {
						$('#bonusDetails').html(data);
					},
					error: function() {
						$('#bonusDetails').html('<div class="alert alert-danger">Failed to load bonus details.</div>');
					}
				});
			});
		});
		
		// Auto-refresh stats every 30 seconds
		setInterval(function() {
			$.ajax({
				url: 'ajax/get_bonus_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.total);
						$('.bg-gradient-warning .fw-500').text(stats.pending);
						$('.bg-gradient-success .fw-500').text(stats.paid);
						$('.bg-gradient-danger .fw-500').text(stats.rejected);
						
						// Update amounts
						$('.bg-gradient-warning small').text('Value: $' + stats.pending_amount);
						$('.bg-gradient-success small').text('Value: $' + stats.total_paid);
						
						// Show notification
						Swal.fire({
							toast: true,
							position: 'top-end',
							icon: 'success',
							title: 'Bonus Stats Updated',
							showConfirmButton: false,
							timer: 1500
						});
					}
				}
			});
		}, 30000); // 30 seconds
		</script>
		
		<style>
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
		}
		.badge {
			padding: 5px 10px;
			border-radius: 20px;
			font-size: 12px;
			font-weight: 600;
		}
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		.bg-white-20 {
			background-color: rgba(255, 255, 255, 0.2);
		}
		.select2-container--default .select2-selection--single {
			height: 38px;
			border: 1px solid #ced4da;
			border-radius: 0.375rem;
		}
		.select2-container--default .select2-selection--single .select2-selection__rendered {
			line-height: 36px;
		}
		</style>
		
	</body>
</html>

<?php
// Helper function to show time ago
function time_ago($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return $diff . " seconds";
    } elseif ($diff < 3600) {
        return floor($diff / 60) . " minutes";
    } elseif ($diff < 86400) {
        return floor($diff / 3600) . " hours";
    } elseif ($diff < 604800) {
        return floor($diff / 86400) . " days";
    } elseif ($diff < 2592000) {
        return floor($diff / 604800) . " weeks";
    } elseif ($diff < 31536000) {
        return floor($diff / 2592000) . " months";
    } else {
        return floor($diff / 31536000) . " years";
    }
}
?>