<?php
// guest_sponsor_lookup.php - AJAX endpoint for sponsor lookup
require_once 'db/connection.php';

header('Content-Type: application/json');

// Rate limiting
session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$limit = 30; // Max 30 lookups per minute
$lookup_key = 'sponsor_lookup_' . $ip;

if (isset($_SESSION[$lookup_key])) {
    if ($_SESSION[$lookup_key]['count'] >= $limit && ($time - $_SESSION[$lookup_key]['time']) < 60) {
        echo json_encode(['success' => false, 'message' => 'Too many lookups. Please try again later.']);
        exit();
    }
}

if (!isset($_GET['user_id']) || empty($_GET['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User ID required']);
    exit();
}

$user_id = (int)$_GET['user_id'];

if ($user_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid User ID']);
    exit();
}

// Query user data
$query = mysqli_query($conn, "SELECT user_id, name, rank, wallet, joining_date FROM users WHERE user_id = $user_id AND status = 1");

if (!$query || mysqli_num_rows($query) == 0) {
    echo json_encode(['success' => false, 'message' => 'Sponsor not found or inactive']);
    exit();
}

$user = mysqli_fetch_assoc($query);

// Calculate team size (simplified)
function getTeamSize($conn, $user_id) {
    $count = 0;
    $queue = [$user_id];
    $visited = [];
    while (!empty($queue)) {
        $current = array_shift($queue);
        if (in_array($current, $visited)) continue;
        $visited[] = $current;
        $r = $conn->query("SELECT left_1_id, left_2_id, right_1_id, right_2_id FROM users WHERE user_id = $current");
        if ($r && $row = $r->fetch_assoc()) {
            foreach (['left_1_id', 'left_2_id', 'right_1_id', 'right_2_id'] as $pos) {
                if (!empty($row[$pos]) && $row[$pos] != 0) {
                    $count++;
                    $queue[] = $row[$pos];
                }
            }
        }
    }
    return $count;
}

// Get current level (simplified)
function getCurrentLevel($conn, $user_id) {
    $res = $conn->query("SELECT MAX(level) as current FROM level_rewards WHERE user_id = $user_id AND paid = 1");
    $row = $res->fetch_assoc();
    return $row['current'] ?? 0;
}

$teamSize = getTeamSize($conn, $user_id);
$level = getCurrentLevel($conn, $user_id);
$rank = $user['rank'] ?? 'STARTER';
$joiningDate = date('d M Y', strtotime($user['joining_date'] ?? 'now'));

// Update rate limit counter
if (!isset($_SESSION[$lookup_key])) {
    $_SESSION[$lookup_key] = ['count' => 1, 'time' => $time];
} else {
    $_SESSION[$lookup_key]['count']++;
}

echo json_encode([
    'success' => true,
    'user_id' => $user['user_id'],
    'name' => $user['name'],
    'rank' => $rank,
    'level' => $level,
    'team_size' => $teamSize,
    'joining_date' => $joiningDate
]);
?>