<?php
$page_title = "Referral System";
require_once 'header.php';

$db = Database::getInstance()->connect();

// Handle commission rate update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_commission'])) {
    $commission_rate = floatval($_POST['commission_rate']);
    
    try {
        // Update setting
        $update_stmt = $db->prepare("
            INSERT INTO settings (`key`, value, type, category, description) 
            VALUES ('referral_commission', ?, 'number', 'referral', 'Referral commission rate')
            ON DUPLICATE KEY UPDATE value = ?, updated_at = NOW()
        ");
        
        $update_stmt->execute([$commission_rate, $commission_rate]);
        
        // Log the action
        $log_stmt = $db->prepare("
            INSERT INTO activity_logs (admin_id, action, details)
            VALUES (?, 'referral_update', ?)
        ");
        
        $log_stmt->execute([
            $_SESSION['admin_id'],
            json_encode(['commission_rate' => $commission_rate])
        ]);
        
        $success = "Commission rate updated successfully!";
    } catch (Exception $e) {
        $error = "Failed to update: " . $e->getMessage();
    }
}

// Handle bonus update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_bonus'])) {
    $bonus_amount = floatval($_POST['bonus_amount']);
    
    try {
        // Update setting
        $update_stmt = $db->prepare("
            INSERT INTO settings (`key`, value, type, category, description) 
            VALUES ('referral_bonus', ?, 'number', 'referral', 'Referral bonus amount')
            ON DUPLICATE KEY UPDATE value = ?, updated_at = NOW()
        ");
        
        $update_stmt->execute([$bonus_amount, $bonus_amount]);
        
        $success = "Bonus amount updated successfully!";
    } catch (Exception $e) {
        $error = "Failed to update: " . $e->getMessage();
    }
}

// Get referral settings
$settings_stmt = $db->query("SELECT * FROM settings WHERE category = 'referral'");
$referral_settings = $settings_stmt->fetchAll();

$commission_rate = 5; // default
$bonus_amount = 10; // default

foreach ($referral_settings as $setting) {
    if ($setting['key'] == 'referral_commission') {
        $commission_rate = floatval($setting['value']);
    }
    if ($setting['key'] == 'referral_bonus') {
        $bonus_amount = floatval($setting['value']);
    }
}

// Get referral statistics
$stats_sql = "
    SELECT 
        COUNT(DISTINCT u.id) as total_users_with_referrals,
        COUNT(DISTINCT u.referred_by) as total_referrers,
        SUM(CASE WHEN u.referred_by IS NOT NULL THEN 1 ELSE 0 END) as referred_users,
        SUM(u.referral_balance) as total_referral_balance,
        (SELECT COUNT(*) FROM transactions WHERE type = 'referral_bonus' AND status = 'completed') as total_bonus_paid,
        (SELECT SUM(amount) FROM transactions WHERE type = 'referral_bonus' AND status = 'completed') as total_bonus_amount
    FROM users u
";

$stats_stmt = $db->query($stats_sql);
$referral_stats = $stats_stmt->fetch();

// Get top referrers
$top_referrers_sql = "
    SELECT 
        u.id,
        u.username,
        u.email,
        COUNT(r.id) as referrals_count,
        u.referral_balance,
        u.referral_code,
        SUM(CASE WHEN r.account_status = 'active' THEN 1 ELSE 0 END) as active_referrals
    FROM users u
    LEFT JOIN users r ON u.id = r.referred_by
    WHERE u.referral_code IS NOT NULL
    GROUP BY u.id
    HAVING referrals_count > 0
    ORDER BY referrals_count DESC
    LIMIT 10
";

$top_referrers_stmt = $db->query($top_referrers_sql);
$top_referrers = $top_referrers_stmt->fetchAll();

// Get recent referral transactions
$recent_transactions_sql = "
    SELECT 
        t.*,
        u.username as user_username,
        u2.username as referrer_username
    FROM transactions t
    JOIN users u ON t.user_id = u.id
    LEFT JOIN users u2 ON u.referred_by = u2.id
    WHERE t.type IN ('referral_bonus', 'referral_commission')
    ORDER BY t.created_at DESC
    LIMIT 20
";

$recent_transactions_stmt = $db->query($recent_transactions_sql);
$recent_transactions = $recent_transactions_stmt->fetchAll();

// Get referral tree (if needed)
$referral_tree_sql = "
    WITH RECURSIVE referral_tree AS (
        SELECT 
            id,
            username,
            email,
            referred_by,
            created_at,
            1 as level,
            CAST(id AS CHAR(200)) as path
        FROM users
        WHERE referred_by IS NULL
        
        UNION ALL
        
        SELECT 
            u.id,
            u.username,
            u.email,
            u.referred_by,
            u.created_at,
            rt.level + 1,
            CONCAT(rt.path, ' > ', u.id)
        FROM users u
        INNER JOIN referral_tree rt ON u.referred_by = rt.id
        WHERE rt.level < 3 -- Limit depth for performance
    )
    SELECT * FROM referral_tree ORDER BY path
";

try {
    $referral_tree_stmt = $db->query($referral_tree_sql);
    $referral_tree = $referral_tree_stmt->fetchAll();
} catch (Exception $e) {
    $referral_tree = [];
}
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold">Referral System</h1>
        <p class="text-gray-600">Manage referral program and track performance</p>
    </div>

    <!-- Messages -->
    <?php if (isset($error)): ?>
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
        <?php echo $error; ?>
    </div>
    <?php endif; ?>
    
    <?php if (isset($success)): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
        <?php echo $success; ?>
    </div>
    <?php endif; ?>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Referrers</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($referral_stats['total_referrers']); ?></h3>
                </div>
                <i class="fas fa-users text-purple-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Referred Users</p>
                    <h3 class="text-2xl font-bold text-green-600"><?php echo number_format($referral_stats['referred_users']); ?></h3>
                </div>
                <i class="fas fa-user-plus text-green-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Bonus Paid</p>
                    <h3 class="text-2xl font-bold">$<?php echo number_format($referral_stats['total_bonus_amount'] ?? 0, 2); ?></h3>
                </div>
                <i class="fas fa-money-bill-wave text-yellow-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Active Referral Balance</p>
                    <h3 class="text-2xl font-bold text-blue-600">$<?php echo number_format($referral_stats['total_referral_balance'] ?? 0, 2); ?></h3>
                </div>
                <i class="fas fa-wallet text-blue-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <!-- Settings Section -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <!-- Commission Rate Settings -->
        <div class="bg-white rounded-xl shadow p-6">
            <h3 class="text-lg font-bold mb-4">Commission Rate Settings</h3>
            <form method="POST" class="space-y-4">
                <div>
                    <label class="block text-gray-700 mb-2">Commission Rate (%)</label>
                    <div class="flex items-center space-x-2">
                        <input type="number" step="0.01" min="0" max="100" name="commission_rate" 
                               value="<?php echo $commission_rate; ?>"
                               class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <span class="text-gray-600">%</span>
                    </div>
                    <p class="text-sm text-gray-500 mt-1">Percentage of referral's deposit that referrer earns</p>
                </div>
                <button type="submit" name="update_commission" 
                        class="w-full bg-purple-600 text-white py-2 rounded-lg hover:bg-purple-700">
                    Update Commission Rate
                </button>
            </form>
        </div>

        <!-- Bonus Settings -->
        <div class="bg-white rounded-xl shadow p-6">
            <h3 class="text-lg font-bold mb-4">Signup Bonus Settings</h3>
            <form method="POST" class="space-y-4">
                <div>
                    <label class="block text-gray-700 mb-2">Signup Bonus ($)</label>
                    <div class="flex items-center space-x-2">
                        <span class="text-gray-600">$</span>
                        <input type="number" step="0.01" min="0" name="bonus_amount" 
                               value="<?php echo $bonus_amount; ?>"
                               class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                    </div>
                    <p class="text-sm text-gray-500 mt-1">Bonus amount for successful referrals</p>
                </div>
                <button type="submit" name="update_bonus" 
                        class="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700">
                    Update Bonus Amount
                </button>
            </form>
        </div>
    </div>

    <!-- Top Referrers -->
    <div class="bg-white rounded-xl shadow mb-6">
        <div class="p-6 border-b">
            <h3 class="text-lg font-bold">Top Referrers</h3>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="p-4 text-left">Referrer</th>
                        <th class="p-4 text-left">Referral Code</th>
                        <th class="p-4 text-left">Total Referrals</th>
                        <th class="p-4 text-left">Active Referrals</th>
                        <th class="p-4 text-left">Referral Balance</th>
                        <th class="p-4 text-left">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php foreach ($top_referrers as $referrer): ?>
                    <tr class="hover:bg-gray-50">
                        <td class="p-4">
                            <p class="font-medium"><?php echo htmlspecialchars($referrer['username']); ?></p>
                            <p class="text-sm text-gray-500"><?php echo htmlspecialchars($referrer['email']); ?></p>
                        </td>
                        <td class="p-4">
                            <code class="bg-gray-100 px-2 py-1 rounded text-sm"><?php echo $referrer['referral_code']; ?></code>
                        </td>
                        <td class="p-4">
                            <p class="font-bold text-purple-600"><?php echo number_format($referrer['referrals_count']); ?></p>
                        </td>
                        <td class="p-4">
                            <p class="font-bold text-green-600"><?php echo number_format($referrer['active_referrals']); ?></p>
                        </td>
                        <td class="p-4">
                            <p class="font-bold">$<?php echo number_format($referrer['referral_balance'], 2); ?></p>
                        </td>
                        <td class="p-4">
                            <a href="user-edit.php?id=<?php echo $referrer['id']; ?>" 
                               class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                <i class="fas fa-eye mr-1"></i> View
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Recent Referral Transactions -->
    <div class="bg-white rounded-xl shadow mb-6">
        <div class="p-6 border-b">
            <h3 class="text-lg font-bold">Recent Referral Transactions</h3>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="p-4 text-left">Date</th>
                        <th class="p-4 text-left">User</th>
                        <th class="p-4 text-left">Referrer</th>
                        <th class="p-4 text-left">Type</th>
                        <th class="p-4 text-left">Amount</th>
                        <th class="p-4 text-left">Status</th>
                        <th class="p-4 text-left">Description</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php foreach ($recent_transactions as $tx): ?>
                    <tr class="hover:bg-gray-50">
                        <td class="p-4">
                            <p><?php echo date('M d', strtotime($tx['created_at'])); ?></p>
                            <p class="text-sm text-gray-500"><?php echo date('H:i', strtotime($tx['created_at'])); ?></p>
                        </td>
                        <td class="p-4">
                            <p class="font-medium"><?php echo htmlspecialchars($tx['user_username']); ?></p>
                        </td>
                        <td class="p-4">
                            <p class="text-sm"><?php echo $tx['referrer_username'] ? htmlspecialchars($tx['referrer_username']) : 'N/A'; ?></p>
                        </td>
                        <td class="p-4">
                            <span class="px-2 py-1 rounded-full text-xs font-semibold 
                                <?php echo $tx['type'] == 'referral_bonus' ? 'bg-green-100 text-green-800' : 'bg-blue-100 text-blue-800'; ?>">
                                <?php echo ucfirst(str_replace('_', ' ', $tx['type'])); ?>
                            </span>
                        </td>
                        <td class="p-4">
                            <p class="font-bold text-green-600">$<?php echo number_format($tx['amount'], 2); ?></p>
                        </td>
                        <td class="p-4">
                            <span class="px-2 py-1 rounded-full text-xs font-semibold 
                                <?php echo $tx['status'] == 'completed' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'; ?>">
                                <?php echo ucfirst($tx['status']); ?>
                            </span>
                        </td>
                        <td class="p-4">
                            <p class="text-sm text-gray-600"><?php echo htmlspecialchars($tx['description'] ?? ''); ?></p>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Referral Tree (Limited Depth) -->
    <?php if (!empty($referral_tree)): ?>
    <div class="bg-white rounded-xl shadow">
        <div class="p-6 border-b">
            <h3 class="text-lg font-bold">Referral Network (Top 3 Levels)</h3>
            <p class="text-sm text-gray-600">Showing referral hierarchy up to 3 levels deep</p>
        </div>
        <div class="p-6">
            <div class="overflow-x-auto">
                <div class="min-w-full">
                    <?php
                    $current_level = 1;
                    foreach ($referral_tree as $user):
                        $indent = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $user['level'] - 1);
                        $connector = $user['level'] > 1 ? '└── ' : '';
                    ?>
                    <div class="flex items-center py-2 border-b last:border-0">
                        <div class="w-8 text-center text-gray-400">
                            <?php if ($user['level'] == 1): ?>
                            <i class="fas fa-user-shield"></i>
                            <?php elseif ($user['level'] == 2): ?>
                            <i class="fas fa-user"></i>
                            <?php else: ?>
                            <i class="fas fa-user-friends"></i>
                            <?php endif; ?>
                        </div>
                        <div class="flex-1">
                            <span class="text-gray-500"><?php echo str_repeat('│&nbsp;&nbsp;', $user['level'] - 1); ?></span>
                            <span class="font-medium"><?php echo htmlspecialchars($user['username']); ?></span>
                            <span class="text-sm text-gray-500 ml-2">(Level <?php echo $user['level']; ?>)</span>
                        </div>
                        <div class="text-sm text-gray-500">
                            <?php echo date('M d, Y', strtotime($user['created_at'])); ?>
                        </div>
                        <div class="ml-4">
                            <a href="user-edit.php?id=<?php echo $user['id']; ?>" 
                               class="text-blue-600 hover:text-blue-800 text-sm">
                                View
                            </a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Bulk Actions -->
    <div class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
        <button onclick="exportReferralReport()" class="bg-blue-600 text-white p-4 rounded-xl hover:bg-blue-700">
            <i class="fas fa-file-export text-2xl mb-2"></i>
            <p class="font-semibold">Export Report</p>
        </button>
        
        <button onclick="processPendingReferrals()" class="bg-green-600 text-white p-4 rounded-xl hover:bg-green-700">
            <i class="fas fa-check-circle text-2xl mb-2"></i>
            <p class="font-semibold">Process Pending</p>
        </button>
        
        <button onclick="resetReferralStats()" class="bg-red-600 text-white p-4 rounded-xl hover:bg-red-700">
            <i class="fas fa-redo text-2xl mb-2"></i>
            <p class="font-semibold">Reset Stats</p>
        </button>
    </div>
</div>

<script>
function exportReferralReport() {
    window.open('export-referral-report.php', '_blank');
}

function processPendingReferrals() {
    if (confirm('Process all pending referral bonuses?')) {
        $.ajax({
            url: '../api/process-referrals.php',
            method: 'POST',
            data: { action: 'process_pending' },
            success: function(response) {
                const result = JSON.parse(response);
                alert(result.message);
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

function resetReferralStats() {
    if (confirm('WARNING: This will reset all referral statistics. This action cannot be undone. Proceed?')) {
        const confirmation = prompt('Type "RESET" to confirm:');
        if (confirmation === 'RESET') {
            $.ajax({
                url: '../api/reset-referral-stats.php',
                method: 'POST',
                success: function(response) {
                    const result = JSON.parse(response);
                    alert(result.message);
                    if (result.success) {
                        location.reload();
                    }
                }
            });
        }
    }
}

// Auto-refresh every 2 minutes for real-time updates
setTimeout(() => {
    location.reload();
}, 120000);
</script>

<?php require_once 'footer.php'; ?>