<?php  
session_start();  
include "db.php";  

/* ---------- GET REF FROM URL ---------- */
$ref_code = $_GET['ref'] ?? '';
  
/* ---------- LOAD BONUS FROM SETTINGS ---------- */  
$registration_bonus = 0;  
$referral_bonus = 0;  
  
$setQ = $conn->query("  
    SELECT setting_key, setting_value   
    FROM settings   
    WHERE setting_key IN ('registration_bonus','referral_bonus')  
");  
while($s = $setQ->fetch_assoc()){  
    if($s['setting_key']=='registration_bonus'){  
        $registration_bonus = (float)$s['setting_value'];  
    }  
    if($s['setting_key']=='referral_bonus'){  
        $referral_bonus = (float)$s['setting_value'];  
    }  
}  
  
$error = "";  
$success = "";  
$redirect = false;  

/* ---------- USER IP ---------- */
$ip_address = $_SERVER['REMOTE_ADDR'];
  
/* ---------- AUTO REFERRAL CODE ---------- */  
function generateReferralCode($length = 8) {  
    return strtoupper(substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"), 0, $length));  
}  
  
/* ---------- FORM SUBMIT ---------- */  
if ($_SERVER["REQUEST_METHOD"] == "POST") {  
  
    $type   = $_POST['type'];  
    $name   = trim($_POST['name']);  
    $pass   = trim($_POST['password']);  
    $invite = trim($_POST['invite']);  
  
    $email  = $_POST['email'] ?? null;  
    $mobile = $_POST['mobile'] ?? null;  
  
    if ($name == "" || $pass == "") {  
        $error = "সব তথ্য পূরণ করুন";  
    }  
    elseif (strlen($pass) < 6) {  
        $error = "পাসওয়ার্ড কমপক্ষে ৬ অক্ষর";  
    }  
    else {  

        /* ---------- IP CHECK (ONE ACCOUNT PER IP) ---------- */
        $ipCheck = $conn->prepare("SELECT id FROM users WHERE ip_address = ?");
        $ipCheck->bind_param("s", $ip_address);
        $ipCheck->execute();
        if($ipCheck->get_result()->num_rows > 0){
            $error = "এই IP ঠিকানা থেকে ইতিমধ্যে একাউন্ট খোলা হয়েছে";
        } else {
  
            /* ----- CHECK DUPLICATE ----- */  
            if($type == "number"){  
                $check = $conn->prepare("SELECT id FROM users WHERE mobile = ?");  
                $check->bind_param("s", $mobile);  
            }else{  
                $check = $conn->prepare("SELECT id FROM users WHERE email = ?");  
                $check->bind_param("s", $email);  
            }  
            $check->execute();  
            if($check->get_result()->num_rows > 0){  
                $error = "এই তথ্য দিয়ে আগেই একাউন্ট আছে";  
            }else{  
  
                /* ----- PASSWORD HASH ----- */  
                $hash = password_hash($pass, PASSWORD_DEFAULT);  
  
                /* ----- REFERRAL CODE ----- */  
                $my_referral = generateReferralCode();  
  
                /* ----- CHECK INVITE CODE ----- */  
                $referred_by = null;  
                if($invite != ""){  
                    $ref = $conn->prepare("SELECT id FROM users WHERE referral_code = ?");  
                    $ref->bind_param("s", $invite);  
                    $ref->execute();  
                    if($ref->get_result()->num_rows == 1){  
                        $referred_by = $invite;  
                    }  
                }  
  
                /* ----- INSERT USER ----- */  
                $balance = $registration_bonus;  
  
                $stmt = $conn->prepare(  
                    "INSERT INTO users   
                    (name, mobile, email, password, referral_code, referred_by, balance, ip_address)   
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)"  
                );  
  
                $stmt->bind_param(  
                    "ssssssds",  
                    $name,  
                    $mobile,  
                    $email,  
                    $hash,  
                    $my_referral,  
                    $referred_by,  
                    $balance,  
                    $ip_address  
                );  
  
                if($stmt->execute()){  
  
                    /* ----- REFERRAL BONUS ----- */  
                    if($referred_by){  
                        $bonus = $conn->prepare(  
                            "UPDATE users   
                             SET referral_balance = referral_balance + ?   
                             WHERE referral_code = ?"  
                        );  
                        $bonus->bind_param("ds", $referral_bonus, $referred_by);  
                        $bonus->execute();  
                    }  
  
                    $_SESSION['user_id'] = $stmt->insert_id;  
                    $success = "আপনার একাউন্ট সফলভাবে তৈরি হয়েছে";  
                    $redirect = true;  
  
                }else{  
                    $error = "রেজিস্ট্রেশন ব্যর্থ হয়েছে";  
                }  
            }  
        }
    }  
}  
?>  

<!DOCTYPE html>  
<html lang="bn">  
<head>  
<meta charset="UTF-8">  
<meta name="viewport" content="width=device-width, initial-scale=1.0">  
<title>AMD Registration</title>  

<?php if($redirect): ?>  
<meta http-equiv="refresh" content="2;url=dashboard.php">  
<?php endif; ?>  

<style>  
*{box-sizing:border-box;font-family:Arial, Helvetica, sans-serif;}  
body{margin:0;min-height:100vh;background:linear-gradient(135deg,#120021,#2a003d);display:flex;justify-content:center;align-items:center;padding:10px;}  
.container{width:100%;max-width:380px;padding:24px;color:#fff;text-align:center;}  
.logo img{width:200px;margin-bottom:12px;}  
h2{margin:0 0 15px 0;color:#00ffcc;}  
.tabs{display:flex;margin-bottom:20px;gap:6px;}  
.tabs button{flex:1;padding:12px;border:none;border-radius:14px;background:#3b1657;color:#fff;cursor:pointer;font-size:15px;}  
.tabs button.active{background:#00ffcc;color:#000;}  
input{width:100%;padding:14px;margin-bottom:14px;border:none;border-radius:16px;background:#3b1657;color:#fff;font-size:15px;}  
input::placeholder{color:#cfcfcf;}  
button.submit{width:100%;padding:15px;background:#00b33c;border:none;border-radius:18px;color:#fff;font-size:16px;}  
.msg{padding:12px;border-radius:14px;margin-bottom:15px;font-size:14px;}  
.error{background:#b30000}  
.success{background:#006633}  
.login{margin-top:18px;font-size:14px;color:#00ffcc;}  
.login a{color:#00ffcc;text-decoration:none;}  
.hidden{display:none}  
</style>  
</head>  

<body>  
<div class="container">  

<div class="logo">  
<img src="https://i.postimg.cc/Vv89Mk8b/61710-removebg-preview.png">  
</div>  

<h2>নিবন্ধন করুন</h2>  

<?php if($error): ?><div class="msg error"><?= $error ?></div><?php endif; ?>  
<?php if($success): ?><div class="msg success"><?= $success ?></div><?php endif; ?>  

<div class="tabs">  
<button id="btnNumber" class="active" onclick="showNumber()">নাম্বার</button>  
<button id="btnEmail" onclick="showEmail()">ইমেইল</button>  
</div>  

<form method="post">  
<input type="hidden" name="type" id="type" value="number">  
<input type="text" name="name" placeholder="নাম" required>  

<div id="numberBox">  
<input type="text" name="mobile" placeholder="মোবাইল নাম্বার">  
</div>  

<div id="emailBox" class="hidden">  
<input type="email" name="email" placeholder="ইমেইল">  
</div>  

<input type="password" name="password" placeholder="পাসওয়ার্ড" required>  

<input 
    type="text" 
    name="invite" 
    placeholder="আমন্ত্রণ কোড (ঐচ্ছিক)" 
    value="<?= htmlspecialchars($ref_code) ?>" 
    readonly
>  

<button class="submit" type="submit">সাইন আপ</button>  
</form>  

<div class="login">  
ইতিমধ্যে অ্যাকাউন্ট আছে?  
<a href="login.php">লগইন করুন</a>  
</div>  

</div>  

<script>  
function showNumber(){  
document.getElementById("numberBox").classList.remove("hidden");  
document.getElementById("emailBox").classList.add("hidden");  
document.getElementById("btnNumber").classList.add("active");  
document.getElementById("btnEmail").classList.remove("active");  
document.getElementById("type").value = "number";  
}  
function showEmail(){  
document.getElementById("emailBox").classList.remove("hidden");  
document.getElementById("numberBox").classList.add("hidden");  
document.getElementById("btnEmail").classList.add("active");  
document.getElementById("btnNumber").classList.remove("active");  
document.getElementById("type").value = "email";  
}  
</script>  

</body>  
</html>