<?php
session_start();

// ================= GET REFERRAL FROM URL =================
if(isset($_GET['ref'])){
    $_SESSION['ref'] = $_GET['ref'];
}

require("config.php");

/* ================= GET USER IP ================= */
function getUserIP(){

    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }

}

$user_ip = getUserIP();

$error = "";
$success = "";

/* ================= FETCH SETTINGS ================= */
$stmt = $pdo->query("SELECT * FROM settings ORDER BY id DESC LIMIT 1");
$row = $stmt->fetch(PDO::FETCH_ASSOC);

$cname  = $row['domain_name'] ?? 'Website';
$cemail = $row['email2'] ?? '';
$adminEmail = $row['email'] ?? $cemail;
$chost  = $row['contact_email'] ?? '';
$cport  = $row['service1'] ?? 587;
$cpass  = $row['password'] ?? '';
$logo   = $row['LOGO'] ?? '';

/* ================= MAILER ================= */
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/* ================= GENERATE CAPTCHA ================= */
if(!isset($_SESSION['security_answer'])){

    $num1 = rand(1,10);
    $num2 = rand(1,10);

    $operator = rand(0,1) ? '+' : '*';

    if($operator == '+'){
        $_SESSION['security_answer'] = $num1 + $num2;
    }else{
        $_SESSION['security_answer'] = $num1 * $num2;
    }

    $_SESSION['security_question'] = "$num1 $operator $num2 = ?";
}

$security_question = $_SESSION['security_question'];

