<?php
// 1. GLOBAL CRASH PROTECTION
ob_start();
session_start();
error_reporting(0); 
ini_set('display_errors', 0); 

// 2. RESPONSE HELPER
function return_json($data) {
    // Clear buffer to prevent "Network response was not ok" caused by PHP warnings
    if (ob_get_length()) ob_clean(); 
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

try {
    // 3. DATABASE CONNECTION
    $db_file = file_exists('db.php') ? 'db.php' : (file_exists('db_config.php') ? 'db_config.php' : null);
    if (!$db_file) throw new Exception("Database file (db.php) not found.");
    require_once $db_file;
    if ($conn->connect_error) throw new Exception("DB Connection Failed: " . $conn->connect_error);

    // 4. AUTO-REPAIR TABLES (Fixes missing tables/columns)
    $conn->query("CREATE TABLE IF NOT EXISTS wallets (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        balance DECIMAL(10,2) DEFAULT 0.00,
        referral_count INT DEFAULT 0,
        referral_commission DECIMAL(10,2) DEFAULT 0.00
    )");

    $conn->query("CREATE TABLE IF NOT EXISTS transactions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        transaction_type VARCHAR(50),
        amount DECIMAL(10,2),
        status VARCHAR(20),
        description VARCHAR(255),
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");

    $conn->query("CREATE TABLE IF NOT EXISTS password_resets (
        id INT AUTO_INCREMENT PRIMARY KEY,
        email VARCHAR(255) NOT NULL,
        token VARCHAR(255) NOT NULL,
        expires_at DATETIME NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");
    
    // Fix Missing Token Column automatically
    $colCheck = $conn->query("SHOW COLUMNS FROM password_resets LIKE 'token'");
    if ($colCheck->num_rows == 0) {
        $conn->query("ALTER TABLE password_resets ADD COLUMN token VARCHAR(255) NOT NULL AFTER email");
    }

    // 5. SMART PHPMAILER LOADER (Finds the file wherever it is)
    $mailAvailable = false;
    $possible_paths = [
        'PHPMailer/src/',
        'PHPMailer/',
        'PHPMailer/PHPMailer/src/',
        'vendor/phpmailer/phpmailer/src/'
    ];

    foreach ($possible_paths as $path) {
        if (file_exists($path . 'PHPMailer.php')) {
            if(file_exists($path . 'Exception.php')) require_once $path . 'Exception.php';
            require_once $path . 'PHPMailer.php';
            if(file_exists($path . 'SMTP.php')) require_once $path . 'SMTP.php';
            
            // Check if class exists to be sure
            if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
                $mailAvailable = true;
            }
            break; 
        }
    }

    // --- FORM LOGIC ---

    // AJAX CHECKS
    if (isset($_POST['check_username'])) {
        $stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
        $stmt->bind_param("s", $_POST['username']);
        $stmt->execute();
        ob_end_clean(); echo $stmt->get_result()->num_rows > 0 ? "exists" : "available"; exit;
    }
    if (isset($_POST['check_email'])) {
        $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->bind_param("s", $_POST['email']);
        $stmt->execute();
        ob_end_clean(); echo $stmt->get_result()->num_rows > 0 ? "exists" : "available"; exit;
    }
    if (isset($_POST['check_phone'])) {
        $stmt = $conn->prepare("SELECT id FROM users WHERE phone = ?");
        $stmt->bind_param("s", $_POST['phone']);
        $stmt->execute();
        ob_end_clean(); echo $stmt->get_result()->num_rows > 0 ? "exists" : "available"; exit;
    }

    // POST REQUESTS
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['form_type'])) {
        
        // --- REGISTER ---
        if ($_POST['form_type'] == 'register') {
            $first_name = trim($_POST['first_name']);
            $last_name  = trim($_POST['last_name']);
            $username   = trim($_POST['username']);
            $email      = trim($_POST['email']);
            $phone      = trim($_POST['phone']);
            $password   = $_POST['password'];
            $referred_by = !empty($_POST['referred_by']) ? trim($_POST['referred_by']) : NULL;
            $referral_code = strtoupper(substr(md5(uniqid()), 0, 6));

            if (empty($first_name) || empty($username) || empty($password)) return_json(['success' => false, 'message' => "Fill all fields."]);

            $chk = $conn->prepare("SELECT id FROM users WHERE username=? OR email=? OR phone=?");
            $chk->bind_param("sss", $username, $email, $phone);
            $chk->execute();
            if ($chk->get_result()->num_rows > 0) return_json(['success' => false, 'message' => "User already exists."]);

            $hashed = password_hash($password, PASSWORD_BCRYPT);
            $stmt = $conn->prepare("INSERT INTO users (first_name, last_name, username, email, phone, password, referral_code, referred_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssssss", $first_name, $last_name, $username, $email, $phone, $hashed, $referral_code, $referred_by);

            if ($stmt->execute()) {
                $new_user_id = $conn->insert_id;
                
                // 1. CREATE WALLET FOR NEW USER (Essential)
                $conn->query("INSERT INTO wallets (user_id, balance) VALUES ($new_user_id, 0.00)");

                $_SESSION['user_id'] = $new_user_id;
                $_SESSION['username'] = $username;
                
                // 2. PROCESS REFERRAL BONUS
                if ($referred_by) {
                    $refQ = $conn->query("SELECT id FROM users WHERE username = '$referred_by'");
                    if ($refQ && $refQ->num_rows > 0) {
                        $referrer_id = $refQ->fetch_assoc()['id'];
                        
                        // FIX: Ensure Referrer has a wallet BEFORE updating
                        $chkRefWallet = $conn->query("SELECT id FROM wallets WHERE user_id = $referrer_id");
                        if ($chkRefWallet->num_rows == 0) {
                            $conn->query("INSERT INTO wallets (user_id, balance) VALUES ($referrer_id, 0.00)");
                        }

                        // A. Add Money
                        $update_success = $conn->query("UPDATE wallets SET balance = balance + 20, referral_count = referral_count + 1, referral_commission = referral_commission + 20 WHERE user_id = $referrer_id");
                        
                        // B. Log Transaction (Only if wallet updated)
                        if ($update_success) {
                            $conn->query("INSERT INTO transactions (user_id, transaction_type, amount, status, description) VALUES ($referrer_id, 'referral_bonus', 20, 'success', 'Referral Bonus for $username')");
                        }
                    }
                }
                
                return_json(['success' => true, 'message' => "Welcome!", 'redirect' => "dashboard.php"]);
            } else {
                return_json(['success' => false, 'message' => "Registration Failed."]);
            }
        }

        // --- LOGIN ---
        elseif ($_POST['form_type'] == 'login') {
            $username = trim($_POST['username']);
            $password = $_POST['password'];

            $stmt = $conn->prepare("SELECT id, username, password FROM users WHERE username = ?");
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();

            if ($user && password_verify($password, $user['password'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                return_json(['success' => true, 'message' => "Login successful!", 'redirect' => "dashboard.php"]);
            } else {
                return_json(['success' => false, 'message' => "Invalid credentials."]);
            }
        }

        // --- RESET PASSWORD ---
        elseif ($_POST['form_type'] == 'reset_password') {
            $email = trim($_POST['email']);
            
            $stmt = $conn->prepare("SELECT id, first_name FROM users WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $res = $stmt->get_result();
            
            if ($res->num_rows > 0) {
                $user = $res->fetch_assoc();
                $token = bin2hex(random_bytes(32));
                $expires = date("Y-m-d H:i:s", strtotime("+1 hour"));
                
                $conn->query("DELETE FROM password_resets WHERE email = '$email'");
                $ins = $conn->prepare("INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, ?)");
                $ins->bind_param("sss", $email, $token, $expires);
                
                if($ins->execute()) {
                    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                    $host = $_SERVER['HTTP_HOST'];
                    $resetLink = "$protocol://$host/reset_password.php?token=$token";
                    
                    if (!$mailAvailable) {
                        return_json(['success' => true, 'message' => "System Link (Email Offline): " . $resetLink]);
                    }

                    try {
                        // Handle Namespace vs Global class based on what was loaded
                        $mail = class_exists('PHPMailer\PHPMailer\PHPMailer') ? new PHPMailer\PHPMailer\PHPMailer(true) : new PHPMailer(true);
                        $mail->isSMTP();
                        $mail->Host       = 'smtp.gmail.com'; 
                        $mail->SMTPAuth   = true;
                        $mail->Username   = 'Wisehs.sender@gmail.com'; 
                        $mail->Password   = 'vmbr cdwy lvsa nkyv'; 
                        $mail->SMTPSecure = 'tls'; 
                        $mail->Port       = 587;

                        $mail->setFrom('Wisehs.sender@gmail.com', 'Nagarta Data Support');
                        $mail->addAddress($email, $user['first_name']);
                        $mail->isHTML(true);
                        $mail->Subject = 'Reset Your Password';
                        $mail->Body    = "
                        <div style='background:#f4f4f4; padding:20px; font-family:Arial;'>
                            <div style='background:white; max-width:500px; margin:auto; padding:20px; border-radius:10px;'>
                                <h2 style='color:#2c5364; text-align:center;'>Reset Password</h2>
                                <p>Hello <strong>{$user['first_name']}</strong>,</p>
                                <p>Click below to reset your password:</p>
                                <p style='text-align:center;'><a href='$resetLink' style='background:#10b981; color:white; padding:10px 20px; text-decoration:none; border-radius:5px;'>Reset Password</a></p>
                                <p style='font-size:12px; color:#888;'>Or copy: $resetLink</p>
                            </div>
                        </div>";

                        $mail->send();
                        return_json(['success' => true, 'message' => "Reset link sent to your email!"]);
                    } catch (Exception $e) {
                        return_json(['success' => true, 'message' => "Email failed. Use this link: " . $resetLink]);
                    }
                } else {
                    return_json(['success' => false, 'message' => "Failed to generate token."]);
                }
            } else {
                return_json(['success' => false, 'message' => "Email not found."]);
            }
        }
    }

} catch (Exception $e) {
    return_json(['success' => false, 'message' => "System Error: " . $e->getMessage()]);
}

ob_end_clean();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nagarta Data Sub - Fast & Reliable Data Services</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* CSS STYLES */
        :root { --primary: #10b981; --primary-dark: #203A96; --primary-light: #d1fae5; --secondary: #059669; --accent: #f59e0b; --light: #f8fafc; --dark: #203A96; --success: #34d399; --warning: #fbbf24; --danger: #ef4444; --gray: #64748b; --gray-light: #e2e8f0; --border-radius: 16px; --box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08); --transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        body { background: linear-gradient(135deg, #f0fdf4 0%, #ecfdf5 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 20px; color: var(--dark); overflow-x: hidden; }
        .container { width: 100%; max-width: 1200px; display: flex; flex-direction: column; align-items: center; animation: fadeIn 1s ease; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        .logo { margin-bottom: 30px; text-align: center; animation: bounceIn 1s ease; }
        @keyframes bounceIn { 0% { transform: scale(0.8); opacity: 0; } 70% { transform: scale(1.05); } 100% { transform: scale(1); opacity: 1; } }
        .logo img { max-width: 180px; height: auto; margin-bottom: 15px; filter: drop-shadow(0 5px 15px rgba(0, 0, 0, 0.1)); }
        .logo h1 { color: var(--primary); font-size: 2.8rem; font-weight: 800; margin-bottom: 10px; text-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); }
        .logo p { color: var(--gray); font-size: 1.2rem; max-width: 600px; line-height: 1.6; }
        .hero-section { display: flex; flex-wrap: wrap; gap: 40px; align-items: center; justify-content: center; margin-bottom: 50px; animation: slideIn 1s ease; }
        @keyframes slideIn { from { opacity: 0; transform: translateX(-30px); } to { opacity: 1; transform: translateX(0); } }
        .hero-content { flex: 1; min-width: 300px; max-width: 600px; }
        .hero-content h2 { font-size: 2.5rem; color: var(--dark); margin-bottom: 20px; line-height: 1.2; }
        .hero-content h2 span { color: var(--primary); }
        .hero-content p { color: var(--gray); font-size: 1.1rem; line-height: 1.7; margin-bottom: 30px; }
        .hero-image { flex: 1; min-width: 300px; max-width: 500px; text-align: center; }
        .hero-image img { max-width: 100%; border-radius: 20px; box-shadow: var(--box-shadow); animation: float 6s ease-in-out infinite; }
        @keyframes float { 0% { transform: translateY(0px); } 50% { transform: translateY(-20px); } 100% { transform: translateY(0px); } }
        .features { display: flex; flex-wrap: wrap; gap: 25px; margin-bottom: 50px; width: 100%; justify-content: center; }
        .feature-card { flex: 1; min-width: 250px; max-width: 300px; background: white; border-radius: var(--border-radius); padding: 30px 25px; box-shadow: var(--box-shadow); text-align: center; transition: var(--transition); border-top: 4px solid var(--primary); animation: fadeIn 1s ease; animation-fill-mode: both; }
        .feature-card:nth-child(1) { animation-delay: 0.2s; }
        .feature-card:nth-child(2) { animation-delay: 0.4s; }
        .feature-card:nth-child(3) { animation-delay: 0.6s; }
        .feature-card:hover { transform: translateY(-10px); box-shadow: 0 15px 30px rgba(0, 0, 0, 0.12); }
        .feature-icon { font-size: 2.8rem; color: var(--primary); margin-bottom: 20px; display: inline-block; padding: 15px; border-radius: 50%; background: var(--primary-light); }
        .feature-card h3 { margin-bottom: 15px; color: var(--dark); font-size: 1.3rem; }
        .feature-card p { color: var(--gray); line-height: 1.6; }
        .cta-section { text-align: center; margin-bottom: 50px; animation: pulse 2s infinite; }
        @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.03); } 100% { transform: scale(1); } }
        .cta-section h2 { font-size: 2.2rem; color: var(--dark); margin-bottom: 20px; }
        .cta-section p { color: var(--gray); font-size: 1.1rem; max-width: 700px; margin: 0 auto 30px; line-height: 1.6; }
        .btn-group { display: flex; gap: 20px; justify-content: center; flex-wrap: wrap; }
        .btn { display: inline-block; padding: 16px 35px; background: var(--primary); color: white; border: none; border-radius: 50px; font-size: 1.1rem; font-weight: 600; cursor: pointer; transition: var(--transition); text-align: center; text-decoration: none; box-shadow: 0 5px 15px rgba(16, 185, 129, 0.3); }
        .btn:hover { background: var(--primary-dark); transform: translateY(-5px); box-shadow: 0 10px 20px rgba(16, 185, 129, 0.4); }
        .btn-outline { background: transparent; color: var(--primary); border: 2px solid var(--primary); box-shadow: none; }
        .btn-outline:hover { background: var(--primary); color: white; }
        /* DOWNLOAD BUTTON STYLE */
        .btn-download { background: var(--dark); color: white; border: none; }
        .btn-download:hover { background: #1a2e7a; color: white; box-shadow: 0 10px 20px rgba(32, 58, 150, 0.4); }
        
        .forms-container { width: 100%; max-width: 500px; background: white; border-radius: var(--border-radius); box-shadow: var(--box-shadow); overflow: hidden; display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 1000; animation: zoomIn 0.5s ease; max-height: 90vh; overflow-y: auto; }
        @keyframes zoomIn { from { opacity: 0; transform: translate(-50%, -50%) scale(0.9); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } }
        .form-content { padding: 40px; }
        .form-title { font-size: 1.8rem; margin-bottom: 10px; color: var(--dark); text-align: center; }
        .form-subtitle { color: var(--gray); margin-bottom: 30px; text-align: center; }
        .form-group { margin-bottom: 20px; }
        .form-row { display: flex; gap: 15px; }
        .form-row .form-group { flex: 1; }
        label { display: block; margin-bottom: 8px; font-weight: 500; color: var(--dark); }
        .input-with-icon { position: relative; }
        .input-with-icon i { position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: var(--gray); }
        input { width: 100%; padding: 15px 15px 15px 45px; border: 1px solid var(--gray-light); border-radius: var(--border-radius); font-size: 1rem; transition: var(--transition); }
        input:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.2); }
        .password-toggle { position: absolute; right: 15px; top: 50%; transform: translateY(-50%); color: var(--gray); cursor: pointer; }
        .referral-section { background-color: rgba(16, 185, 129, 0.05); border-radius: var(--border-radius); padding: 20px; margin-top: 20px; border-left: 4px solid var(--primary); }
        .referral-section h3 { color: var(--primary); margin-bottom: 10px; font-size: 1.1rem; }
        .referral-section p { color: var(--gray); font-size: 0.9rem; margin-bottom: 15px; }
        .form-footer { margin-top: 30px; text-align: center; color: var(--gray); }
        .form-footer a { color: var(--primary); text-decoration: none; font-weight: 500; }
        .form-footer a:hover { text-decoration: underline; }
        .alert { padding: 15px; border-radius: var(--border-radius); margin-bottom: 20px; display: none; animation: slideDown 0.5s ease; }
        @keyframes slideDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
        .alert-success { background-color: rgba(52, 211, 153, 0.1); border-left: 4px solid var(--success); color: #0d9669; }
        .alert-error { background-color: rgba(239, 68, 68, 0.1); border-left: 4px solid var(--danger); color: #b91c1c; }
        .close-form { text-align: right; padding: 15px 20px 0 0; position: sticky; top: 0; background: white; z-index: 10; }
        .close-btn { background: none; border: none; font-size: 1.5rem; color: var(--gray); cursor: pointer; transition: var(--transition); }
        .close-btn:hover { color: var(--danger); transform: rotate(90deg); }
        .overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); z-index: 999; }
        .forgot-password { text-align: right; margin-top: 10px; margin-bottom: 20px; }
        .forgot-password a { color: var(--primary); text-decoration: none; font-size: 0.9rem; }
        .forgot-password a:hover { text-decoration: underline; }
        .services-icon { display: flex; justify-content: center; gap: 15px; margin-top: 10px; flex-wrap: wrap; }
        .service-item { display: flex; flex-direction: column; align-items: center; gap: 5px; min-width: 60px; }
        .service-icon { font-size: 1.5rem; color: var(--primary); background: var(--primary-light); padding: 10px; border-radius: 50%; width: 50px; height: 50px; display: flex; align-items: center; justify-content: center; }
        .service-label { font-size: 0.7rem; color: var(--gray); text-align: center; }
        @media (max-width: 768px) { .hero-section { flex-direction: column; text-align: center; } .hero-content h2 { font-size: 2rem; } .btn-group { flex-direction: column; align-items: center; } .btn { width: 100%; max-width: 300px; } .form-row { flex-direction: column; gap: 0; } .form-content { padding: 30px 20px; } .logo h1 { font-size: 2.2rem; } .forms-container { width: 95%; } .services-icon { gap: 10px; } .service-item { min-width: 50px; } .service-icon { width: 45px; height: 45px; font-size: 1.3rem; } }
        @media (max-width: 480px) { .logo h1 { font-size: 1.8rem; } .hero-content h2 { font-size: 1.7rem; } .feature-card { min-width: 100%; } .cta-section h2 { font-size: 1.8rem; } .services-icon { gap: 8px; } .service-item { min-width: 45px; } .service-icon { width: 40px; height: 40px; font-size: 1.1rem; padding: 8px; } .service-label { font-size: 0.65rem; } }
    </style>
