<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: admin_login.php");
    exit();
}
require_once 'db.php';

// Handle commission rate updates
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] == 'update_rates') {
        $level1_rate = floatval($_POST['level1_rate']);
        $level2_rate = floatval($_POST['level2_rate']);
        $level3_rate = floatval($_POST['level3_rate']);
        
        // Validate rates
        if ($level1_rate >= 0 && $level1_rate <= 100 &&
            $level2_rate >= 0 && $level2_rate <= 100 &&
            $level3_rate >= 0 && $level3_rate <= 100) {
            
            mysqli_begin_transaction($conn);
            
            try {
                // Update or insert commission rates
                $update_level1 = "INSERT INTO commission_settings (level, percentage, updated_at) 
                    VALUES (1, $level1_rate, NOW()) 
                    ON DUPLICATE KEY UPDATE percentage = $level1_rate, updated_at = NOW()";
                mysqli_query($conn, $update_level1);
                
                $update_level2 = "INSERT INTO commission_settings (level, percentage, updated_at) 
                    VALUES (2, $level2_rate, NOW()) 
                    ON DUPLICATE KEY UPDATE percentage = $level2_rate, updated_at = NOW()";
                mysqli_query($conn, $update_level2);
                
                $update_level3 = "INSERT INTO commission_settings (level, percentage, updated_at) 
                    VALUES (3, $level3_rate, NOW()) 
                    ON DUPLICATE KEY UPDATE percentage = $level3_rate, updated_at = NOW()";
                mysqli_query($conn, $update_level3);
                
                mysqli_commit($conn);
                $success = "Commission rates updated successfully!";
            } catch (Exception $e) {
                mysqli_rollback($conn);
                $error = "Failed to update rates: " . $e->getMessage();
            }
        } else {
            $error = "Invalid commission rates! Rates must be between 0% and 100%.";
        }
    } elseif ($_POST['action'] == 'toggle_system') {
        $status = mysqli_real_escape_string($conn, $_POST['status']);
        
        $update_query = "INSERT INTO commission_settings (level, status, updated_at) 
            VALUES (0, '$status', NOW()) 
            ON DUPLICATE KEY UPDATE status = '$status', updated_at = NOW()";
        
        if (mysqli_query($conn, $update_query)) {
            $success = "Referral system " . ($status == 'active' ? 'enabled' : 'disabled') . " successfully!";
        } else {
            $error = "Failed to update system status!";
        }
    }
}

// Get current commission rates
$rates_query = "SELECT level, percentage, status FROM commission_settings WHERE level IN (0, 1, 2, 3)";
$rates_result = mysqli_query($conn, $rates_query);

$rates = [
    'level1' => 10.00,
    'level2' => 6.00,
    'level3' => 4.00,
    'status' => 'active'
];

while ($row = mysqli_fetch_assoc($rates_result)) {
    if ($row['level'] == 0) {
        $rates['status'] = $row['status'];
    } elseif ($row['level'] == 1) {
        $rates['level1'] = $row['percentage'];
    } elseif ($row['level'] == 2) {
        $rates['level2'] = $row['percentage'];
    } elseif ($row['level'] == 3) {
        $rates['level3'] = $row['percentage'];
    }
}

// Get commission statistics
$stats_query = "SELECT 
    COUNT(DISTINCT user_id) as total_earners,
    SUM(amount) as total_paid,
    SUM(CASE WHEN level = 1 THEN amount ELSE 0 END) as level1_total,
    SUM(CASE WHEN level = 2 THEN amount ELSE 0 END) as level2_total,
    SUM(CASE WHEN level = 3 THEN amount ELSE 0 END) as level3_total,
    COUNT(*) as total_commissions
    FROM referral_commissions";
$stats_result = mysqli_query($conn, $stats_query);
$stats = mysqli_fetch_assoc($stats_result);

// Get recent commissions
$recent_query = "SELECT rc.*, u1.phone_number as earner, u2.phone_number as from_user
    FROM referral_commissions rc
    JOIN users u1 ON rc.user_id = u1.id
    JOIN users u2 ON rc.from_user_id = u2.id
    ORDER BY rc.created_at DESC
    LIMIT 20";
$recent_result = mysqli_query($conn, $recent_query);

// Get top earners
$top_earners_query = "SELECT u.phone_number, u.email, SUM(rc.amount) as total_earned,
    COUNT(DISTINCT rc.from_user_id) as total_referrals
    FROM referral_commissions rc
    JOIN users u ON rc.user_id = u.id
    GROUP BY u.id
    ORDER BY total_earned DESC
    LIMIT 10";
