<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/mailer.php';
$pageTitle = "Forgot Password";
$error = ""; $success = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email']);
    $stmt = $pdo->prepare("SELECT id, full_name FROM employees WHERE email = ?");
    $stmt->execute([$email]);
    $emp = $stmt->fetch();

    // Always show the same success message, whether or not the email exists
    // (prevents attackers from checking which emails are registered)
    $success = "If an account exists with that email, a password reset link has been sent.";

    if ($emp) {
        $token = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
        $upd = $pdo->prepare("UPDATE employees SET reset_token = ?, reset_expires = ? WHERE id = ?");
        $upd->execute([$token, $expires, $emp['id']]);

        $resetLink = "https://" . $_SERVER['HTTP_HOST'] . BASE_URL . "/employee/reset_password.php?token=" . $token;
        $body = "
            <h2 style='color:#16232E; margin-top:0;'>Reset Your Password</h2>
            <p>Hi " . e($emp['full_name']) . ",</p>
            <p>We received a request to reset your The Umbergaon Jobs password. Click the button below to set a new one. This link expires in 1 hour.</p>
            <p><a href='" . $resetLink . "' style='background:#F2B705; color:#16232E; padding:10px 20px; border-radius:4px; text-decoration:none; font-weight:bold;'>Reset Password</a></p>
            <p style='font-size:13px; color:#5B6570;'>If you didn't request this, you can safely ignore this email.</p>";
        sendSiteEmail($email, $emp['full_name'], "Reset your The Umbergaon Jobs password", $body);
    }
}

require_once __DIR__ . '/../includes/header.php';
?>
<section>
    <div class="container">
        <div class="form-wrap">
            <h2 style="text-align:center;">Forgot Password</h2>
            <p style="text-align:center; color:var(--ink-soft); margin-bottom:20px;">Enter your email and we'll send you a reset link.</p>
            <?php if ($error): ?><div class="error-box"><?php echo e($error); ?></div><?php endif; ?>
            <?php if ($success): ?><div class="success-box"><?php echo e($success); ?></div><?php endif; ?>
            <?php if (!$success): ?>
            <form method="post">
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" required>
                </div>
                <button type="submit" class="btn btn-primary btn-block">Send Reset Link</button>
            </form>
            <?php endif; ?>
            <p class="form-note"><a href="login.php" style="color:var(--navy); font-weight:600;">Back to Login</a></p>
        </div>
    </div>
</section>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
