<?php
session_start();

require_once "includes/db.php";
require_once "includes/functions.php";

$message = "";

if(isset($_POST['register']))
{
    $full_name = sanitize($_POST['full_name']);
    $email = sanitize($_POST['email']);
    $phone = sanitize($_POST['phone']);
    $pin = sanitize($_POST['pin']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $invitation_code = sanitize($_POST['invitation_code']);

    if(empty($full_name) || empty($email) || empty($phone) || empty($pin) || empty($password) || empty($confirm_password) || empty($invitation_code))
    {
        $message = "<div class='error'>All fields are required.</div>";
    }

    elseif($password != $confirm_password)
    {
        $message = "<div class='error'>Passwords do not match.</div>";
    }

    else
    {  
        $checkUsers = $pdo->query("SELECT COUNT(*) FROM users");
$totalUsers = $checkUsers->fetchColumn(); 

        // Check Invitation Code
        if($totalUsers == 0)
{
    // First user can register without invitation code
}
else
{
    $checkReferral = $pdo->prepare("SELECT id FROM users WHERE referral_code=?");
    $checkReferral->execute([$invitation_code]);

    if($checkReferral->rowCount() < 1)
    {
        $message = "<div class='error'>Invalid Invitation Code.</div>";
    }
}
        {
            // Check Email
            $checkEmail = $pdo->prepare("SELECT id FROM users WHERE email=?");
            $checkEmail->execute([$email]);

            if($checkEmail->rowCount() > 0)
            {
                $message = "<div class='error'>Email already exists.</div>";
            }
            else
            {
                // Check Phone
                $checkPhone = $pdo->prepare("SELECT id FROM users WHERE phone=?");
                $checkPhone->execute([$phone]);

                if($checkPhone->rowCount() > 0)
                {
                    $message = "<div class='error'>Phone number already exists.</div>";
                }
                else
                {
                    $referral_code = generateReferralCode($pdo);

                    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                    $hashedPin = password_hash($pin, PASSWORD_DEFAULT);

                    $insert = $pdo->prepare("
                        INSERT INTO users(
                            referral_code,
                            referred_by,
                            full_name,
                            email,
                            phone,
                            password,
                            transaction_pin,
                            level
                        )
                        VALUES(?,?,?,?,?,?,?,?)
                    ");

                    $insert->execute([
                        $referral_code,
                        $invitation_code,
                        $full_name,
                        $email,
                        $phone,
                        $hashedPassword,
                        $hashedPin,
                        'Intern'
                    ]);

                    $message = "<div class='success'>
                    Registration Successful.
                    <br><br>
                    <a href='login.php'>Login Now</a>
                    </div>";
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">

<title>Sub Partner Registration</title>

<style>

*{
margin:0;
padding:0;
box-sizing:border-box;
font-family:Arial,sans-serif;
}

body{
background:#f5f7ff;
display:flex;
justify-content:center;
align-items:center;
min-height:100vh;
padding:20px;
}

.container{
width:100%;
max-width:500px;
background:#fff;
border-radius:15px;
padding:30px;
box-shadow:0 5px 20px rgba(0,0,0,.1);
}

.logo{
text-align:center;
margin-bottom:20px;
}

.logo h1{
color:royalblue;
font-size:32px;
}

.logo p{
color:#666;
font-size:14px;
}

input{
width:100%;
padding:14px;
margin-top:12px;
border:1px solid #ddd;
border-radius:8px;
outline:none;
}

.password-box{
position:relative;
}

.password-box span{
position:absolute;
right:15px;
top:27px;
cursor:pointer;
font-size:13px;
color:royalblue;
font-weight:bold;
}

.btn{
width:100%;
padding:15px;
background:royalblue;
color:white;
border:none;
border-radius:8px;
margin-top:15px;
cursor:pointer;
font-size:16px;
}

.btn:hover{
opacity:.9;
}

.error{
background:#ffe5e5;
padding:12px;
border-radius:8px;
margin-bottom:15px;
color:red;
}

.success{
background:#e8fff1;
padding:12px;
border-radius:8px;
margin-bottom:15px;
color:green;
}

.success a{
text-decoration:none;
font-weight:bold;
}

.login-link{
text-align:center;
margin-top:15px;
}

.login-link a{
text-decoration:none;
color:royalblue;
font-weight:bold;
}

</style>
</head>
<body>

<div class="container">

<div class="logo">
<h1>Sub Partner</h1>
<p>Partnership & Referral Platform</p>
</div>

<?php echo $message; ?>

<form method="POST">

<input type="text" name="full_name" placeholder="Full Name" required>

<input type="email" name="email" placeholder="Email Address" required>

<input type="text" name="phone" placeholder="Phone Number" required>

<input type="password" name="pin" placeholder="Transaction PIN" required>

<div class="password-box">
<input type="password" id="password" name="password" placeholder="Password" required>
<span onclick="togglePassword('password')">Show</span>
</div>

<div class="password-box">
<input type="password" id="confirm_password" name="confirm_password" placeholder="Confirm Password" required>
<span onclick="togglePassword('confirm_password')">Show</span>
</div>

<input type="text" name="invitation_code" placeholder="Invitation Code" required>

<button type="submit" name="register" class="btn">
Create Account
</button>

</form>

<div class="login-link">
Already have an account?
<a href="login.php">Login</a>
</div>

</div>

<script>

function togglePassword(id)
{
    let input = document.getElementById(id);

    if(input.type === "password")
    {
        input.type = "text";
    }
    else
    {
        input.type = "password";
    }
}

</script>

</body>
</html>