$top_earners_result = mysqli_query($conn, $top_earners_query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Referral Commission - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            background-color: #000;
            color: #fff;
            font-family: Arial, sans-serif;
            font-size: 13px;
        }
        .header {
            background: #111;
            padding: 12px 15px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
            position: sticky;
            top: 0;
            z-index: 100;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .header h1 {
            color: #fff;
            font-size: 18px;
        }
        .back-btn {
            color: #FFD700;
            text-decoration: none;
            font-size: 20px;
        }
        .logout-btn {
            background: #f87171;
            color: #fff;
            padding: 8px 15px;
            border-radius: 5px;
            text-decoration: none;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .container {
            padding: 12px;
            max-width: 1200px;
            margin: 0 auto;
        }
        .alert {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 12px;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .alert-success {
            background: #1a4d1a;
            border: 1px solid #2d7a2d;
            color: #4ade80;
        }
        .alert-error {
            background: #4d1a1a;
            border: 1px solid #7a2d2d;
            color: #f87171;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 10px;
            margin-bottom: 15px;
        }
        .stat-card {
            background: #111;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            border: 1px solid #333;
        }
        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #FFD700;
            margin-bottom: 5px;
        }
        .stat-label {
            color: #888;
            font-size: 11px;
        }
        .card {
            background: #111;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
            border: 1px solid #333;
        }
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #333;
        }
        .card-title {
            color: #FFD700;
            font-size: 16px;
            font-weight: bold;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }
        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #666;
            transition: .4s;
            border-radius: 24px;
        }
        .slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        input:checked + .slider {
            background-color: #4ade80;
        }
        input:checked + .slider:before {
            transform: translateX(26px);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-label {
            display: block;
            color: #888;
            font-size: 11px;
            margin-bottom: 5px;
        }
        .form-row {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-bottom: 15px;
        }
        .rate-input-group {
            background: #000;
            border: 1px solid #333;
            border-radius: 8px;
            padding: 12px;
        }
        .rate-label {
            color: #FFD700;
            font-size: 12px;
            font-weight: bold;
            margin-bottom: 8px;
            display: block;
        }
        .rate-sublabel {
            color: #666;
            font-size: 10px;
            margin-bottom: 8px;
            display: block;
        }
        input[type="number"] {
            width: 100%;
            padding: 10px;
            background: #111;
            border: 1px solid #333;
            border-radius: 5px;
            color: #fff;
            font-size: 14px;
            font-weight: bold;
        }
        input[type="number"]:focus {
            outline: none;
            border-color: #FFD700;
        }
        .btn {
            padding: 12px 20px;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            font-size: 13px;
            transition: all 0.3s;
        }
        .btn-primary {
            background: #FFD700;
            color: #000;
            width: 100%;
        }
        .btn-primary:hover {
            background: #FFA500;
        }
        .info-box {
            background: #000;
            border: 1px solid #333;
            border-radius: 5px;
            padding: 10px;
            margin: 10px 0;
            font-size: 11px;
            color: #888;
        }
        .info-box i {
            color: #FFD700;
            margin-right: 5px;
        }
        .commission-item {
            background: #000;
            padding: 12px;
            border: 1px solid #333;
            border-radius: 5px;
            margin-bottom: 8px;
        }
        .commission-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 8px;
        }
        .commission-amount {
            font-size: 16px;
            font-weight: bold;
            color: #FFD700;
        }
        .commission-level {
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 10px;
            font-weight: bold;
        }
        .level-1 { background: #FFD700; color: #000; }
        .level-2 { background: #FFA500; color: #000; }
        .level-3 { background: #FF6347; color: #fff; }
        .commission-details {
            font-size: 11px;
            color: #888;
            display: grid;
            gap: 4px;
        }
        .commission-row {
            display: flex;
            justify-content: space-between;
        }
        .earner-item {
            background: #000;
            padding: 12px;
            border: 1px solid #333;
            border-radius: 5px;
            margin-bottom: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .earner-info {
            flex: 1;
        }
        .earner-phone {
            color: #FFD700;
            font-weight: bold;
            font-size: 12px;
        }
        .earner-email {
            color: #666;
            font-size: 10px;
        }
        .earner-stats {
            text-align: right;
        }
        .earner-amount {
            color: #4ade80;
            font-weight: bold;
            font-size: 14px;
        }
        .earner-referrals {
            color: #888;
            font-size: 10px;
        }
        .no-data {
            text-align: center;
            padding: 30px;
            color: #666;
        }
        .no-data i {
            font-size: 40px;
            margin-bottom: 10px;
            opacity: 0.3;
        }
        .tabs {
            display: flex;
            gap: 8px;
            margin-bottom: 15px;
            border-bottom: 2px solid #333;
        }
        .tab {
            padding: 10px 15px;
            cursor: pointer;
            background: transparent;
            border: none;
            color: #888;
            font-size: 12px;
            border-bottom: 2px solid transparent;
            margin-bottom: -2px;
        }
        .tab.active {
            color: #FFD700;
            border-bottom-color: #FFD700;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-left">
            <a href="admin_dashboard.php" class="back-btn"><i class="fas fa-arrow-left"></i></a>
            <h1><i class="fas fa-percentage"></i> Referral Commission</h1>
        </div>
        <a href="admin_logout.php" class="logout-btn">
            <i class="fas fa-sign-out-alt"></i> Logout
        </a>
    </div>

    <div class="container">
        <?php if (isset($success)): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <span><?php echo $success; ?></span>
            </div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i>
                <span><?php echo $error; ?></span>
            </div>
        <?php endif; ?>

        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number">$<?php echo number_format($stats['total_paid'] ?? 0, 2); ?></div>
                <div class="stat-label">Total Paid</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo number_format($stats['total_earners'] ?? 0); ?></div>
                <div class="stat-label">Total Earners</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo number_format($stats['total_commissions'] ?? 0); ?></div>
                <div class="stat-label">Total Transactions</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">$<?php echo number_format($stats['level1_total'] ?? 0, 2); ?></div>
                <div class="stat-label">Level 1 Paid</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">$<?php echo number_format($stats['level2_total'] ?? 0, 2); ?></div>
                <div class="stat-label">Level 2 Paid</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">$<?php echo number_format($stats['level3_total'] ?? 0, 2); ?></div>
                <div class="stat-label">Level 3 Paid</div>
            </div>
        </div>

        <!-- System Control -->
        <div class="card">
            <div class="card-header">
                <div class="card-title">
                    <i class="fas fa-power-off"></i> System Control
                </div>
                <form method="POST" style="margin: 0;">
                    <input type="hidden" name="action" value="toggle_system">
                    <input type="hidden" name="status" id="systemStatus" value="<?php echo $rates['status'] == 'active' ? 'inactive' : 'active'; ?>">
                    <label class="toggle-switch">
                        <input type="checkbox" <?php echo $rates['status'] == 'active' ? 'checked' : ''; ?> onchange="this.form.submit()">
                        <span class="slider"></span>
                    </label>
                </form>
            </div>
            <div class="info-box">
                <i class="fas fa-info-circle"></i>
                <strong>Status: <?php echo ucfirst($rates['status']); ?></strong><br>
                <?php if ($rates['status'] == 'active'): ?>
                    Referral commissions are currently being distributed automatically when users make investments.
                <?php else: ?>
                    Referral system is disabled. No commissions will be paid out until re-enabled.
                <?php endif; ?>
            </div>
        </div>

        <!-- Commission Rates Configuration -->
        <div class="card">
            <div class="card-header">
                <div class="card-title">
                    <i class="fas fa-sliders-h"></i> Commission Rates
                </div>
            </div>
            
            <form method="POST">
                <input type="hidden" name="action" value="update_rates">
                
                <div class="form-row">
                    <div class="rate-input-group">
                        <label class="rate-label">Level 1 Commission</label>
                        <span class="rate-sublabel">Direct Referrals</span>
                        <input type="number" name="level1_rate" step="0.01" min="0" max="100" 
                            value="<?php echo $rates['level1']; ?>" required>
                    </div>
                    
                    <div class="rate-input-group">
                        <label class="rate-label">Level 2 Commission</label>
                        <span class="rate-sublabel">2nd Generation</span>
                        <input type="number" name="level2_rate" step="0.01" min="0" max="100" 
                            value="<?php echo $rates['level2']; ?>" required>
                    </div>
                    
                    <div class="rate-input-group">
                        <label class="rate-label">Level 3 Commission</label>
                        <span class="rate-sublabel">3rd Generation</span>
                        <input type="number" name="level3_rate" step="0.01" min="0" max="100" 
                            value="<?php echo $rates['level3']; ?>" required>
                    </div>
                </div>
                
                <div class="info-box">
                    <i class="fas fa-calculator"></i>
                    <strong>Example:</strong> If a user invests $1,000:<br>
                    • Level 1 earns: $<?php echo number_format((1000 * $rates['level1']) / 100, 2); ?> (<?php echo $rates['level1']; ?>%)<br>
                    • Level 2 earns: $<?php echo number_format((1000 * $rates['level2']) / 100, 2); ?> (<?php echo $rates['level2']; ?>%)<br>
                    • Level 3 earns: $<?php echo number_format((1000 * $rates['level3']) / 100, 2); ?> (<?php echo $rates['level3']; ?>%)
                </div>
                
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> Update Commission Rates
                </button>
            </form>
        </div>

        <!-- Tabs -->
        <div class="tabs">
            <button class="tab active" onclick="showTab('recent')">Recent Commissions</button>
            <button class="tab" onclick="showTab('earners')">Top Earners</button>
        </div>

        <!-- Recent Commissions -->
        <div id="recent" class="tab-content active">
            <div class="card">
                <div class="card-header">
                    <div class="card-title">
                        <i class="fas fa-history"></i> Recent Commission Payments
                    </div>
                </div>
                
                <?php if ($recent_result && mysqli_num_rows($recent_result) > 0): ?>
                    <?php while ($commission = mysqli_fetch_assoc($recent_result)): ?>
                    <div class="commission-item">
                        <div class="commission-header">
                            <div class="commission-amount">
                                <i class="fas fa-dollar-sign"></i> <?php echo number_format($commission['amount'], 2); ?>
                            </div>
                            <span class="commission-level level-<?php echo $commission['level']; ?>">
                                Level <?php echo $commission['level']; ?>
                            </span>
                        </div>
                        <div class="commission-details">
                            <div class="commission-row">
                                <span>Earner:</span>
                                <span style="color: #FFD700;"><?php echo htmlspecialchars($commission['earner']); ?></span>
                            </div>
                            <div class="commission-row">
                                <span>From User:</span>
                                <span style="color: #fff;"><?php echo htmlspecialchars($commission['from_user']); ?></span>
                            </div>
                            <div class="commission-row">
                                <span>Date:</span>
                                <span><?php echo date('M d, Y - h:i A', strtotime($commission['created_at'])); ?></span>
                            </div>
                            <div class="commission-row">
                                <span>Percentage:</span>
                                <span><?php echo $commission['percentage']; ?>%</span>
                            </div>
                        </div>
                    </div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="no-data">
                        <i class="fas fa-inbox"></i>
                        <p>No commission payments yet</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Top Earners -->
        <div id="earners" class="tab-content">
            <div class="card">
                <div class="card-header">
                    <div class="card-title">
                        <i class="fas fa-trophy"></i> Top Commission Earners
                    </div>
                </div>
                
                <?php if ($top_earners_result && mysqli_num_rows($top_earners_result) > 0): ?>
                    <?php $rank = 1; ?>
                    <?php while ($earner = mysqli_fetch_assoc($top_earners_result)): ?>
                    <div class="earner-item">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <div style="font-size: 18px; font-weight: bold; color: <?php echo $rank <= 3 ? '#FFD700' : '#666'; ?>;">
                                #<?php echo $rank; ?>
                            </div>
                            <div class="earner-info">
                                <div class="earner-phone"><?php echo htmlspecialchars($earner['phone_number']); ?></div>
                                <div class="earner-email"><?php echo htmlspecialchars($earner['email']); ?></div>
                            </div>
                        </div>
                        <div class="earner-stats">
                            <div class="earner-amount">$<?php echo number_format($earner['total_earned'], 2); ?></div>
                            <div class="earner-referrals"><?php echo $earner['total_referrals']; ?> referrals</div>
                        </div>
                    </div>
                    <?php $rank++; ?>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="no-data">
                        <i class="fas fa-user-friends"></i>
                        <p>No earnings data yet</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        function showTab(tabName) {
            // Hide all tab contents
            const contents = document.querySelectorAll('.tab-content');
            contents.forEach(content => content.classList.remove('active'));
            
            // Remove active class from all tabs
            const tabs = document.querySelectorAll('.tab');
            tabs.forEach(tab => tab.classList.remove('active'));
            
            // Show selected tab content
            document.getElementById(tabName).classList.add('active');
            
            // Add active class to clicked tab
            event.target.classList.add('active');
        }

        // Auto-hide alerts
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                alert.style.transition = 'opacity 0.5s';
                alert.style.opacity = '0';
                setTimeout(function() {
                    alert.remove();
                }, 500);
            });
        }, 5000);
    </script>
</body>
</html>
<?php
mysqli_close($conn);
?>