/* ================= REGISTER ================= */
if(isset($_POST['submit'])){

    $fullname = trim($_POST['name']);
    $username = trim($_POST['username']);
    $email    = trim($_POST['email']);
    $phone    = trim($_POST['phone']);
    $currency = trim($_POST['currency']);

    $password_raw  = $_POST['password'];
    $cpassword_raw = $_POST['password2'];

    $security = trim($_POST['security']);

    $ref = $_POST['ref'] ?? '';

    /* ================= VALIDATE REF ================= */
    if(!empty($ref)){

        $checkRef = $pdo->prepare("SELECT id FROM logins WHERE username=?");
        $checkRef->execute([$ref]);

        if($checkRef->rowCount() == 0){
            $ref = '';
        }
    }

    /* ================= VALIDATION ================= */
    if(
        empty($fullname) ||
        empty($username) ||
        empty($email) ||
        empty($phone) ||
        empty($currency) ||
        empty($password_raw)
    ){

        $error = "All fields are required!";

    }
    elseif($password_raw !== $cpassword_raw){

        $error = "Passwords do not match!";

    }
    elseif($security != $_SESSION['security_answer']){

        $error = "Security answer is incorrect!";

    }
    else{

        /* ================= CHECK EXISTING ================= */
        $stmt = $pdo->prepare("
            SELECT id 
            FROM logins 
            WHERE email=? OR username=?
        ");

        $stmt->execute([$email,$username]);

        if($stmt->rowCount() > 0){

            $error = "Email or Username already exists!";

        }else{

            $password = password_hash($password_raw,PASSWORD_DEFAULT);

            /* ================= INSERT USER ================= */
            $stmt = $pdo->prepare("
                INSERT INTO logins
                (
                    fullname,
                    username,
                    email,
                    phone,
                    currency,
                    password,
                    cpassword,
                    ip,
                    ref,
                    created_at,
                    status,
                    verified,
                    balance
                )

                VALUES
                (
                    ?,?,?,?,?,?,?,?,?,NOW(),?,?,?
                )
            ");

            $stmt->execute([
                $fullname,
                $username,
                $email,
                $phone,
                $currency,
                $password,
                $cpassword_raw,
                $user_ip,
                $ref,
                1,
                0,
                0.00
            ]);

            /* ================= REFERRAL BONUS ================= */
            if(!empty($ref)){

                $pdo->prepare("
                    UPDATE logins 
                    SET reftot = reftot + 1 
                    WHERE username = ?
                ")->execute([$ref]);

            }

            /* ================= SEND EMAIL ================= */
            try{

                $mail = new PHPMailer(true);

                $mail->isSMTP();
                $mail->Host       = $chost;
                $mail->SMTPAuth   = true;
                $mail->Username   = $cemail;
                $mail->Password   = $cpass;
                $mail->SMTPSecure = 'tls';
                $mail->Port       = $cport;

                $mail->setFrom($cemail,$cname);
                $mail->addAddress($email);

                $mail->isHTML(true);

                $mail->Subject = "Welcome to $cname";

                $mail->Body = "

                <div style='font-family:Arial;padding:20px;'>

                    <h2>Welcome to $cname</h2>

                    <p>Your account has been created successfully.</p>

                    <p><b>Email:</b> $email</p>

                    <p><b>Password:</b> $password_raw</p>

                    <p><b>IP Address:</b> $user_ip</p>

                </div>

                ";

                $mail->send();

            }catch(Exception $e){
                // ignore mail errors
            }

            $success = "Account created successfully!";

            unset($_SESSION['security_answer']);
            unset($_SESSION['security_question']);
        }
    }
}

/* ================= FETCH CURRENCIES ================= */
$stmt = $pdo->prepare("
    SELECT * 
    FROM currencies 
    WHERE status = 1 
    ORDER BY id DESC
");

$stmt->execute();

$currencies = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

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

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Create Account</title>

<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>

*{
    margin:0;
    padding:0;
    box-sizing:border-box;
}

body{

    font-family:'Segoe UI',sans-serif;

    background:
    linear-gradient(rgba(5,10,25,0.88),rgba(5,10,25,0.88)),
    url('assets/styles/images/bannerbg.jpg');

    background-size:cover;
    background-position:center;

    display:flex;
    justify-content:center;
    align-items:center;

    min-height:100vh;

    padding:20px;
}

/* ================= MAIN BOX ================= */

.auth-box{

    width:100%;
    max-width:460px;

    background:rgba(255,255,255,0.06);

    backdrop-filter:blur(18px);

    border:1px solid rgba(255,255,255,0.08);

    border-radius:24px;

    padding:35px 30px;

    box-shadow:0 15px 50px rgba(0,0,0,0.45);

    animation:fadeIn 0.7s ease;
}

/* ================= LOGO ================= */

.auth-logo{

    text-align:center;

    margin-bottom:20px;
}

.auth-logo img{

    max-width:180px;

    max-height:90px;

    object-fit:contain;
}

/* ================= HEADER ================= */

.auth-header{

    text-align:center;

    margin-bottom:30px;
}

.auth-header h3{

    color:#fff;

    font-size:30px;

    margin-bottom:8px;
}

.auth-header p{

    color:#bbb;

    font-size:14px;

    line-height:1.6;
}

/* ================= FORM ================= */

.form-group{

    position:relative;

    margin-bottom:18px;
}

.form-group i{

    position:absolute;

    left:15px;

    top:50%;

    transform:translateY(-50%);

    color:#999;

    z-index:2;
}

.form-control{

    width:100%;

    height:54px;

    border:none;

    outline:none;

    border-radius:14px;

    background:rgba(255,255,255,0.08);

    color:#fff;

    padding:0 15px 0 45px;

    font-size:15px;

    transition:0.3s;
}

.form-control:focus{

    border:1px solid #d4af37;

    background:rgba(255,255,255,0.12);
}

select.form-control{
    appearance:none;
}

select option{
    background:#111827;
    color:#fff;
}

/* ================= TERMS ================= */

.terms-box{

    margin-bottom:18px;

    color:#ccc;

    font-size:14px;
}

.terms-box input{
    margin-right:8px;
}

/* ================= BUTTON ================= */

.btn-register{

    width:100%;

    height:55px;

    border:none;

    border-radius:14px;

    background:linear-gradient(135deg,#d4af37,#f6d365);

    color:#111;

    font-weight:700;

    font-size:16px;

    cursor:pointer;

    transition:0.3s;

    margin-top:10px;
}

.btn-register:hover{

    transform:translateY(-2px);

    box-shadow:0 8px 20px rgba(212,175,55,0.35);
}

/* ================= REFRESH ================= */

.refresh-btn{

    width:100%;

    height:48px;

    border:none;

    border-radius:12px;

    background:#1f2937;

    color:#fff;

    cursor:pointer;

    margin-bottom:18px;

    transition:0.3s;
}

.refresh-btn:hover{
    background:#374151;
}

/* ================= LINKS ================= */

.auth-links{

    margin-top:25px;

    display:flex;

    gap:12px;

    flex-wrap:wrap;
}

.auth-links a{

    flex:1;

    text-align:center;

    padding:12px;

    border-radius:12px;

    text-decoration:none;

    font-size:14px;

    font-weight:600;

    transition:0.3s;
}

.login-btn{

    background:#2563eb;

    color:#fff;
}

.login-btn:hover{
    background:#1d4ed8;
}

.home-btn{

    background:#222;

    color:#fff;
}

.home-btn:hover{
    background:#333;
}

/* ================= ALERT ================= */

.alert{

    padding:14px;

    border-radius:12px;

    margin-bottom:18px;

    font-size:14px;
}

.alert-danger{

    background:#7f1d1d;

    color:#fff;
}

.alert-success{

    background:#064e3b;

    color:#fff;
}

/* ================= MOBILE ================= */

@media(max-width:600px){

    .auth-box{

        padding:25px 20px;

        border-radius:18px;
    }

    .auth-header h3{
        font-size:24px;
    }

    .auth-links{
        flex-direction:column;
    }
}

/* ================= ANIMATION ================= */

@keyframes fadeIn{

    from{
        opacity:0;
        transform:translateY(25px);
    }

    to{
        opacity:1;
        transform:translateY(0);
    }
}

</style>

</head>

<body>

<div class="auth-box">

<!-- ================= LOGO ================= -->

<div class="auth-logo">

<?php if(!empty($logo)){ ?>

<img src="user/uploads/<?php echo $logo; ?>" alt="Logo">

<?php }else{ ?>

<h2 style="color:#fff;"><?php echo $cname; ?></h2>

<?php } ?>

</div>

<!-- ================= HEADER ================= -->

<div class="auth-header">

<h3>Create Account</h3>

<p>
Create your investment account securely and start earning online.
</p>

</div>

<!-- ================= ALERT ================= -->

<?php if($error){ ?>

<div class="alert alert-danger">
<?php echo $error; ?>
</div>

<?php } ?>

<?php if($success){ ?>

<div class="alert alert-success">
<?php echo $success; ?>
</div>

<?php } ?>

<!-- ================= FORM ================= -->

<form method="POST">

<div class="form-group">

<i class="fa fa-user"></i>

<input type="text"
name="name"
placeholder="Full Name"
required
class="form-control">

</div>

<div class="form-group">

<i class="fa fa-user-circle"></i>

<input type="text"
name="username"
placeholder="Username"
required
class="form-control">

</div>

<div class="form-group">

<i class="fa fa-envelope"></i>

<input type="email"
name="email"
placeholder="Email Address"
required
class="form-control">

</div>

<div class="form-group">

<i class="fa fa-phone"></i>

<input type="tel"
name="phone"
placeholder="Phone Number"
required
class="form-control">

</div>

<div class="form-group">

<i class="fa fa-coins"></i>

<select name="currency" required class="form-control">

<option value="">Select Currency</option>

<?php foreach($currencies as $cur){ ?>

<option value="<?php echo $cur['cur_shot_name']; ?>">

<?php echo $cur['cur_symbol']." - ".$cur['cur_name']; ?>

</option>

<?php } ?>

</select>

</div>

<div class="form-group">

<i class="fa fa-lock"></i>

<input type="password"
name="password"
placeholder="Password"
required
class="form-control">

</div>

<div class="form-group">

<i class="fa fa-lock"></i>

<input type="password"
name="password2"
placeholder="Confirm Password"
required
class="form-control">

</div>

<!-- TERMS -->

<div class="terms-box">

<label>

<input type="checkbox" required>

I agree to Terms & Conditions

</label>

</div>

<input type="hidden"
name="ref"
value="<?php echo $_SESSION['ref'] ?? ''; ?>">

<!-- CAPTCHA -->

<div class="form-group">

<i class="fa fa-shield"></i>

<input type="text"
id="securityInput"
name="security"
placeholder="Solve: <?php echo $security_question; ?>"
required
class="form-control">

</div>

<button type="button"
id="refreshBtn"
class="refresh-btn">

<i class="fa fa-rotate"></i>

Refresh Question

</button>

<button type="submit"
name="submit"
class="btn-register">

<i class="fa fa-user-plus"></i>

Create Account

</button>

<!-- ================= LINKS ================= -->

<div class="auth-links">

<a href="/signin.php" class="login-btn">

<i class="fa fa-sign-in-alt"></i>

Login

</a>

<a href="/" class="home-btn">

<i class="fa fa-home"></i>

Back Home

</a>

</div>

</form>

</div>

<!-- ================= CAPTCHA REFRESH ================= -->

<script>

document.getElementById("refreshBtn").addEventListener("click",function(){

    fetch("refresh_question.php")

    .then(res => res.text())

    .then(data => {

        document.getElementById("securityInput").placeholder =
        "Solve: " + data;

        document.getElementById("securityInput").value = "";

    });

});

</script>

</body>
</html>