</head>
<body>
    <div class="overlay" id="overlay"></div>
    <div class="container">
        <div class="logo">
            <div style="display: flex; align-items: center; justify-content: center; gap: 15px; margin-bottom: 15px;">
                <img src="logo.png" alt="Nagarta Data Sub Logo" style="max-width: 80px;">
                <h1>Nagarta Data Sub</h1>
            </div>
            <p>Fast, reliable data services with instant activation and referral rewards</p>
            <div class="services-icon">
                <div class="service-item"><div class="service-icon"><i class="fas fa-wifi"></i></div><div class="service-label">Data</div></div>
                <div class="service-item"><div class="service-icon"><i class="fas fa-mobile-alt"></i></div><div class="service-label">Airtime</div></div>
                <div class="service-item"><div class="service-icon"><i class="fas fa-graduation-cap"></i></div><div class="service-label">Education</div></div>
                <div class="service-item"><div class="service-icon"><i class="fas fa-file-invoice-dollar"></i></div><div class="service-label">Bills</div></div>
                <div class="service-item"><div class="service-icon"><i class="fas fa-tv"></i></div><div class="service-label">Cable TV</div></div>
            </div>
        </div>
        
        <div class="hero-section">
            <div class="hero-content">
                <h2>Get <span>Lightning-Fast Data</span> For All Networks</h2>
                <p>Nagarta Data Sub provides instant data services with competitive pricing. Enjoy seamless connectivity and earn rewards through our referral program.</p>
                <div class="btn-group">
                    <a href="#" class="btn" id="show-login">Sign In</a>
                    <a href="#" class="btn btn-outline" id="show-register">Create Account</a>
                    <a href="Apps/Nagarta-data.apk" class="btn btn-download" download><i class="fas fa-download" style="margin-right:8px;"></i> Download App</a>
                </div>
            </div>
            <div class="hero-image"><img src="asaad.jpg" alt="Data Connection"></div>
        </div>
        
        <div class="features">
            <div class="feature-card">
                <div class="feature-icon"><i class="fas fa-bolt"></i></div>
                <h3>Instant Activation</h3><p>Get your data plans activated instantly after payment confirmation</p>
            </div>
            <div class="feature-card">
                <div class="feature-icon"><i class="fas fa-money-bill-wave"></i></div>
                <h3>Earn With Referrals</h3><p>Get N20 for each friend you refer and N1 for their data purchases</p>
            </div>
            <div class="feature-card">
                <div class="feature-icon"><i class="fas fa-shield-alt"></i></div>
                <h3>Secure & Reliable</h3><p>Your data and transactions are protected with advanced security</p>
            </div>
        </div>
        
        <div class="cta-section">
            <h2>Join Thousands of Satisfied Users</h2>
            <p>Experience the fastest data services with competitive pricing and earn money through our referral program. Sign up today and get connected!</p>
            <div class="btn-group"><a href="#" class="btn" id="show-register-2">Get Started Now</a></div>
        </div>

        <div style="margin-top: 50px; text-align: center; color: var(--gray); font-size: 0.9rem; opacity: 0.8;">Developed by <span style="color: var(--primary); font-weight: 600;">Wisehive Sphere Ltd.</span></div>
        
        <div class="forms-container" id="login-form">
            <div class="close-form"><button class="close-btn" id="close-login">&times;</button></div>
            <div class="form-content">
                <h2 class="form-title">Welcome Back</h2><p class="form-subtitle">Sign in to your account to continue</p>
                <div class="alert alert-error" id="login-error"></div>
                <form id="loginForm" autocomplete="off">
                    <div class="form-group"><label for="login-username">Username</label><div class="input-with-icon"><i class="fas fa-user"></i><input type="text" id="login-username" name="username" placeholder="Enter your username" required></div></div>
                    <div class="form-group"><label for="login-password">Password</label><div class="input-with-icon"><i class="fas fa-lock"></i><input type="password" id="login-password" name="password" placeholder="Enter your password" required><span class="password-toggle" id="login-password-toggle"><i class="fas fa-eye"></i></span></div></div>
                    <div class="forgot-password"><a href="#" id="show-reset-password">Forgot Password?</a></div>
                    <button type="submit" class="btn" style="width:100%">Sign In</button>
                </form>
                <div class="form-footer"><p>Don't have an account? <a href="#" id="switch-to-register">Sign up here</a></p></div>
            </div>
        </div>
        
        <div class="forms-container" id="register-form">
            <div class="close-form"><button class="close-btn" id="close-register">&times;</button></div>
            <div class="form-content">
                <h2 class="form-title">Create Account</h2><p class="form-subtitle">Join Nagarta Data Sub today</p>
                <div class="alert alert-success" id="register-success"></div><div class="alert alert-error" id="register-error"></div>
                <form id="registerForm" autocomplete="off">
                    <div class="form-row">
                        <div class="form-group"><label for="register-first-name">First Name</label><div class="input-with-icon"><i class="fas fa-user"></i><input type="text" id="register-first-name" name="first_name" placeholder="First name" required></div></div>
                        <div class="form-group"><label for="register-last-name">Last Name</label><div class="input-with-icon"><i class="fas fa-user"></i><input type="text" id="register-last-name" name="last_name" placeholder="Last name" required></div></div>
                    </div>
                    <div class="form-group"><label for="register-username">Username</label><div class="input-with-icon"><i class="fas fa-at"></i><input type="text" id="register-username" name="username" placeholder="Choose a username" required></div></div>
                    <div class="form-group"><label for="register-email">Email</label><div class="input-with-icon"><i class="fas fa-envelope"></i><input type="email" id="register-email" name="email" placeholder="Your email address" required></div></div>
                    <div class="form-group"><label for="register-phone">Phone Number</label><div class="input-with-icon"><i class="fas fa-phone"></i><input type="tel" id="register-phone" name="phone" placeholder="Your phone number" required></div></div>
                    <div class="form-group"><label for="register-password">Password</label><div class="input-with-icon"><i class="fas fa-lock"></i><input type="password" id="register-password" name="password" placeholder="Create a password" required><span class="password-toggle" id="register-password-toggle"><i class="fas fa-eye"></i></span></div></div>
                    <div class="referral-section"><h3>Referral Program</h3><p>If you were referred by someone, enter their username below to get your bonus!</p><div class="form-group"><label for="referrer-username">Referrer Username (Optional)</label><div class="input-with-icon"><i class="fas fa-user-friends"></i><input type="text" id="referrer-username" name="referred_by" placeholder="Enter referrer's username"></div></div></div>
                    <button type="submit" class="btn" style="width:100%">Create Account</button>
                </form>
                <div class="form-footer"><p>Already have an account? <a href="#" id="switch-to-login">Sign in here</a></p></div>
            </div>
        </div>
        
        <div class="forms-container" id="reset-password-form">
            <div class="close-form"><button class="close-btn" id="close-reset-password">&times;</button></div>
            <div class="form-content">
                <h2 class="form-title">Reset Password</h2><p class="form-subtitle">Enter your email to reset your password</p>
                <div class="alert alert-success" id="reset-success"></div><div class="alert alert-error" id="reset-error"></div>
                <form id="resetPasswordForm" autocomplete="off">
                    <div class="form-group"><label for="reset-email">Email Address</label><div class="input-with-icon"><i class="fas fa-envelope"></i><input type="email" id="reset-email" name="email" placeholder="Your email address" required></div></div>
                    <button type="submit" class="btn" style="width:100%">Reset Password</button>
                </form>
                <div class="form-footer"><p>Remember your password? <a href="#" id="switch-to-login-from-reset">Sign in here</a></p></div>
            </div>
        </div>
    </div>

    <script>
        const overlay = document.getElementById('overlay');
        const loginForm = document.getElementById('login-form');
        const registerForm = document.getElementById('register-form');
        const resetPasswordForm = document.getElementById('reset-password-form');
        
        function showForm(form) { 
            document.querySelectorAll('.alert').forEach(a => { a.style.display = 'none'; a.textContent = ''; });
            const actualForm = form.querySelector('form');
            if(actualForm) { actualForm.reset(); actualForm.querySelectorAll('input').forEach(i => i.value = ''); }
            overlay.style.display = 'block'; 
            form.style.display = 'block'; 
            document.body.style.overflow = 'hidden'; 
        }

        function hideForms() { overlay.style.display = 'none'; loginForm.style.display = 'none'; registerForm.style.display = 'none'; resetPasswordForm.style.display = 'none'; document.body.style.overflow = 'auto'; }
        document.getElementById('show-login').addEventListener('click', (e) => { e.preventDefault(); showForm(loginForm); });
        document.getElementById('show-register').addEventListener('click', (e) => { e.preventDefault(); showForm(registerForm); });
        document.getElementById('show-register-2').addEventListener('click', (e) => { e.preventDefault(); showForm(registerForm); });
        document.getElementById('show-reset-password').addEventListener('click', (e) => { e.preventDefault(); loginForm.style.display = 'none'; showForm(resetPasswordForm); });
        document.getElementById('close-login').addEventListener('click', hideForms);
        document.getElementById('close-register').addEventListener('click', hideForms);
        document.getElementById('close-reset-password').addEventListener('click', hideForms);
        overlay.addEventListener('click', hideForms);
        document.getElementById('switch-to-register').addEventListener('click', (e) => { e.preventDefault(); loginForm.style.display = 'none'; registerForm.style.display = 'block'; }); 
        document.getElementById('switch-to-login').addEventListener('click', (e) => { e.preventDefault(); registerForm.style.display = 'none'; loginForm.style.display = 'block'; }); 
        document.getElementById('switch-to-login-from-reset').addEventListener('click', (e) => { e.preventDefault(); resetPasswordForm.style.display = 'none'; loginForm.style.display = 'block'; }); 
        document.querySelectorAll('.password-toggle').forEach(toggle => {
            toggle.addEventListener('click', () => {
                const input = toggle.parentElement.querySelector('input');
                const icon = toggle.querySelector('i');
                if (input.type === 'password') { input.type = 'text'; icon.classList.remove('fa-eye'); icon.classList.add('fa-eye-slash'); }
                else { input.type = 'password'; icon.classList.remove('fa-eye-slash'); icon.classList.add('fa-eye'); }
            });
        });

        async function makeApiCall(formData, endpoint = '') {
            try {
                const response = await fetch(endpoint, { method: 'POST', body: formData });
                // Check if response is okay
                if (!response.ok) throw new Error('Network response was not ok');
                
                // Parse text first to check for HTML errors
                const text = await response.text();
                try {
                    return JSON.parse(text);
                } catch(e) {
                    console.error("Invalid JSON from Server:", text); // Debugging info
                    return { success: false, message: "Server Error. Check Console." };
                }
            } catch (error) { 
                console.error('API call failed:', error); 
                return { success: false, message: "Connection Error." };
            }
        }

        document.getElementById('loginForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            formData.append('form_type', 'login');
            try {
                const response = await makeApiCall(formData, window.location.href);
                if (response.success) {
                    showAlert('login-error', 'success', response.message);
                    if (response.user_id) localStorage.setItem('user_id', response.user_id);
                    if (response.username) localStorage.setItem('username', response.username);
                    setTimeout(() => { window.location.href = response.redirect || 'dashboard.php'; }, 1500);
                } else { showAlert('login-error', 'error', response.message); }
            } catch (error) { showAlert('login-error', 'error', 'Network error. Please try again.'); }
        });

        document.getElementById('registerForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            formData.append('form_type', 'register');
            try {
                const response = await makeApiCall(formData, window.location.href);
                if (response.success) {
                    showAlert('register-success', 'success', response.message);
                    document.getElementById('registerForm').reset();
                    if (response.user_id) localStorage.setItem('user_id', response.user_id);
                    if (response.username) localStorage.setItem('username', response.username);
                    if (response.has_referral && response.referral_bonus && response.referral_bonus.success) {
                        setTimeout(() => { showAlert('register-success', 'success', `Referral bonus earned!`); }, 1000);
                    }
                    setTimeout(() => { window.location.href = response.redirect || 'dashboard.php'; }, 3000);
                } else { showAlert('register-error', 'error', response.message); }
            } catch (error) { showAlert('register-error', 'error', 'Network error. Please try again.'); }
        });

        document.getElementById('resetPasswordForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            formData.append('form_type', 'reset_password');
            let btn = e.target.querySelector('button');
            let originalText = btn.innerText;
            btn.innerText = "Sending...";
            btn.disabled = true;
            try {
                const response = await makeApiCall(formData, window.location.href);
                if (response.success) {
                    showAlert('reset-success', 'success', response.message);
                    document.getElementById('resetPasswordForm').reset();
                    setTimeout(() => { hideForms(); }, 3000);
                } else { showAlert('reset-error', 'error', response.message); }
            } catch (error) { showAlert('reset-error', 'error', 'Network error. Please try again.'); }
            finally { btn.innerText = originalText; btn.disabled = false; }
        });

        function showAlert(containerId, type, message) {
            const alertContainer = document.getElementById(containerId);
            alertContainer.textContent = message;
            alertContainer.className = 'alert';
            if (type === 'success') alertContainer.classList.add('alert-success');
            else if (type === 'error') alertContainer.classList.add('alert-error');
            alertContainer.style.display = 'block';
            if (type === 'success') setTimeout(() => { alertContainer.style.display = 'none'; }, 10000);
        }

        ['register-username', 'register-email', 'register-phone'].forEach(id => {
            document.getElementById(id).addEventListener('blur', async function() {
                const val = this.value.trim();
                if (id === 'register-username' && val.length < 5) return;
                if (!val) return;
                const formData = new FormData();
                if (id === 'register-username') { formData.append('check_username', true); formData.append('username', val); }
                else if (id === 'register-email') { formData.append('check_email', true); formData.append('email', val); }
                else { formData.append('check_phone', true); formData.append('phone', val); }
                try {
                    const response = await fetch(window.location.href, { method: 'POST', body: formData });
                    const result = await response.text();
                    if (result === 'exists') showAlert('register-error', 'error', `${id.replace('register-', '').replace('-', ' ')} already exists.`);
                } catch (error) { console.error('Check failed:', error); }
            });
        });
        
        window.onload = function() {
            document.querySelectorAll("form").forEach(function(f) { f.reset(); f.setAttribute("autocomplete", "off"); });
            document.querySelectorAll("input").forEach(function(i) { if(i.type !== 'hidden' && i.type !== 'submit') { i.value = ""; i.setAttribute("autocomplete", "off"); } });
        };

        if (window.history.replaceState) { window.history.replaceState(null, null, window.location.href); }
        
// --- SECRET ADMIN LAUNCHER ---
    let secretCode = "admin"; // The secret word
    let inputSequence = "";

    document.addEventListener('keydown', (e) => {
        // Ignore if user is typing in a form field (Input/Textarea)
        if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;

        // Add the pressed key to the sequence
        inputSequence += e.key.toLowerCase();

        // Check if the typed sequence ends with "admin"
        if (inputSequence.endsWith(secretCode)) {
            // Flash screen to confirm (Visual Feedback)
            document.body.style.transition = "0.2s";
            document.body.style.opacity = "0";
            
            setTimeout(() => {
                window.location.href = "Nag/index.php";
            }, 300);
        }
    });

    </script>
</body>
</html>