<?php
// register.php - Public registration page with Aadhaar and sponsor lookup
session_start();

// Generate CSRF token
if (empty($_SESSION['guest_csrf_token'])) {
    $_SESSION['guest_csrf_token'] = bin2hex(random_bytes(32));
}

// Check for success/error messages
$success_msg = isset($_GET['success']) ? $_GET['success'] : '';
$error_msg = isset($_GET['error']) ? $_GET['error'] : '';
$new_user_id = isset($_GET['new_id']) ? $_GET['new_id'] : '';

// db connection
include("db/connection.php");

// ===== FIXED: Handle shared parameters from URL =====
$shared_sponsor = isset($_GET['sponsor']) ? (int)$_GET['sponsor'] : 0;
$shared_epin = isset($_GET['epin']) ? $_GET['epin'] : '';
$shared_package = isset($_GET['package']) ? (int)$_GET['package'] : 0;

// Validate the shared EPIN exists and is available
$epin_valid = false;
if (!empty($shared_epin)) {
    $pin_check = mysqli_query($conn, "SELECT * FROM pin WHERE pin_value = '$shared_epin' AND status = '0'");
    if (mysqli_num_rows($pin_check) > 0) {
        $epin_valid = true;
        $pin_data = mysqli_fetch_assoc($pin_check);
        
        // If package is not specified, use the PIN's package if available
        if ($shared_package == 0 && isset($pin_data['package_id']) && $pin_data['package_id'] > 0) {
            $shared_package = $pin_data['package_id'];
        }
    } else {
        $shared_epin = ''; // Clear invalid EPIN
    }
}

// Validate sponsor exists
$sponsor_valid = false;
$sponsor_name = "SDB INNOVATIONS";
if ($shared_sponsor > 0) {
    $sponsor_check = mysqli_query($conn, "SELECT name FROM users WHERE user_id = $shared_sponsor");
    if ($sponsor_check && mysqli_num_rows($sponsor_check) > 0) {
        $sponsor_valid = true;
        $sponsor_data = mysqli_fetch_assoc($sponsor_check);
        $sponsor_name = $sponsor_data['name'];
    } else {
        $shared_sponsor = '0'; // Default to root if invalid
    }
} else {
    $shared_sponsor = '0'; // Default root sponsor
}

// Validate package
if ($shared_package != 2500 && $shared_package != 3500) {
    $shared_package = 2500; // Default to starter
}

