<?php
require_once __DIR__ . '/../app/config.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/csrf.php';

$error=null; $success=null;
$pdo = db();

$token = $_GET['token'] ?? '';

if ($_SERVER['REQUEST_METHOD']==='POST') {
    $token = $_POST['token'] ?? '';
    $pass  = $_POST['password'] ?? '';
    $tokenCsrf = $_POST['csrf'] ?? '';

    if (!csrf_verify($tokenCsrf)) {
        $error = "Sessão expirada. Recarregue a página.";
    } elseif(strlen($pass)<6){
        $error = "Senha muito curta.";
    } else {
        $stmt=$pdo->prepare("select id, reset_expires from auth_users where reset_token=:t limit 1");
        $stmt->execute([':t'=>$token]);
        $user=$stmt->fetch();

        if(!$user){
            $error="Token inválido.";
        } elseif(strtotime($user['reset_expires']) < time()){
            $error="Token expirado.";
        } else {
            $hash=password_hash($pass,PASSWORD_DEFAULT);
            $pdo->prepare("update auth_users set password_hash=:h, reset_token=null, reset_expires=null where id=:id")
                ->execute([':h'=>$hash, ':id'=>$user['id']]);
            $success="Senha redefinida com sucesso! <a href='login.php'>Entrar</a>";
        }
    }
}
?>
<!doctype html>
<html lang="pt-br">
<head>
  <meta charset="utf-8">
  <title>Redefinir senha</title>
    <!-- Favicon -->
  <link rel="icon" type="image/png" href="assets/brand/favicon.png">
  <link rel="apple-touch-icon" href="assets/brand/favicon.png">
  <style>
    body{font-family:sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#0f172a;color:#e2e8f0}
    .card{max-width:380px;background:#111827;padding:24px;border-radius:14px}
    input{width:100%;padding:10px;border-radius:8px;border:1px solid #374151;background:#0b1220;color:#fff}
    .btn{margin-top:12px;width:100%;padding:10px;border-radius:8px;background:#2563eb;color:#fff;font-weight:600;border:0;cursor:pointer}
    .msg{margin:10px 0;padding:8px;border-radius:8px;font-size:.9rem}
    .error{background:#7f1d1d;color:#fecaca}
    .success{background:#064e3b;color:#a7f3d0}
  </style>
</head>
<body>
  <div class="card">
    <h2>Redefinir senha</h2>
    <?php if($error): ?><div class="msg error"><?= $error ?></div><?php endif; ?>
    <?php if($success): ?><div class="msg success"><?= $success ?></div><?php endif; ?>

    <?php if(!$success): ?>
    <form method="post">
      <input type="hidden" name="csrf" value="<?= htmlspecialchars(csrf_token()) ?>">
      <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">
      <input type="password" name="password" placeholder="Nova senha" required>
      <button class="btn" type="submit">Salvar nova senha</button>
    </form>
    <?php endif; ?>
  </div>
</body>
</html>
