<?php
session_start();
require_once 'config.php';

$username = $usernumber = $password = $repassword = '';
$username_err = $usernumber_err = $password_err = $repassword_err = $register_err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	// Validate username
	if (empty(trim($_POST['username']))) {
		$username_err = 'Please enter a username.';
	} else {
		$sql = 'SELECT id FROM users WHERE username = ?';
		if ($stmt = mysqli_prepare($link, $sql)) {
			mysqli_stmt_bind_param($stmt, 's', $_POST['username']);
			mysqli_stmt_execute($stmt);
			mysqli_stmt_store_result($stmt);
			if (mysqli_stmt_num_rows($stmt) > 0) {
				$username_err = 'This username is already taken.';
			} else {
				$username = trim($_POST['username']);
			}
			mysqli_stmt_close($stmt);
		}
	}

	// Validate usernumber
	if (empty(trim($_POST['usernumber']))) {
		$usernumber_err = 'Please enter a user number.';
	} elseif (!ctype_digit($_POST['usernumber'])) {
		$usernumber_err = 'User number must be an integer.';
	} else {
		$sql = 'SELECT id FROM users WHERE usernumber = ?';
		if ($stmt = mysqli_prepare($link, $sql)) {
			mysqli_stmt_bind_param($stmt, 'i', $_POST['usernumber']);
			mysqli_stmt_execute($stmt);
			mysqli_stmt_store_result($stmt);
			if (mysqli_stmt_num_rows($stmt) > 0) {
				$usernumber_err = 'This user number is already taken.';
			} else {
				$usernumber = trim($_POST['usernumber']);
			}
			mysqli_stmt_close($stmt);
		}
	}

	// Validate password
	if (empty(trim($_POST['password']))) {
		$password_err = 'Please enter a password.';
	} elseif (strlen(trim($_POST['password'])) < 6) {
		$password_err = 'Password must have at least 6 characters.';
	} else {
		$password = trim($_POST['password']);
	}

	// Validate re-password
	if (empty(trim($_POST['repassword']))) {
		$repassword_err = 'Please confirm password.';
	} else {
		$repassword = trim($_POST['repassword']);
		if ($password !== $repassword) {
			$repassword_err = 'Passwords do not match.';
		}
	}

	// Check input errors before inserting in database
	if (empty($username_err) && empty($usernumber_err) && empty($password_err) && empty($repassword_err)) {
        $sql = 'INSERT INTO users (username, usernumber, password) VALUES (?, ?, ?)';
        if ($stmt = mysqli_prepare($link, $sql)) {
            $param_password = password_hash($password, PASSWORD_DEFAULT);
            mysqli_stmt_bind_param($stmt, 'sis', $username, $usernumber, $param_password);
            if (mysqli_stmt_execute($stmt)) {
                // Show stylish popup and redirect after 2 seconds
                echo '
                <div id="success-popup" style="
                    position: fixed;
                    top: 0; left: 0; right: 0; bottom: 0;
                    background: rgba(0,0,0,0.35);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    z-index: 9999;
                ">
                    <div style="
                        background: linear-gradient(120deg, #17a2b8 60%, #ffd600 100%);
                        color: #222;
                        padding: 40px 32px;
                        border-radius: 18px;
                        box-shadow: 0 8px 32px rgba(0,0,0,0.18);
                        text-align: center;
                        font-size: 1.3rem;
                        font-weight: 600;
                        min-width: 320px;
                        animation: popupShow 0.5s;
                    ">
                        <div style="font-size:2.2rem; color:#17a2b8; margin-bottom:10px;">&#10004;</div>
                        Registration Successful!<br>
                        <span style="font-size:1rem; color:#005c97;">You will be redirected to login...</span>
                    </div>
                </div>
                <style>
                @keyframes popupShow {
                    from { transform: scale(0.7); opacity: 0; }
                    to { transform: scale(1); opacity: 1; }
                }
                </style>
                <script>
                    setTimeout(function(){ window.location.href="login.php"; }, 2000);
                </script>
                ';
                // Show popup over the form, do not exit so form remains visible
                return;
            } else {
                $register_err = 'Something went wrong. Please try again later.';
            }
            mysqli_stmt_close($stmt);
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Register</title>
	<link rel="stylesheet" href="style.css">
	<script>
function validateRegisterForm() {
    let username = document.getElementById('username').value.trim();
    let usernumber = document.getElementById('usernumber').value.trim();
    let password = document.getElementById('password').value;
    let repassword = document.getElementById('repassword').value;
    let errors = [];

    // Username validation
    if (username.length < 3) {
        errors.push("Username must be at least 3 characters.");
    }

    // Usernumber validation
    if (!/^\d+$/.test(usernumber)) {
        errors.push("User number must be an integer.");
    }

    // Password validation
    if (password.length < 6) {
        errors.push("Password must have at least 6 characters.");
    }

    // Repassword validation
    if (password !== repassword) {
        errors.push("Passwords do not match.");
    }

    // Show errors or submit
    let errorBox = document.getElementById('js-errors');
    if (errors.length > 0) {
        errorBox.innerHTML = errors.map(e => `<div class="error">${e}</div>`).join('');
        return false;
    }
    errorBox.innerHTML = '';
    return true;
}
</script>
</head>
<body>
	<?php include 'header.php'; ?>
	<div class="wrapper">
		<h2>Register</h2>
		<p>Please fill this form to create an account.</p>
		<?php
		// Display error messages
		?>
		<div id="js-errors">
			<?php
			if (!empty($register_err)) echo '<div class="error">'.$register_err.'</div>';
			if (!empty($username_err)) echo '<div class="error">'.$username_err.'</div>';
			if (!empty($usernumber_err)) echo '<div class="error">'.$usernumber_err.'</div>';
            if (!empty($password_err)) echo '<div class="error">'.$password_err.'</div>';
            if (!empty($repassword_err)) echo '<div class="error">'.$repassword_err.'</div>';
    ?>
</div>
		<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return validateRegisterForm();">
			<label for="username">Username</label>
			<input class="styled-input" type="text" name="username" id="username" required>
			<label for="usernumber">User Number</label>
			<input class="styled-input" type="text" name="usernumber" id="usernumber" required>
			<label for="password">Password</label>
			<input class="styled-input" type="password" name="password" id="password" required>
			<label for="repassword">Re-Password</label>
			<input class="styled-input" type="password" name="repassword" id="repassword" required>
			<button class="cta" type="submit">Register</button>
		</form>
	</div>
	<?php include 'footer.php'; ?>
</body>
</html>
