<?php
// Initialize session safely
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Ensure this path jumps up from public/ to the root for config
require_once __DIR__ . '/../config/config.php';
// Include EmailService for sending emails after registration
require_once __DIR__ . '/../admin/includes/EmailService.php';

$settings_file = __DIR__ . '/../config/site-settings.json';
$site_name = 'tipspac';
if (file_exists($settings_file)) {
    $loaded = json_decode(file_get_contents($settings_file), true);
    if (!empty($loaded['site_name'])) $site_name = $loaded['site_name'];
}

// Determine mode based on query string, defaulting to login
$mode = isset($_GET['mode']) && $_GET['mode'] === 'register' ? 'register' : 'login';

$error = '';
$success = '';

// ==========================================
// BACKEND AUTHENTICATION ENGINE
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $mode_submit = $_GET['mode'] ?? 'login';

    // --- REGISTRATION LOGIC ---
    if ($mode_submit === 'register') {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['identity'] ?? '');
        $password = $_POST['password'] ?? '';
        $referral_code = trim($_POST['referral_code'] ?? '');

        if (empty($name) || empty($email) || empty($password)) {
            $error = "All fields are required to deploy a profile.";
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = "Please provide a valid email address.";
        } else {
            // Check if email already exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            
            if ($stmt->fetch()) {
                $error = "This email is already active in the matrix. Please log in.";
            } else {
                // Generate unique referral code for the new user
                $base = strtolower(substr(preg_replace('/[^a-zA-Z0-9]/', '', $name), 0, 4));
                $random = bin2hex(random_bytes(3));
                $new_referral_code = strtoupper($base . $random);
                
                // Ensure uniqueness
                $check_stmt = $pdo->prepare("SELECT id FROM users WHERE referral_code = ?");
                $check_stmt->execute([$new_referral_code]);
                while ($check_stmt->fetch()) {
                    $random = bin2hex(random_bytes(3));
                    $new_referral_code = strtoupper($base . $random);
                    $check_stmt->execute([$new_referral_code]);
                }
                
                // Securely hash the password
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                
                // Insert new user into the database
                $stmt = $pdo->prepare("INSERT INTO users (full_name, email, password, user_tier, status, referral_code) VALUES (?, ?, ?, 'FREE', 'ACTIVE', ?)");
                
                if ($stmt->execute([$name, $email, $hashed_password, $new_referral_code])) {
                    $new_user_id = $pdo->lastInsertId();
                    
                    // --- REFERRAL SYSTEM: Process referral if code was provided ---
                    $referral_message = "";
                    if (!empty($referral_code)) {
                        // Find the referrer by their referral code
                        $stmt = $pdo->prepare("SELECT id, full_name FROM users WHERE referral_code = ? AND status = 'ACTIVE'");
                        $stmt->execute([$referral_code]);
                        $referrer = $stmt->fetch(PDO::FETCH_ASSOC);
                        
                        if ($referrer) {
                            // Check if this user was already referred
                            $check_stmt = $pdo->prepare("SELECT id FROM referrals WHERE invited_user_id = ?");
                            $check_stmt->execute([$new_user_id]);
                            if (!$check_stmt->fetch()) {
                                // Insert referral record
                                $stmt = $pdo->prepare("INSERT INTO referrals (referrer_user_id, invited_user_id, referral_code_used, status) VALUES (?, ?, ?, 'active')");
                                $stmt->execute([$referrer['id'], $new_user_id, $referral_code]);
                                
                                // Update referrer's referral count
                                $stmt = $pdo->prepare("UPDATE users SET referral_count = referral_count + 1, is_affiliate = 1 WHERE id = ?");
                                $stmt->execute([$referrer['id']]);
                                
                                // Check if referrer has reached the threshold for reward (10 referrals)
                                $stmt = $pdo->prepare("SELECT referral_count, referral_rewards_earned FROM users WHERE id = ?");
                                $stmt->execute([$referrer['id']]);
                                $referrer_data = $stmt->fetch(PDO::FETCH_ASSOC);
                                
                                $total_referrals = $referrer_data['referral_count'];
                                $rewards_earned = $referrer_data['referral_rewards_earned'];
                                $threshold = 10;
                                $tiers_earned = floor($total_referrals / $threshold);
                                $new_rewards = $tiers_earned - $rewards_earned;
                                
                                if ($new_rewards > 0) {
                                    // Award VIP days for each new tier
                                    for ($i = 0; $i < $new_rewards; $i++) {
                                        // Award 7 days of VIP
                                        $stmt = $pdo->prepare("
                                            UPDATE users 
                                            SET 
                                                user_tier = 'VIP',
                                                vip_expires_at = CASE 
                                                    WHEN vip_expires_at IS NULL OR vip_expires_at < NOW() 
                                                    THEN DATE_ADD(NOW(), INTERVAL 7 DAY)
                                                    ELSE DATE_ADD(vip_expires_at, INTERVAL 7 DAY)
                                                END,
                                                total_vip_days_earned = total_vip_days_earned + 7
                                            WHERE id = ?
                                        ");
                                        $stmt->execute([$referrer['id']]);
                                        
                                        // Log the reward in referral_rewards table
                                        $reward_stmt = $pdo->prepare("
                                            INSERT INTO referral_rewards (user_id, referral_id, reward_type, days_added, status) 
                                            VALUES (?, (SELECT id FROM referrals WHERE invited_user_id = ? AND referrer_user_id = ?), 'VIP_DAYS', 7, 'COMPLETED')
                                        ");
                                        $reward_stmt->execute([$referrer['id'], $new_user_id, $referrer['id']]);
                                    }
                                    
                                    // Update rewards earned count
                                    $stmt = $pdo->prepare("UPDATE users SET referral_rewards_earned = ? WHERE id = ?");
                                    $stmt->execute([$tiers_earned, $referrer['id']]);
                                }
                                
                                $referral_message = "🎉 You were referred by " . htmlspecialchars($referrer['full_name']) . "!";
                            }
                        } else {
                            $referral_message = "Account created! (Referral code was invalid)";
                        }
                    }
                    
                    // Log the user in immediately after successful registration
                    $_SESSION['user_id'] = $new_user_id;
                    $_SESSION['user_name'] = $name;
                    $_SESSION['user_tier'] = 'FREE';
                    
                    // Store referral message for display on dashboard
                    if (!empty($referral_message)) {
                        $_SESSION['referral_message'] = $referral_message;
                    }
                    
                    // ============================================================
                    // 🔥 SEND WELCOME EMAIL
                    // ============================================================
                    $emailService = new EmailService($pdo);
                    $emailService->sendTemplateEmail('welcome', $email, [
                        'user_name' => $name,
                        'site_url'  => SITE_URL
                    ]);
                    // ============================================================
                    
                    // Route to dashboard
                    header("Location: user/dashboard.php");
                    exit;
                } else {
                    $error = "An internal error occurred during deployment. Please try again.";
                }
            }
        }
    } 
    
    // --- LOGIN LOGIC ---
    elseif ($mode_submit === 'login') {
        $identity = trim($_POST['identity'] ?? '');
        $password = $_POST['password'] ?? '';

        if (empty($identity) || empty($password)) {
            $error = "Please provide your credentials to access the terminal.";
        } else {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? OR full_name = ? LIMIT 1");
            $stmt->execute([$identity, $identity]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && password_verify($password, $user['password'])) {
                if ($user['status'] === 'BANNED') {
                    $error = "Terminal Access Denied. Account suspended.";
                } else {
                    $current_tier = $user['user_tier'];
                    if ($current_tier === 'VIP' && !empty($user['vip_expires_at'])) {
                        if (strtotime($user['vip_expires_at']) < time()) {
                            $current_tier = 'FREE';
                            $updateStmt = $pdo->prepare("UPDATE users SET user_tier = 'FREE', vip_expires_at = NULL WHERE id = ?");
                            $updateStmt->execute([$user['id']]);
                        }
                    }

                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['user_name'] = $user['full_name'];
                    $_SESSION['user_tier'] = $current_tier;

                    header("Location: user/dashboard.php");
                    exit;
                }
            } else {
                $error = "Invalid credentials. Access denied.";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo ucfirst($mode); ?> Terminal - <?php echo htmlspecialchars($site_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        /* Custom styles matching PPT design */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: #020617;
            color: #e2e8f0;
        }
        
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: #020617; }
        ::-webkit-scrollbar-thumb { background: #1e293b; border-radius: 10px; }
        ::-webkit-scrollbar-thumb:hover { background: #334155; }
        
        .gradient-text {
            background: linear-gradient(135deg, #10b981, #06b6d4);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #10b981, #059669);
            transition: all 0.3s ease;
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #059669, #047857);
            transform: translateY(-2px);
            box-shadow: 0 0 30px rgba(16, 185, 129, 0.3);
        }
        
        .input-focus:focus {
            border-color: #10b981;
            box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
        }
        
        .referral-info {
            background: rgba(16, 185, 129, 0.05);
            border: 1px solid rgba(16, 185, 129, 0.1);
            border-radius: 0.75rem;
            padding: 0.75rem 1rem;
        }
        .referral-info .label {
            font-size: 9px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            color: #94a3b8;
        }
        .referral-info .hint {
            font-size: 10px;
            color: #64748b;
            margin-top: 2px;
        }
    </style>
</head>
<body class="min-h-screen flex flex-col justify-center relative overflow-x-hidden px-4 sm:px-6 py-8">

    <!-- Exit Button -->
    <header class="absolute top-6 right-6 z-50">
        <a href="index.php" class="text-[9px] font-black text-slate-400 hover:text-white transition uppercase tracking-[0.2em] bg-slate-900/60 backdrop-blur border border-slate-800 px-4 py-2.5 rounded-xl shadow-lg flex items-center gap-2">
            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
            Exit Terminal
        </a>
    </header>

    <!-- Background Effects -->
    <div class="fixed inset-0 z-0 pointer-events-none opacity-20 bg-cover bg-center bg-no-repeat" style="background-image: url('https://images.unsplash.com/photo-1579952363873-27f3bade9f55?q=80&w=2000&auto=format&fit=crop');"></div>
    <div class="fixed inset-0 z-0 bg-gradient-to-t from-[#020617] via-[#020617]/85 to-transparent pointer-events-none"></div>
    
    <!-- Neural Network Canvas -->
    <canvas id="neuralCanvas" class="fixed inset-0 w-full h-full pointer-events-none z-0 opacity-20"></canvas>

    <main class="relative z-10 flex-1 w-full flex items-center justify-center max-w-6xl mx-auto">
        
        <div class="w-full bg-slate-900/40 backdrop-blur-2xl border border-slate-800/80 rounded-[2rem] overflow-hidden shadow-[0_0_60px_rgba(0,0,0,0.6)] grid grid-cols-1 md:grid-cols-2 gap-0">
            
            <!-- LEFT SIDE - Branding/Info Panel -->
            <div class="relative p-8 md:p-10 overflow-hidden hidden md:flex flex-col justify-center border-r border-slate-800/60" style="background: linear-gradient(180deg, rgba(16, 185, 129, 0.05), rgba(6, 182, 212, 0.05));">
                <div class="absolute -top-32 -left-32 w-96 h-96 bg-emerald-500/10 rounded-full blur-[120px] pointer-events-none"></div>
                <div class="absolute -bottom-32 -right-32 w-96 h-96 bg-cyan-500/10 rounded-full blur-[120px] pointer-events-none"></div>

                <div class="relative z-10 space-y-6">
                    <!-- Logo/Badge -->
                    <div class="inline-flex items-center gap-2 bg-emerald-500/10 border border-emerald-500/20 rounded-full px-4 py-1.5 w-fit">
                        <span class="w-2 h-2 bg-emerald-400 rounded-full animate-pulse"></span>
                        <span class="text-emerald-400 text-[10px] font-bold tracking-wider uppercase">AI-Powered Engine</span>
                    </div>

                    <!-- Main Headline -->
                    <h1 class="text-3xl md:text-4xl lg:text-5xl font-black text-white tracking-tight leading-tight">
                        Smarter <br>
                        <span class="gradient-text">Predictions</span>
                    </h1>

                    <!-- Sub-headline -->
                    <h2 class="text-xl md:text-2xl font-bold text-slate-300">
                        Driven by <span class="text-emerald-400">Deep Learning</span>
                    </h2>

                    <!-- Description -->
                    <p class="text-sm text-slate-400 leading-relaxed max-w-sm">
                        Stop guessing. Our exclusive machine-learning algorithms process millions of 
                        historical data points and tactical conditions to yield highly calculated match outcomes.
                    </p>

                    <!-- Feature List -->
                    <ul class="space-y-3 pt-2">
                        <li class="flex items-center gap-3 text-xs font-bold text-slate-300">
                            <div class="w-7 h-7 rounded-full bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center text-emerald-400 text-[10px]">✦</div>
                            <span>Smart Predictions, Powered by AI</span>
                        </li>
                        <li class="flex items-center gap-3 text-xs font-bold text-slate-300">
                            <div class="w-7 h-7 rounded-full bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center text-emerald-400 text-[10px]">🎯</div>
                            <span>Bankers — 75%+ Success Rate</span>
                        </li>
                        <li class="flex items-center gap-3 text-xs font-bold text-slate-300">
                            <div class="w-7 h-7 rounded-full bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center text-emerald-400 text-[10px]">📈</div>
                            <span>See the Game Differently</span>
                        </li>
                    </ul>

                    <!-- Stats/Trust Badge -->
                    <div class="mt-4 flex items-center gap-6 pt-4 border-t border-slate-800/60">
                        <div>
                            <div class="text-xl font-bold text-white">98.7%</div>
                            <div class="text-[9px] text-slate-500">Accuracy</div>
                        </div>
                        <div>
                            <div class="text-xl font-bold text-white">2.4M+</div>
                            <div class="text-[9px] text-slate-500">Data Points</div>
                        </div>
                        <div>
                            <div class="text-xl font-bold text-white">150+</div>
                            <div class="text-[9px] text-slate-500">Leagues</div>
                        </div>
                    </div>

                    <!-- Referral Reward Info -->
                    <div class="mt-4 p-4 bg-emerald-500/5 border border-emerald-500/10 rounded-xl">
                        <div class="flex items-center gap-2 text-emerald-400 text-xs font-bold">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v1m0-1c-1.11 0-2.08.402-2.599 1M12 9v1m0-1c1.11 0 2.08-.402 2.599-1M12 9v1m0 1c-1.11 0-2.08-.402-2.599-1M12 12v1m0-1c1.11 0 2.08.402 2.599 1M12 12v1m0 1c-1.11 0-2.08-.402-2.599-1M12 15v1m0-1c1.11 0 2.08.402 2.599 1M12 15v1"></path>
                            </svg>
                            Referral Rewards
                        </div>
                        <p class="text-[10px] text-slate-400 mt-1">
                            Refer 10 friends and get <span class="text-emerald-400 font-bold">7 days of VIP</span> access absolutely FREE!
                        </p>
                    </div>
                </div>
            </div>

            <!-- RIGHT SIDE - Login/Register Form -->
            <div class="p-6 sm:p-8 md:p-10 relative flex flex-col justify-center">
                
                <!-- Toggle Tabs -->
                <div class="bg-slate-950 border border-slate-800 rounded-xl p-1 flex mb-8 w-full max-w-[240px]">
                    <a href="login-register.php?mode=login" class="flex-1 <?php echo $mode === 'login' ? 'bg-emerald-600 shadow text-white' : 'text-slate-400 hover:text-white'; ?> text-[10px] font-bold uppercase tracking-widest py-2.5 rounded-lg transition text-center">Login</a>
                    <a href="login-register.php?mode=register" class="flex-1 <?php echo $mode === 'register' ? 'bg-emerald-600 shadow text-white' : 'text-slate-400 hover:text-white'; ?> text-[10px] font-bold uppercase tracking-widest py-2.5 rounded-lg transition text-center">Register</a>
                </div>

                <!-- Form Header -->
                <?php if ($mode === 'login'): ?>
                    <div class="space-y-1.5 mb-6">
                        <h2 class="text-xl sm:text-2xl font-black text-white tracking-tight">Welcome back</h2>
                        <p class="text-[10px] sm:text-[11px] text-slate-400">Unlock smarter predictions powered by AI.</p>
                    </div>
                <?php else: ?>
                    <div class="space-y-1.5 mb-6">
                        <h2 class="text-xl sm:text-2xl font-black text-white tracking-tight">Create Account</h2>
                        <p class="text-[10px] sm:text-[11px] text-slate-400">Start making smarter predictions today.</p>
                        <?php if (isset($_GET['ref']) && !empty($_GET['ref'])): ?>
                            <div class="referral-info mt-3">
                                <div class="label">🎁 Referral Program</div>
                                <div class="hint">You are signing up with a referral code. Get started with benefits!</div>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

                <!-- Error Message -->
                <?php if ($error): ?>
                    <div class="bg-rose-500/10 border border-rose-500/20 text-rose-400 text-[10px] p-3 rounded-xl mb-5">
                        <div class="flex items-center gap-2">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                            <?php echo htmlspecialchars($error); ?>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Form -->
                <form method="POST" action="login-register.php?mode=<?php echo $mode; ?>" class="space-y-4 max-w-md w-full">
                    
                    <?php if ($mode === 'register'): ?>
                        <!-- Full Name -->
                        <div class="space-y-1">
                            <label class="block text-[9px] font-bold text-slate-300 uppercase tracking-wider">Full Name</label>
                            <input type="text" name="name" placeholder="John Doe" class="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 px-4 text-[11px] text-white focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 transition-all placeholder-slate-600 input-focus" required>
                        </div>
                    <?php endif; ?>

                    <!-- Email/Username -->
                    <div class="space-y-1">
                        <label class="block text-[9px] font-bold text-slate-300 uppercase tracking-wider">Username or Email</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                <svg class="w-3.5 h-3.5 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                                </svg>
                            </div>
                            <input type="text" name="identity" placeholder="john@example.com" class="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 pl-11 pr-4 text-[11px] text-white focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 transition-all placeholder-slate-600 input-focus" required>
                        </div>
                    </div>

                    <!-- Password -->
                    <div class="space-y-1">
                        <label class="block text-[9px] font-bold text-slate-300 uppercase tracking-wider">Password</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                <svg class="w-3.5 h-3.5 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
                                </svg>
                            </div>
                            <input type="password" name="password" placeholder="••••••••" class="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 pl-11 pr-10 text-[11px] text-white focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 transition-all placeholder-slate-600 input-focus" required>
                            <div class="absolute inset-y-0 right-0 pr-4 flex items-center cursor-pointer text-slate-500 hover:text-white transition toggle-password">
                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                                </svg>
                            </div>
                        </div>
                    </div>

                    <!-- REFERRAL CODE FIELD - Only for Registration -->
                    <?php if ($mode === 'register'): ?>
                        <div class="space-y-1">
                            <label class="block text-[9px] font-bold text-slate-300 uppercase tracking-wider">
                                Referral Code <span class="text-slate-500 font-normal">(optional)</span>
                            </label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                    <svg class="w-3.5 h-3.5 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                                    </svg>
                                </div>
                                <input type="text" name="referral_code" 
                                       placeholder="Enter referral code (e.g., JOHN3X7K)" 
                                       value="<?php echo isset($_GET['ref']) ? htmlspecialchars($_GET['ref']) : ''; ?>"
                                       class="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 pl-11 pr-4 text-[11px] text-white focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 transition-all placeholder-slate-600 input-focus">
                            </div>
                            <p class="text-[8px] text-slate-500 mt-1">
                                Enter a friend's referral code to earn rewards together! 🎁
                            </p>
                        </div>
                    <?php endif; ?>

                    <!-- Terms & Conditions -->
                    <?php if ($mode === 'login'): ?>
                        <div class="flex items-center justify-between pt-1 text-[9px]">
                            <label class="flex items-center space-x-2 cursor-pointer group">
                                <input type="checkbox" checked class="w-3.5 h-3.5 rounded border-slate-700 bg-slate-950 text-emerald-500 focus:ring-emerald-500 focus:ring-offset-slate-900 cursor-pointer">
                                <span class="text-slate-400 group-hover:text-white transition">Keep me logged in</span>
                            </label>
                            <a href="#" class="font-bold text-slate-400 hover:text-emerald-400 transition">Forgot details?</a>
                        </div>
                    <?php else: ?>
                        <div class="pt-1 text-[9px]">
                            <label class="flex items-center space-x-2 cursor-pointer group">
                                <input type="checkbox" required class="w-3.5 h-3.5 rounded border-slate-700 bg-slate-950 text-emerald-500 focus:ring-emerald-500 focus:ring-offset-slate-900 cursor-pointer">
                                <span class="text-slate-400 group-hover:text-white transition">I accept the <a href="terms.php" class="text-emerald-400 hover:underline">Terms & Conditions</a></span>
                            </label>
                        </div>
                    <?php endif; ?>

                    <!-- Submit Button -->
                    <button type="submit" class="w-full btn-primary text-white font-black py-3.5 rounded-xl text-[10px] uppercase tracking-[0.15em] transition flex items-center justify-center gap-2 mt-2">
                        <span><?php echo ucfirst($mode); ?></span>
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7l5 5m0 0l-5 5m5-5H6"></path>
                        </svg>
                    </button>
                </form>

                <!-- Footer Links -->
                <?php if ($mode === 'login'): ?>
                    <div class="mt-6 text-center">
                        <span class="text-[9px] text-slate-500 tracking-wider">Don't have an account? <a href="login-register.php?mode=register" class="text-emerald-400 font-bold hover:underline">Get started now</a></span>
                    </div>
                <?php else: ?>
                    <div class="mt-6 text-center">
                        <span class="text-[9px] text-slate-500 tracking-wider">Already have an account? <a href="login-register.php?mode=login" class="text-emerald-400 font-bold hover:underline">Log in directly</a></span>
                        <div class="mt-3 text-[8px] text-slate-600">
                            Have a referral code? It will be applied automatically! 🎯
                        </div>
                    </div>
                <?php endif; ?>

            </div>
        </div>
    </main>

    <!-- JavaScript -->
    <script>
        // Neural Network Canvas
        const canvas = document.getElementById("neuralCanvas");
        if(canvas) {
            const ctx = canvas.getContext("2d");
            let width, height;
            let particles = [];
            let mouse = { x: null, y: null };
            
            window.addEventListener('mousemove', function(e) {
                mouse.x = e.x;
                mouse.y = e.y;
            });

            function initCanvas() {
                width = canvas.width = window.innerWidth;
                height = canvas.height = window.innerHeight;
                particles = [];
                let particleCount = (width * height) / 15000;
                for (let i = 0; i < particleCount; i++) {
                    particles.push({
                        x: Math.random() * width,
                        y: Math.random() * height,
                        vx: (Math.random() - 0.5) * 1.5,
                        vy: (Math.random() - 0.5) * 1.5,
                        radius: Math.random() * 1.5 + 0.5
                    });
                }
            }

            function animateCanvas() {
                ctx.clearRect(0, 0, width, height);
                for (let i = 0; i < particles.length; i++) {
                    let p = particles[i];
                    p.x += p.vx;
                    p.y += p.vy;
                    if (p.x < 0 || p.x > width) p.vx *= -1;
                    if (p.y < 0 || p.y > height) p.vy *= -1;
                    
                    ctx.beginPath();
                    ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
                    ctx.fillStyle = "rgba(16, 185, 129, 0.3)";
                    ctx.fill();
                    
                    for (let j = i + 1; j < particles.length; j++) {
                        let p2 = particles[j];
                        let dist = Math.sqrt(Math.pow(p.x - p2.x, 2) + Math.pow(p.y - p2.y, 2));
                        if (dist < 100) {
                            ctx.beginPath();
                            ctx.moveTo(p.x, p.y);
                            ctx.lineTo(p2.x, p2.y);
                            ctx.strokeStyle = `rgba(16, 185, 129, ${0.8 - dist/100})`;
                            ctx.lineWidth = 0.5;
                            ctx.stroke();
                        }
                    }
                }
                requestAnimationFrame(animateCanvas);
            }
            
            window.addEventListener("resize", initCanvas);
            initCanvas();
            animateCanvas();
        }

        // Password Toggle
        document.querySelectorAll('.toggle-password').forEach(button => {
            button.addEventListener('click', function() {
                const input = this.closest('.relative').querySelector('input');
                if (input.type === 'password') {
                    input.type = 'text';
                } else {
                    input.type = 'password';
                }
            });
        });

        // Auto-fill referral code from URL
        const urlParams = new URLSearchParams(window.location.search);
        const refCode = urlParams.get('ref');
        if (refCode) {
            const referralInput = document.querySelector('input[name="referral_code"]');
            if (referralInput) {
                referralInput.value = refCode;
                referralInput.style.borderColor = '#10b981';
            }
        }
    </script>
</body>
</html>