// For demo, if no DB row, set fallback
$row = [];
$row[1] = "SDB INNOVATIONS";
$row[3] = "8171437264";
include('assets/header.php');
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title><?php echo $row[1]; ?> | Member Registration</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta content="Register as a member with SDB Innovations" name="description">

    <!-- Favicon -->
    <link href="img/logo/logo22222.ico" rel="icon">

    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">

    <!-- Font Awesome & Bootstrap Icons -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">

    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- AOS Animation Library -->
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">

    <!-- SweetAlert2 -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <style>
        
        
        .registration-container {
            max-width: 1000px;
            margin: 98px auto;
        }
        
        .glass-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            border-radius: 30px;
            padding: 40px;
        }
        
        .form-header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .form-header h2 {
            font-size: 2.5rem;
            font-weight: 700;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin-bottom: 10px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            display: block;
        }
        
        .form-label i {
            color: var(--primary);
            margin-right: 8px;
        }
        
        .form-control, .input-group-text {
            border: 2px solid #e2e8f0;
            border-radius: 15px;
            padding: 12px 20px;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgb(75 23 193 / 35%);
            outline: none;
        }
        
        .input-group-text {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
        }
        
        /* Sponsor Info Card */
        .sponsor-info-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            margin-top: 10px;
            margin-bottom: 20px;
            display: none;
            animation: slideDown 0.3s ease;
        }
        
        .sponsor-info-card.show {
            display: block;
        }
        
        .sponsor-info-card .sponsor-detail {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .sponsor-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: rgba(255,255,255,0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: bold;
            border: 2px solid white;
        }
        
        .sponsor-details h4 {
            margin: 0;
            font-size: 1.2rem;
            font-weight: 600;
        }
        
        .sponsor-details p {
            margin: 5px 0 0;
            opacity: 0.9;
            font-size: 0.9rem;
        }
        
        .sponsor-stats {
            display: flex;
            gap: 15px;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid rgba(255,255,255,0.2);
        }
        
        .sponsor-stat {
            flex: 1;
            text-align: center;
        }
        
        .sponsor-stat-label {
            font-size: 0.8rem;
            opacity: 0.9;
            margin-bottom: 5px;
        }
        
        .sponsor-stat-value {
            font-size: 1.2rem;
            font-weight: 700;
        }
        
        .sponsor-badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 20px;
            background: rgba(255,255,255,0.2);
            font-size: 0.8rem;
            margin-left: 10px;
        }
        
        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .pin-input-wrapper {
            position: relative;
        }
        
        .pin-status-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 1.2rem;
        }
        
        .pin-valid {
            color: #10b981;
        }
        
        .pin-invalid {
            color: #ef4444;
        }
        
        .pin-info-text {
            font-size: 0.85rem;
            margin-top: 5px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .btn-submit {
            width: 100%;
            padding: 15px;
            border: none;
            border-radius: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: 700;
            font-size: 1.1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            margin-top: 20px;
        }
        
        .btn-submit:hover:not(:disabled) {
            transform: translateY(-3px);
            box-shadow: 0 15px 30px rgba(102, 126, 234, 0.5);
        }
        
        .btn-submit:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .password-requirements {
            background: #f8fafc;
            border-radius: 12px;
            padding: 12px 15px;
            margin-top: 10px;
            font-size: 0.85rem;
        }
        
        .requirement-item {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #64748b;
            margin-bottom: 5px;
        }
        
        .requirement-item.valid {
            color: #10b981;
        }
        
        .success-message {
            background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            color: #1e293b;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .error-message {
            background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);
            color: #1e293b;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        @keyframes slideIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @media screen and (max-width: 600px) {
         .registration-container {
    margin: 25px auto;
}   
        }
        
        .animate-slide {
            animation: slideIn 0.5s ease forwards;
        }
        
        .package-selector {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .package-card {
            flex: 1;
            border: 2px solid #e2e8f0;
            border-radius: 15px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }
        
        .package-card.selected {
            border-color: var(--primary);
            background: rgb(75 23 193 / 35%);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.2);
        }
        
        .package-card h4 {
            font-weight: 700;
            color: #333;
        }
        
        .package-card .price {
            font-size: 1.8rem;
            font-weight: 800;
            color: var(--primary);
            margin: 10px 0;
        }
        
        .package-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            background: black;
            color: white;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .package-card .package-badge.popular {
            background: #EC4899;
        }
        
        .aadhaar-preview {
            font-family: monospace;
            font-size: 1.2rem;
            letter-spacing: 2px;
        }
        
        /* Loading spinner */
        .spinner-border-sm {
            width: 1rem;
            height: 1rem;
            border-width: 0.15em;
        }
        
        /* Sponsor search loading */
        .sponsor-search-loading {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
        }
    </style>
</head>

<body>
    <div class="container registration-container">
        <div class="glass-card animate-slide">
            <div class="form-header">
                <h2><i class="fas fa-user-plus me-2"></i>Member Registration</h2>
                <p class="text-muted">Join SDB Innovations today and start your journey</p>
            </div>
            
            <!-- Success/Error Messages -->
            <?php if ($success_msg): ?>
                <div class="success-message">
                    <i class="fas fa-check-circle fa-4x mb-3" style="color: #10b981;"></i>
                    <h3>Registration Successful!</h3>
                    <p class="lead mb-3"><?php echo htmlspecialchars(urldecode($success_msg)); ?></p>
                    <div class="alert alert-light">
                        <p><strong>Please save your User ID carefully!</strong></p>
                        <p>Your User ID: <span class="badge bg-primary fs-4 p-3"><?php echo $new_user_id; ?></span></p>
                    </div>
                    <a href="login.php?user_id=<?php echo $new_user_id; ?>" class="btn btn-light btn-lg mt-3">Go to Login <i class="fas fa-arrow-right ms-2"></i></a>
                </div>
            <?php else: ?>
            
            <!-- Error Message -->
            <?php if ($error_msg): ?>
                <div class="error-message">
                    <i class="fas fa-exclamation-circle fa-2x"></i>
                    <div>
                        <h5 class="mb-1">Registration Failed</h5>
                        <p class="mb-0"><?php echo htmlspecialchars(urldecode($error_msg)); ?></p>
                    </div>
                    <button class="btn-close ms-auto" onclick="this.parentElement.remove()"></button>
                </div>
            <?php endif; ?>
            
            <!-- Package Selector -->
            <!-- Package Selector - UPDATED to use shared_package -->
