<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\Database;
use App\Core\Security;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) {
        set_flash('error', 'Invalid security token. Refresh the page and try again.');
        redirect('public/forgot-password.php');
    }
    $email = strtolower(trim((string)($_POST['email'] ?? '')));
    $rateKey = 'forgot:' . Security::clientIp();
    if (Security::rateLimit($rateKey, 5, 3600) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $user = Database::safeFetchOne('SELECT id,name,email FROM users WHERE LOWER(email)=? AND status<>"deleted" LIMIT 1', [$email]);
        if ($user && Database::tableExists('password_reset_tokens')) {
            $token = Security::randomToken();
            Database::safeExecute('DELETE FROM password_reset_tokens WHERE user_id=? OR expires_at<NOW()', [$user['id']]);
            Database::execute(
                'INSERT INTO password_reset_tokens (user_id,email,token_hash,expires_at,created_at) VALUES (?,?,?,?,NOW())',
                [$user['id'], $email, hash('sha256', $token), date('Y-m-d H:i:s', time() + 3600)]
            );
            $link = url('public/reset-password.php?token=' . urlencode($token) . '&email=' . urlencode($email));
            $headers = [];
            if (MAIL_FROM_ADDRESS !== '' && filter_var(MAIL_FROM_ADDRESS, FILTER_VALIDATE_EMAIL)) {
                $headers[] = 'From: ' . str_replace(["\r", "\n"], '', MAIL_FROM_NAME) . ' <' . MAIL_FROM_ADDRESS . '>';
            }
            $headers[] = 'Content-Type: text/plain; charset=UTF-8';
            $sent = mail(
                $email,
                APP_NAME . ' password reset',
                "Hello {$user['name']},\n\nReset your password using this link (valid for 1 hour):\n{$link}\n\nIf you did not request this, ignore this message.",
                implode("\r\n", $headers)
            );
            Security::logActivity((int)$user['id'], 'password_reset_requested', ['mail_sent' => $sent]);
            if (APP_ENV !== 'production') $_SESSION['debug_reset_link'] = $link;
        }
    }
    set_flash('success', 'If the email exists, a password-reset link has been generated and sent.');
    redirect('public/forgot-password.php');
}
$pageTitle = 'Forgot Password | ' . BRAND_NAME;
include ROOT_PATH . '/app/Layouts/frontend_header.php';
?>
<section class="container py-5"><div class="row justify-content-center"><div class="col-lg-5"><div class="card border-0 shadow-sm"><div class="card-body p-4"><h3>Reset your password</h3><p class="text-muted">Enter the email used for your account.</p><?php if($m=flash('success')): ?><div class="alert alert-success"><?= e($m) ?></div><?php endif; ?><?php if($m=flash('error')): ?><div class="alert alert-danger"><?= e($m) ?></div><?php endif; ?><?php if(APP_ENV !== 'production' && !empty($_SESSION['debug_reset_link'])): ?><div class="alert alert-info small"><a href="<?= e($_SESSION['debug_reset_link']) ?>">Development reset link</a></div><?php unset($_SESSION['debug_reset_link']); endif; ?><form method="post"><?= csrf_field() ?><input class="form-control mb-3" type="email" name="email" required autocomplete="email"><button class="btn btn-primary w-100">Send reset link</button></form></div></div></div></div></section>
<?php include ROOT_PATH . '/app/Layouts/frontend_footer.php'; ?>
