<?php
require_once 'config.php';
$usernumber = $password = $repassword = '';
$usernumber_err = $password_err = $repassword_err = $reset_err = $reset_success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	if (empty(trim($_POST['usernumber']))) {
		$usernumber_err = 'Please enter your user number.';
	} else {
		$usernumber = trim($_POST['usernumber']);
	}
	if (empty(trim($_POST['password']))) {
		$password_err = 'Please enter a new password.';
	} elseif (strlen(trim($_POST['password'])) < 6) {
		$password_err = 'Password must have at least 6 characters.';
	} else {
		$password = trim($_POST['password']);
	}
	if (empty(trim($_POST['repassword']))) {
		$repassword_err = 'Please confirm your new password.';
	} else {
		$repassword = trim($_POST['repassword']);
		if ($password !== $repassword) {
			$repassword_err = 'Passwords do not match.';
		}
	}
	if (empty($usernumber_err) && empty($password_err) && empty($repassword_err)) {
		$sql = 'SELECT id FROM users WHERE usernumber = ?';
		if ($stmt = mysqli_prepare($link, $sql)) {
			mysqli_stmt_bind_param($stmt, 'i', $usernumber);
			mysqli_stmt_execute($stmt);
			mysqli_stmt_store_result($stmt);
			if (mysqli_stmt_num_rows($stmt) == 1) {
				$sql_update = 'UPDATE users SET password = ? WHERE usernumber = ?';
				if ($stmt_update = mysqli_prepare($link, $sql_update)) {
					$param_password = password_hash($password, PASSWORD_DEFAULT);
					mysqli_stmt_bind_param($stmt_update, 'si', $param_password, $usernumber);
					if (mysqli_stmt_execute($stmt_update)) {
						// 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>
                        Password Reset 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 {
						$reset_err = 'Something went wrong. Please try again.';
					}
					mysqli_stmt_close($stmt_update);
				}
			} else {
				$reset_err = 'Username not found.';
			}
			mysqli_stmt_close($stmt);
		}
	}
}
?>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Reset Password</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
	<div class="wrapper">
		<h2>Reset Password</h2>
		<?php if(!empty($reset_err)) echo '<div class="error">'.$reset_err.'</div>'; ?>
		<?php if(!empty($reset_success)) echo '<div class="success">'.$reset_success.'</div>'; ?>
		<form id="resetForm" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" novalidate>
			<label>User Number</label>
			<input class="styled-input" type="text" name="usernumber" id="usernumber">
			<div id="usernumberErr" class="error" style="display: none;"></div>
			
			<label>New Password</label>
			<input class="styled-input" type="password" name="password" id="password">
			<div id="passwordErr" class="error" style="display: none;"></div>
			
			<label>Re-Password</label>
			<input class="styled-input" type="password" name="repassword" id="repassword">
			<div id="repasswordErr" class="error" style="display: none;"></div>
			
			<input class="cta" type="submit" value="Reset Password">
		</form>
		<p><a href="login.php">Back to Login</a></p>
	</div>

	<script>
	document.getElementById('resetForm').addEventListener('submit', function(e) {
		let valid = true;

		// Clear previous errors
		document.getElementById('usernameErr').textContent = '';
		document.getElementById('passwordErr').textContent = '';
		document.getElementById('repasswordErr').textContent = '';

		// User Number validation
		const usernumber = document.getElementById('usernumber').value.trim();
		if (usernumber === '') {
			document.getElementById('usernumberErr').textContent = 'Please enter your user number.';
			valid = false;
		}

		// Password validation
		const password = document.getElementById('password').value;
		if (password === '') {
			document.getElementById('passwordErr').textContent = 'Please enter a new password.';
			valid = false;
		} else if (password.length < 6) {
			document.getElementById('passwordErr').textContent = 'Password must have at least 6 characters.';
			valid = false;
		}

		// Re-Password validation
		const repassword = document.getElementById('repassword').value;
		if (repassword === '') {
			document.getElementById('repasswordErr').textContent = 'Please confirm your new password.';
			valid = false;
		} else if (password !== repassword) {
			document.getElementById('repasswordErr').textContent = 'Passwords do not match.';
			valid = false;
		}

		if (!valid) {
			e.preventDefault(); // Prevent form submission if validation fails
		}
	});
	</script>
</body>
</html>