<div class="package-selector">
    <div class="package-card <?php echo ($shared_package == 2500) ? 'selected' : ''; ?>" 
         data-package="2500" onclick="selectPackage(this, 2500)">
        <span class="package-badge">Starter</span>
        <i class="fas fa-box fa-2x text-primary mb-2"></i>
        <h4>Starter Package</h4>
        <div class="price">₹2,500</div>
        <p class="text-muted small">EMS Foot Massager + Detox Patch + Anti-Radiation Chip + Magnetic Door Mat + Tulsi Drops</p>
    </div>
    <div class="package-card <?php echo ($shared_package == 3500) ? 'selected' : ''; ?>" 
         data-package="3500" onclick="selectPackage(this, 3500)">
        <span class="package-badge popular">Popular</span>
        <i class="fas fa-crown fa-2x text-warning mb-2"></i>
        <h4>Pro Package</h4>
        <div class="price">₹3,500</div>
        <p class="text-muted small">Alkaline Water Jug + Anti-Radiation Chip + EMS Foot Massager + Tulsi Drops + Detox Patch</p>
    </div>
</div>

<!-- Hidden package field -->
<input type="hidden" name="package_id" id="package_id" value="<?php echo $shared_package; ?>">
            
            <form method="POST" action="guest_process_registration.php" id="registrationForm">
                <!-- CSRF Token -->
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['guest_csrf_token']; ?>">
                
                <!-- Package ID -->
                
                <div class="row">
                   <!-- Sponsor ID with lookup - UPDATED to use shared_sponsor -->
<div class="col-md-6">
    <div class="form-group">
        <label class="form-label"><i class="fas fa-user-tie"></i>Sponsor ID <span class="text-danger">*</span></label>
        <div class="position-relative">
            <input type="number" class="form-control" id="sponsor_id" name="sponsor_id" 
                   placeholder="Enter sponsor user ID" required
                   value="<?php echo $shared_sponsor; ?>"
                   onkeyup="lookupSponsor(this.value)" autocomplete="off">
            <div class="sponsor-search-loading" id="sponsorLoading" style="display: none;">
                <div class="spinner-border spinner-border-sm" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
            </div>
        </div>
    </div>
</div>
                    
                    <!-- Sponsor Info Card (appears when valid sponsor found) -->
                    <div class="col-12">
                        <div id="sponsorInfoCard" class="sponsor-info-card">
                            <div class="sponsor-detail">
                                <div class="sponsor-avatar" id="sponsorAvatar">👤</div>
                                <div class="sponsor-details">
                                    <h4 id="sponsorName">Loading...</h4>
                                    <p id="sponsorId">ID: <span id="sponsorIdValue"></span></p>
                                </div>
                            </div>
                            <div class="sponsor-stats">
                                <div class="sponsor-stat">
                                    <div class="sponsor-stat-label">Rank</div>
                                    <div class="sponsor-stat-value" id="sponsorRank">-</div>
                                </div>
                                <div class="sponsor-stat">
                                    <div class="sponsor-stat-label">Team</div>
                                    <div class="sponsor-stat-value" id="sponsorTeam">-</div>
                                </div>
                                <div class="sponsor-stat">
                                    <div class="sponsor-stat-label">Level</div>
                                    <div class="sponsor-stat-value" id="sponsorLevel">-</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Full Name -->
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label"><i class="fas fa-user"></i>Full Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="name" name="name" 
                                   placeholder="Enter your full name" required
                                   oninput="this.value = this.value.toUpperCase()">
                        </div>
                    </div>
                    
                    <!-- Email -->
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label"><i class="fas fa-envelope"></i>Email</label>
                            <input type="email" class="form-control" id="email" name="email" 
                                   placeholder="Enter your email (optional)">
                        </div>
                    </div>
                    
                    <!-- Mobile -->
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label"><i class="fas fa-phone-alt"></i>Mobile <span class="text-danger">*</span></label>
                            <input type="tel" class="form-control" id="phone" name="phone" 
                                   placeholder="10 digit mobile number" required
                                   pattern="[0-9]{10}" maxlength="10"
                                   oninput="this.value = this.value.replace(/[^0-9]/g, '')">
                        </div>
                    </div>
                    
                    <!-- Aadhaar Number -->
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label"><i class="fas fa-id-card"></i>Aadhaar Number <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="aadhaar" name="aadhaar" 
                                   placeholder="12 digit Aadhaar number" required
                                   pattern="[0-9]{12}" maxlength="12"
                                   oninput="this.value = this.value.replace(/[^0-9]/g, ''); formatAadhaar(this.value)">
                            <small class="text-muted">Enter 12 digit Aadhaar number</small>
                            <div id="aadhaarPreview" class="aadhaar-preview mt-2"></div>
                        </div>
                    </div>
                    
                    <!-- E-PIN -->
                    <!-- E-PIN - UPDATED to use shared_epin -->
