<?php
require_once 'connection.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sponsor_id'])) {
    $sponsor_id = (int)$_POST['sponsor_id'];
 
    $ip = $_SERVER['REMOTE_ADDR'];
    $key = 'sponsor_check_' . md5($ip);
    
    if (!isset($_SESSION[$key])) {
        $_SESSION[$key] = [];
    }
    
    // Clean old attempts (last 1 minute)
    $_SESSION[$key] = array_filter($_SESSION[$key], function($time) {
        return (time() - $time) < 60;
    });
    
    if (count($_SESSION[$key]) > 30) { // Max 30 checks per minute
        echo json_encode(['valid' => false, 'message' => 'Too many requests']);
        exit();
    }
    
    $_SESSION[$key][] = time();
    
    // Validate sponsor
    $stmt = $conn->prepare("SELECT name, mobile FROM users WHERE user_id = ? AND status = 1");
    $stmt->bind_param("i", $sponsor_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $sponsor = $result->fetch_assoc();
        echo json_encode([
            'valid' => true,
            'name' => htmlspecialchars($sponsor['name']),
            'mobile' => htmlspecialchars($sponsor['mobile'])
        ]);
    } else {
        echo json_encode(['valid' => false, 'message' => 'Invalid Sponsor ID']);
    }
} else {
    echo json_encode(['valid' => false, 'message' => 'Invalid request']);
}
?>