<?php
session_start();
require 'user/db.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'user/PHPMailer/src/PHPMailer.php';
require 'user/PHPMailer/src/SMTP.php';
require 'user/PHPMailer/src/Exception.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fullname = trim($_POST['fullname']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    $errors = [];

    // Validate
    if (empty($fullname) || strlen($fullname) < 3) $errors[] = "Full name must be at least 3 characters.";
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email address.";
    if (strlen($password) < 6) $errors[] = "Password must be at least 6 characters.";
    if ($password !== $confirm_password) $errors[] = "Passwords do not match.";

    // Check email exists
    $stmt = $conn->prepare("SELECT id FROM users WHERE email=?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows > 0) $errors[] = "Email is already registered.";
    $stmt->close();

    if (empty($errors)) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $token = bin2hex(random_bytes(50));
        $role = 'user';

        // Generate unique user_id
        $prefix = "USR";
        $randNum = rand(1000, 9999);
        $user_id = $prefix . $randNum;

        // Ensure uniqueness
        $stmt = $conn->prepare("SELECT id FROM users WHERE user_id=?");
        $stmt->bind_param("s", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        while($result->num_rows > 0) {
            $randNum = rand(1000, 9999);
            $user_id = $prefix . $randNum;
            $stmt->bind_param("s", $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
        }
        $stmt->close();

        // Insert new user
        $stmt = $conn->prepare("INSERT INTO users (user_id, fullname, email, password, role, verification_token) VALUES (?,?,?,?,?,?)");
        $stmt->bind_param("ssssss", $user_id, $fullname, $email, $hashed_password, $role, $token);

        if ($stmt->execute()) {
            // Send verification email using PHPMailer
            $mail = new PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host = 'smtp.gmail.com'; // Gmail SMTP
                $mail->SMTPAuth = true;
                $mail->Username = 'twinklegoodluck@gmail.com';
                $mail->Password = 'nnlqxkuftyxnekuv'; // Your App Password
                $mail->SMTPSecure = 'tls';
                $mail->Port = 587;

                $mail->setFrom('twinklegoodluck@gmail.com', 'Activ8Hub');
                $mail->addAddress($email, $fullname);
                $mail->isHTML(true);
                $mail->Subject = 'Verify Your Email';
                $verification_link = "https://activate.ejsub.com/activ8/user/verify.php?token=" . $token;
                $mail->Body = "Hi $fullname,<br><br>Click the link below to verify your email:<br><a href='$verification_link'>$verification_link</a>";

                $mail->send();
                $success = "Registration successful! Your User ID is <strong>$user_id</strong>. Check your email to verify your account.";
            } catch (Exception $e) {
                $error = "Registration successful but email could not be sent: {$mail->ErrorInfo}";
            }
        } else {
            $error = "Something went wrong. Please try again.";
        }
        $stmt->close();
    } else {
        $error = implode("<br>", $errors);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register</title>
<style>
body { font-family: 'Poppins', sans-serif; background: rgb(21,97,179); color:white; display:flex; justify-content:center; align-items:center; min-height:100vh; }
.register-container { background: rgba(255,255,255,0.05); padding: 40px 30px; border-radius: 15px; width:100%; max-width:400px; box-shadow: 0 8px 20px rgba(0,0,0,0.3); }
.register-container h2 { text-align:center; margin-bottom:25px; color: white; }
.register-container form { display:flex; flex-direction:column; gap:20px; }
.register-container input { padding:12px 15px; border:none; border-radius:10px; background: white; color:black; font-size:16px; }
.register-container button { padding:12px; border:none; border-radius:10px; background: white; color: rgb(23,35,58); font-weight:bold; cursor:pointer; }
.register-container button:hover { background:rgb(21,97,179); }
.register-container .login-link { text-align:center; margin-top:10px; font-size:14px; opacity:0.8; }
.register-container .login-link a { color: rgb(245,164,37); text-decoration:none; }
</style>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>

<div class="register-container">
    <h2>Create Account</h2>
    <form method="POST" action="">
        <input type="text" name="fullname" placeholder="Full Name" required>
        <input type="email" name="email" placeholder="Email Address" required>
        <input type="password" name="password" placeholder="Password" required>
        <input type="password" name="confirm_password" placeholder="Confirm Password" required>
        <button type="submit">Register</button>
    </form>
    <p class="login-link">Already have an account? <a href="login.php" style="color:black">Login</a></p>
</div>

<?php if(!empty($success)): ?>
<script>
Swal.fire({
    icon: 'success',
    title: 'Success!',
    html: '<?php echo $success; ?>',
    timer: 5000,
    timerProgressBar: true,
    showConfirmButton: false,
    toast: true,
    position: 'top-right'
});
</script>
<?php endif; ?>

<?php if(!empty($error)): ?>
<script>
Swal.fire({
    icon: 'error',
    title: 'Oops!',
    html: '<?php echo $error; ?>',
    timer: 5000,
    timerProgressBar: true,
    showConfirmButton: false,
    toast: true,
    position: 'top-right'
});
</script>
<?php endif; ?>

</body>
</html>