<div class="col-md-6">
    <div class="form-group">
        <label class="form-label"><i class="fas fa-ticket-alt"></i>E-PIN <span class="text-danger">*</span></label>
        <div class="input-group">
            <span class="input-group-text"><i class="fas fa-key"></i></span>
            <input type="text" class="form-control" id="pin" name="pin" 
                   placeholder="Enter your E-PIN" required
                   value="<?php echo htmlspecialchars($shared_epin); ?>"
                   onkeyup="validatePIN(this.value)" maxlength="20" autocomplete="off">
            <span class="pin-status-icon" id="pinStatus"></span>
        </div>
        <div class="pin-info-text" id="pinMessage">
            <?php if ($epin_valid && !empty($shared_epin)): ?>
                <span style="color: #10b981;"><i class="fas fa-check-circle"></i> Valid PIN from shared link</span>
            <?php endif; ?>
        </div>
    </div>
</div>
                    
                    <!-- Password -->
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label"><i class="fas fa-lock"></i>Password <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-key"></i></span>
                                <input type="password" class="form-control" id="password" name="password" 
                                       placeholder="Create password" required
                                       onkeyup="validatePassword()" autocomplete="new-password">
                            </div>
                        </div>
                    </div>
                    
                    <!-- Confirm Password -->
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label"><i class="fas fa-check-circle"></i>Confirm Password <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-check-circle"></i></span>
                                <input type="password" class="form-control" id="confirm_password" 
                                       name="confirm_password" placeholder="Confirm password" required
                                       onkeyup="validatePasswordMatch()" autocomplete="new-password">
                            </div>
                            <div id="passwordMatchMessage" class="pin-info-text"></div>
                        </div>
                    </div>
                </div>
                
                <!-- Password Requirements -->
                <div class="password-requirements">
                    <div class="requirement-item" id="req-length">
                        <i class="fas fa-circle"></i> At least 6 characters
                    </div>
                    <div class="requirement-item" id="req-match">
                        <i class="fas fa-circle"></i> Passwords match
                    </div>
                </div>
                
                <!-- Terms & Conditions -->
                <div class="form-check mt-3">
                    <input class="form-check-input" type="checkbox" id="terms" required>
                    <label class="form-check-label" for="terms">
                        I agree to the <a href="#" data-bs-toggle="modal" data-bs-target="#termsModal">Terms & Conditions</a> and confirm that the information provided is correct.
                    </label>
                </div>
                
                <!-- Submit Button -->
                <button type="submit" name="guest_registration" class="btn-submit" id="submitBtn">
                    <i class="fas fa-user-plus"></i>
                    <span>Complete Registration</span>
                </button>
                
                <div class="text-center mt-4">
                    <p>Already have an account? <a href="login.php" class="text-primary">Login here</a></p>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Terms Modal -->
    <div class="modal fade" id="termsModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Terms & Conditions</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <h6>1. Registration</h6>
                    <p>By registering, you agree to provide accurate information. One ID per person (Aadhaar based).</p>
                    
                    <h6>2. PIN Usage</h6>
                    <p>E-PIN is valid for one-time use only. Keep your PIN confidential.</p>
                    
                    <h6>3. Income Plan</h6>
                    <p>Income is based on performance and team building. Admin charges: 10%, TDS: 5%.</p>
                    
                    <h6>4. Payouts</h6>
                    <p>Payouts are processed on 1st and 15th of every month.</p>
                    
                    <h6>5. KYC Requirements</h6>
                    <p>Aadhaar is mandatory for registration and future payouts.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">I Agree</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
    
    <!-- Sponsor Lookup PHP Endpoint -->
    <script>
        AOS.init();
        
        // Package selection
        function selectPackage(element, price) {
            document.querySelectorAll('.package-card').forEach(card => {
                card.classList.remove('selected');
            });
            element.classList.add('selected');
            document.getElementById('package_id').value = price;
        }
        
        // Aadhaar formatting
        function formatAadhaar(value) {
            const preview = document.getElementById('aadhaarPreview');
            if (value.length === 12) {
                const formatted = value.replace(/(\d{4})(\d{4})(\d{4})/, '$1 $2 $3');
                preview.innerHTML = '<i class="fas fa-id-card text-primary me-2"></i>' + formatted;
                preview.classList.add('text-success');
            } else {
                preview.innerHTML = '';
            }
        }
        
        // Sponsor lookup function
        let sponsorLookupTimeout;
        function lookupSponsor(userId) {
            clearTimeout(sponsorLookupTimeout);
            
            if (!userId || userId.length < 4) {
                document.getElementById('sponsorInfoCard').classList.remove('show');
                return;
            }
            
            // Show loading spinner
            document.getElementById('sponsorLoading').style.display = 'block';
            
            sponsorLookupTimeout = setTimeout(() => {
                fetch('guest_sponsor_lookup.php?user_id=' + encodeURIComponent(userId))
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById('sponsorLoading').style.display = 'none';
                        
                        if (data.success) {
                            // Update sponsor info card
                            document.getElementById('sponsorName').textContent = data.name;
                            document.getElementById('sponsorIdValue').textContent = data.user_id;
                            document.getElementById('sponsorRank').textContent = data.rank;
                            document.getElementById('sponsorTeam').textContent = data.team_size;
                            document.getElementById('sponsorLevel').textContent = data.level;
                            
                            // Set avatar first letter
                            document.getElementById('sponsorAvatar').textContent = data.name.charAt(0).toUpperCase();
                            
                            // Show the card
                            document.getElementById('sponsorInfoCard').classList.add('show');
                        } else {
                            // Hide card if not found
                            document.getElementById('sponsorInfoCard').classList.remove('show');
                            
                            // Optional: Show error toast
                            if (data.message) {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Invalid Sponsor',
                                    text: data.message,
                                    toast: true,
                                    position: 'top-end',
                                    showConfirmButton: false,
                                    timer: 3000
                                });
                            }
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        document.getElementById('sponsorLoading').style.display = 'none';
                        document.getElementById('sponsorInfoCard').classList.remove('show');
                    });
            }, 500); // Debounce for 500ms
        }
        
        // Initial lookup if sponsor ID is pre-filled
        window.addEventListener('load', function() {
            const initialSponsor = document.getElementById('sponsor_id').value;
            if (initialSponsor) {
                lookupSponsor(initialSponsor);
            }
        });
        
        // PIN Validation
        let pinValid = false;
        let passwordValid = false;
        let passwordsMatch = false;
        
        function validatePIN(pin) {
            const pinStatus = document.getElementById('pinStatus');
            const pinMessage = document.getElementById('pinMessage');
            
            if (pin.length < 4) {
                pinStatus.innerHTML = '';
                pinMessage.innerHTML = '';
                pinValid = false;
                return;
            }
            
            fetch('guest_validate_pin.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'pin=' + encodeURIComponent(pin)
            })
            .then(response => response.json())
            .then(result => {
                if (result.valid) {
                    pinStatus.innerHTML = '<i class="fas fa-check-circle pin-valid"></i>';
                    pinMessage.innerHTML = '<span style="color: #10b981;"><i class="fas fa-check-circle"></i> Valid PIN</span>';
                    pinValid = true;
                    
                    // If PIN has package_id, auto-select package
                    if (result.package_id && result.package_id > 0) {
                        const packageCards = document.querySelectorAll('.package-card');
                        packageCards.forEach(card => {
                            const price = card.getAttribute('data-package');
                            if (parseInt(price) === result.package_id) {
                                selectPackage(card, result.package_id);
                            }
                        });
                    }
                } else {
                    pinStatus.innerHTML = '<i class="fas fa-times-circle pin-invalid"></i>';
                    pinMessage.innerHTML = '<span style="color: #ef4444;"><i class="fas fa-exclamation-circle"></i> ' + result.message + '</span>';
                    pinValid = false;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                pinStatus.innerHTML = '<i class="fas fa-exclamation-triangle pin-invalid"></i>';
                pinMessage.innerHTML = '<span style="color: #ef4444;">Error validating PIN</span>';
                pinValid = false;
            });
        }
        
        // Password Validation
        function validatePassword() {
            const password = document.getElementById('password').value;
            const reqLength = document.getElementById('req-length');
            
            if (password.length >= 6) {
                reqLength.innerHTML = '<i class="fas fa-check-circle" style="color: #10b981;"></i> At least 6 characters ✓';
                reqLength.style.color = '#10b981';
                passwordValid = true;
            } else {
                reqLength.innerHTML = '<i class="fas fa-circle"></i> At least 6 characters';
                reqLength.style.color = '#64748b';
                passwordValid = false;
            }
            
            validatePasswordMatch();
        }
        
        // Password Match Validation
        function validatePasswordMatch() {
            const password = document.getElementById('password').value;
            const confirm = document.getElementById('confirm_password').value;
            const reqMatch = document.getElementById('req-match');
            const message = document.getElementById('passwordMatchMessage');
            
            if (confirm.length > 0) {
                if (password === confirm) {
                    reqMatch.innerHTML = '<i class="fas fa-check-circle" style="color: #10b981;"></i> Passwords match ✓';
                    reqMatch.style.color = '#10b981';
                    message.innerHTML = '<span style="color: #10b981;"><i class="fas fa-check-circle"></i> Passwords match</span>';
                    passwordsMatch = true;
                } else {
                    reqMatch.innerHTML = '<i class="fas fa-circle"></i> Passwords match';
                    reqMatch.style.color = '#64748b';
                    message.innerHTML = '<span style="color: #ef4444;"><i class="fas fa-times-circle"></i> Passwords do not match</span>';
                    passwordsMatch = false;
                }
            } else {
                reqMatch.innerHTML = '<i class="fas fa-circle"></i> Passwords match';
                reqMatch.style.color = '#64748b';
                message.innerHTML = '';
                passwordsMatch = false;
            }
        }
        
        // Form Submission
        document.getElementById('registrationForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Validate Aadhaar length
            const aadhaar = document.getElementById('aadhaar').value;
            if (aadhaar.length !== 12) {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Aadhaar',
                    text: 'Aadhaar number must be exactly 12 digits'
                });
                document.getElementById('aadhaar').focus();
                return;
            }
            
            if (!pinValid) {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid PIN',
                    text: 'Please enter a valid PIN'
                });
                document.getElementById('pin').focus();
                return;
            }
            
            if (!passwordValid) {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Password',
                    text: 'Password must be at least 6 characters'
                });
                document.getElementById('password').focus();
                return;
            }
            
            if (!passwordsMatch) {
                Swal.fire({
                    icon: 'error',
                    title: 'Password Mismatch',
                    text: 'Passwords do not match'
                });
                document.getElementById('confirm_password').focus();
                return;
            }
            
            if (!document.getElementById('terms').checked) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Terms Required',
                    text: 'Please accept the terms and conditions'
                });
                return;
            }
            
            // Show loading
            Swal.fire({
                title: 'Processing...',
                text: 'Please wait while we register you',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            this.submit();
        });
        
        // Auto-validate shared EPIN and load sponsor info on page load
window.addEventListener('load', function() {
    // Lookup sponsor info
    const sponsorId = document.getElementById('sponsor_id').value;
    if (sponsorId) {
        lookupSponsor(sponsorId);
    }
    
    // Validate EPIN if present
    const epin = document.getElementById('pin').value;
    if (epin) {
        setTimeout(() => {
            validatePIN(epin);
        }, 500);
    }
    
    // Show notification if coming from shared link
    <?php if (!empty($shared_epin) && $epin_valid): ?>
    Swal.fire({
        icon: 'success',
        title: 'Registration Link Detected!',
        html: `
            <p>Sponsor ID: <strong><?php echo $shared_sponsor; ?></strong></p>
            <p>E-PIN: <strong><?php echo chunk_split($shared_epin, 4, ' '); ?></strong></p>
            <p>Package: <strong>₹<?php echo $shared_package; ?></strong></p>
            <p class="mt-3">Complete the form to register</p>
        `,
        confirmButtonColor: '#667eea',
        timer: 5000
    });
    <?php endif; ?>
});
    </script>
</body>
</html>