<?php
require_once __DIR__ . "/config.inc.php";

$errors = [];
$sent = false;
$email = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        user_check_csrf();
    } catch (Throwable $e) {
        $errors[] = "Invalid CSRF token. Refresh and try again.";
    }

    $email = trim($_POST['email'] ?? '');

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Please enter a valid email address.";
    }

    if (!$errors) {
        try {
            $db = db();

            $stmt = $db->prepare("
                SELECT id, full_name, email
                FROM users
                WHERE email = ?
                LIMIT 1
            ");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $userRow = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            // Always show the same success message to avoid account enumeration.
            if ($userRow) {
                // Remove previous active tokens for this account.
                $stmt = $db->prepare("DELETE FROM password_resets WHERE user_id = ?");
                $uid = (int)$userRow['id'];
                $stmt->bind_param("i", $uid);
                $stmt->execute();
                $stmt->close();

                $rawToken = bin2hex(random_bytes(32));
                $tokenHash = hash('sha256', $rawToken);
                $expiresAt = date('Y-m-d H:i:s', time() + 3600);

                $stmt = $db->prepare("
                    INSERT INTO password_resets (user_id, token_hash, expires_at)
                    VALUES (?, ?, ?)
                ");
                $stmt->bind_param("iss", $uid, $tokenHash, $expiresAt);
                $stmt->execute();
                $stmt->close();

                $resetUrl = rtrim(BASE_URL, '/') . '/reset_password.php?token=' . urlencode($rawToken);

                // Reuse the project's existing PHPMailer helper.
                $mailHelper = dirname(__DIR__) . '/admin/mail_helper.php';
                if (file_exists($mailHelper)) {
                    require_once $mailHelper;
                }

                $html = '
                <html><body style="font-family:Arial,sans-serif;line-height:1.6;color:#1e293b">
                <div style="max-width:600px;margin:auto;padding:24px;border:1px solid #e2e8f0;border-radius:8px">
                    <h2 style="color:#2563eb">Password Reset Request</h2>
                    <p>Dear <strong>' . e($userRow['full_name']) . '</strong>,</p>
                    <p>We received a request to reset your besttutor.lk account password.</p>
                    <p><a href="' . e($resetUrl) . '" style="display:inline-block;padding:12px 18px;background:#2563eb;color:#fff;text-decoration:none;border-radius:6px">Reset Password</a></p>
                    <p>This link will expire in <strong>1 hour</strong> and can be used only once.</p>
                    <p>If you did not request this, you can safely ignore this email.</p>
                </div>
                </body></html>';

                if (function_exists('send_app_email')) {
                    if (!send_app_email($userRow['email'], $userRow['full_name'], 'Password Reset - besttutor.lk', $html)) {
                        error_log("Forgot password email failed for user ID " . $uid);
                    }
                } else {
                    error_log("Forgot password: mail helper unavailable for user ID " . $uid);
                }
            }

            $sent = true;
        } catch (Throwable $e) {
            error_log('Forgot Password Error: ' . $e->getMessage());
            // Do not reveal whether the account exists.
            $sent = true;
        }
    }
}

require_once __DIR__ . "/partials/header.php";
?>
<div class="row justify-content-center">
    <div class="col-md-6 col-lg-5">
        <div class="card shadow-sm">
            <div class="card-body">
                <h4 class="mb-3">Forgot Password</h4>

                <?php if ($sent): ?>
                    <div class="alert alert-success">
                        If an account exists for that email address, a password reset link has been sent.
                        Please check your inbox and spam folder.
                    </div>
                <?php endif; ?>

                <?php if ($errors): ?>
                    <div class="alert alert-danger">
                        <ul class="mb-0">
                            <?php foreach ($errors as $er): ?>
                                <li><?= e($er) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <?php if (!$sent): ?>
                <form method="post" class="row g-3">
                    <input type="hidden" name="csrf_token" value="<?= e(user_csrf()) ?>">

                    <div class="col-12">
                        <label class="form-label">Email Address</label>
                        <input class="form-control" type="email" name="email" value="<?= e($email) ?>" required autocomplete="email">
                    </div>

                    <div class="col-12 d-grid">
                        <button class="btn btn-primary" type="submit">Send Reset Link</button>
                    </div>
                </form>
                <?php endif; ?>

                <div class="text-center mt-3">
                    <a href="login.php">Back to Login</a>
                </div>
            </div>
        </div>
    </div>
</div>
<?php require_once __DIR__ . "/partials/footer.php"; ?>
