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

$sent = false;
$error = '';
$infoMessage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	$username = trim($_POST['username'] ?? '');

	// Always look up in the `accounts` table only and include appointed_division
	$stmt = $conn->prepare("SELECT id, email, username AS uname, appointed_division FROM accounts WHERE username = ?");
	$stmt->bind_param("s", $username);
	$stmt->execute();
	$res = $stmt->get_result();
	$user = $res->fetch_assoc();
	$stmt->close();

	$token = bin2hex(random_bytes(32));
	$expires = date('Y-m-d H:i:s', time() + 3600);

	// Only generate token and send email if account exists and is assigned to pmed
	if ($user) {
		if (isset($user['appointed_division']) && $user['appointed_division'] === 'pmed') {
		$stmt = $conn->prepare("UPDATE accounts SET reset_token = ?, reset_expires = ? WHERE id = ?");
		$stmt->bind_param("ssi", $token, $expires, $user['id']);
		$stmt->execute();
		$stmt->close();

		if (!empty($user['email'])) {
			@sendPasswordResetEmail($user['email'], $user['uname'], $token, false);
		}
			$infoMessage = 'If the account exists, a reset link has been sent to the registered email.';
		} else {
			// Account exists but is not appointed to pmed
			$infoMessage = 'The account is not Appointed to pmed division.';
		}
	} else {
		// Unknown username - generic message to avoid enumeration
		$infoMessage = 'If the account exists, a reset link has been sent to the registered email.';
	}

	$sent = true; // show message (custom if non-pmed, generic otherwise)
}
?>
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Forgot 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; }
		.info { background-color:#e8f0fe; color:#0b57d0; border:1px solid #cfe1ff; }
		@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>Forgot Password</h1>
		<?php if ($sent): ?>
			<div class="message info"><?php echo htmlspecialchars($infoMessage ?: 'If the account exists, a reset link has been sent to the registered email.'); ?></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 else: ?>
			<form method="post" autocomplete="off">
				<div class="form-group">
					<label for="username">Username</label>
					<input type="text" id="username" name="username" required>
				</div>
				<p style="font-size:0.9rem; color:#555; margin-bottom:1rem;">Enter your username and we'll send a password reset link if an account exists.</p>
				<button type="submit" class="login-button">Send Reset Link</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>


