<?php
session_start();
require_once 'main_db_connect.php';
require_once 'functions.php';

$token = $_GET['token'] ?? '';
$valid = false;
$user = null;

if ($token) {
	// Only check the accounts table for reset token validity and ensure account is assigned to pmed
	$stmt = $conn->prepare("SELECT id, username AS uname, appointed_division FROM accounts WHERE reset_token = ? AND reset_expires > NOW() AND appointed_division = 'pmed'");
	$stmt->bind_param("s", $token);
	$stmt->execute();
	$res = $stmt->get_result();
	$user = $res->fetch_assoc();
	$stmt->close();

	if ($user) $valid = true;
}

$done = false;
$errors = [];

if ($valid && $_SERVER['REQUEST_METHOD'] === 'POST') {
	$new = $_POST['new_password'] ?? '';
	$confirm = $_POST['confirm_password'] ?? '';
	if ($new !== $confirm) $errors[] = 'Passwords do not match.';
	if (strlen($new) < 8) $errors[] = 'Password must be at least 8 characters.';

	if (!$errors) {
		$hash = password_hash($new, PASSWORD_DEFAULT);
		$stmt = $conn->prepare("UPDATE accounts SET password = ?, reset_token = NULL, reset_expires = NULL, last_updated = NOW() WHERE id = ?");
		$stmt->bind_param("si", $hash, $user['id']);
		$ok = $stmt->execute();
		$stmt->close();
		if ($ok) {
			if (function_exists('logAction')) {
				logAction($conn, $user['id'], $user['uname'], 'Reset password via email link');
			}
			$done = true;
		} else {
			$errors[] = 'Failed to update password.';
		}
	}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Reset Password</title>
	<link rel="icon" href="favicon_io/favicon.ico" type="image/x-icon">
	<style>
		/* Copied layout/styles from index.php for consistent look */
		body { font-family: Arial, sans-serif; margin: 0; padding: 0; height: 100vh; overflow: hidden; position: relative; }
		body::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: url('icons/provincial.jpg') no-repeat center center fixed; background-size: cover; opacity: 0.4; z-index: -1; }
		.navbar { background-color:rgb(148, 0, 0); height: 14vh; padding: 0 1rem; display: flex; align-items: center; justify-content: space-between; position: relative; z-index: 1000; }
		.navbar-center { display: flex; align-items: center; gap: 1rem; flex: 1; justify-content: center; }
		.navbar-logo { height: 60px; width: 60px; object-fit: contain; }
		.navbar p { font-family: 'Times New Roman', Times, serif; font-size: calc(1rem + 1vw); color: white; margin: 0; }
		.login-container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 90%; max-width: 400px; background-color: rgba(255,255,255,0.95); border-radius: 15px; padding: 2rem; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.5); }
		.login-container h1 { font-size: 1.8rem; color:rgb(148, 0, 0); margin-bottom: 1.5rem; }
		.form-group { margin-bottom: 1.25rem; text-align: left; }
		.form-group label { display: block; margin-bottom: 0.5rem; color: #333; font-weight: bold; }
		.form-group input[type="text"], .form-group input[type="password"] { width: 100%; padding: 0.75rem; border: 1px solid #ddd; border-radius: 5px; font-size: 1rem; box-sizing: border-box; }
		.form-group input:focus { outline: none; border-color: rgb(148, 0, 0); box-shadow: 0 0 5px rgba(0,53,148,0.3); }
		.login-button { background-color:rgb(148, 0, 0); color: white; border: none; padding: 0.75rem 0rem; border-radius: 5px; cursor: pointer; font-size: 1rem; font-weight: bold; width: 100%; }
		.message { padding: 0.75rem; border-radius: 5px; margin-bottom: 1rem; }
		.success { background-color:#e6ffed; color:#1a7f37; border:1px solid #c8f7d1; }
		.error { background-color:#ffebee; color:#c62828; border:1px solid #ffcdd2; }
		@media (max-width:768px) { .navbar { height: auto; padding:1rem 0.5rem; } .navbar-logo { height:50px; width:50px; } }
	</style>
</head>
<body>
	<div class="navbar">
		<div class="navbar-center">
			<img src="icons/seal_laguna.webp" alt="Logo" class="navbar-logo">
			<p>Provincial Government of Laguna</p>
		</div>
	</div>

	<div class="login-container">
		<h1>Reset Password</h1>
		<?php if (!$token): ?>
			<div class="message error">Invalid or missing token.</div>
			<a href="index.php" class="login-button" style="display:block;text-decoration:none;text-align:center;margin-top:8px;">Return to Login</a>
		<?php elseif (!$valid && !$done): ?>
			<div class="message error">Reset link is invalid or expired.</div>
			<a href="index.php" class="login-button" style="display:block;text-decoration:none;text-align:center;margin-top:8px;">Return to Login</a>
		<?php elseif ($done): ?>
			<div class="message success">Password has been reset. You can now log in.</div>
			<a href="index.php" class="login-button" style="display:block; text-decoration:none; text-align:center;">Go to Login</a>
		<?php else: ?>
			<?php if ($errors): ?>
				<?php foreach ($errors as $e): ?>
					<div class="message error"><?php echo htmlspecialchars($e); ?></div>
				<?php endforeach; ?>
			<?php endif; ?>
			<form method="post" autocomplete="off">
				<div class="form-group">
					<label for="new_password">New Password</label>
					<div class="input-field" style="display:flex;align-items:center;gap:8px;">
						<input required class="input" type="password" name="new_password" id="new_password" style="flex:1;padding:0.75rem;border:1px solid #ddd;border-radius:5px;" />
						<div style="display:flex;flex-direction:column;gap:4px;">
							<label style="font-size:0.85rem;margin:0;line-height:1"><input type="radio" class="pwdToggle" name="show_new_password" data-target="new_password" value="show"> Show</label>
							<label style="font-size:0.85rem;margin:0;line-height:1"><input type="radio" class="pwdToggle" name="show_new_password" data-target="new_password" value="hide" checked> Hide</label>
						</div>
					</div>
				</div>
				<div class="form-group">
					<label for="confirm_password">Confirm New Password</label>
					<div class="input-field" style="display:flex;align-items:center;gap:8px;">
						<input required class="input" type="password" name="confirm_password" id="confirm_password" style="flex:1;padding:0.75rem;border:1px solid #ddd;border-radius:5px;" />
						<div style="display:flex;flex-direction:column;gap:4px;">
							<label style="font-size:0.85rem;margin:0;line-height:1"><input type="radio" class="pwdToggle" name="show_confirm_password" data-target="confirm_password" value="show"> Show</label>
							<label style="font-size:0.85rem;margin:0;line-height:1"><input type="radio" class="pwdToggle" name="show_confirm_password" data-target="confirm_password" value="hide" checked> Hide</label>
						</div>
					</div>
				</div>
				<button type="submit" class="login-button">Set New Password</button>
				<a href="index.php" style="display:block;text-decoration:none;text-align:center;margin-top:8px;color:#b10000;">Return to Login</a>
			</form>
		<?php endif; ?>
	</div>
</body>
</html>
<script>
	(function(){
		var radios = document.querySelectorAll('.pwdToggle');
		radios.forEach(function(r){
			r.addEventListener('change', function(){
				var target = document.getElementById(r.getAttribute('data-target'));
				if (!target) return;
				if (r.value === 'show' && r.checked) target.type = 'text';
				if (r.value === 'hide' && r.checked) target.type = 'password';
			});
		});
	})();
</script>


