<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/helpers.php';

$err = '';
$ok  = '';
$email = strtolower(trim($_GET['e'] ?? ''));
$tHex  = trim($_GET['t'] ?? '');

// Render form on GET; process on POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = strtolower(trim($_POST['email'] ?? ''));
    $tHex  = trim($_POST['token'] ?? '');
    $pass1 = $_POST['password'] ?? '';
    $pass2 = $_POST['password2'] ?? '';

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $err = 'Invalid request.';
    } elseif (!preg_match('/^[0-9a-f]{64}$/i', $tHex)) {
        $err = 'Invalid request.';
    } elseif ($pass1 !== $pass2 || strlen($pass1) < 6) {
        $err = 'Passwords must match and be at least 6 characters.';
    } else {
        $st = $pdo->prepare("SELECT id, reset_token_hash, reset_expires FROM users WHERE LOWER(email)=? LIMIT 1");
        $st->execute([$email]);
        $u = $st->fetch();

        if (!$u || empty($u['reset_token_hash']) || empty($u['reset_expires'])) {
            $err = 'Reset token invalid or expired.';
        } else {
            $bin    = hex2bin($tHex);
            $expect = (string)$u['reset_token_hash']; // binary from DB
            $given  = hash('sha256', $bin, true);

            $now = new DateTime('now', new DateTimeZone('Africa/Lagos'));
            $exp = new DateTime($u['reset_expires'], new DateTimeZone('Africa/Lagos'));

            if (!hash_equals($expect, $given) || $now > $exp) {
                $err = 'Reset token invalid or expired.';
            } else {
                $hash = password_hash($pass1, PASSWORD_DEFAULT);
                $upd  = $pdo->prepare("UPDATE users
                    SET password_hash=?, reset_token_hash=NULL, reset_expires=NULL
                    WHERE id=?");
                $upd->execute([$hash, $u['id']]);
                $ok = 'Password updated. You can now log in.';
            }
        }
    }
}

include __DIR__ . '/../includes/header.php';
?>
<div class="card auth-card">
  <h2 class="mb-2 center">Set a new password</h2>

  <?php if ($err): ?><div class="error mb-2"><?= sanitize($err) ?></div><?php endif; ?>
  <?php if ($ok):  ?><div class="success mb-2"><?= sanitize($ok) ?></div><?php endif; ?>

  <?php if (!$ok): ?>
  <form method="post" class="stack">
    <input type="hidden" name="email" value="<?= sanitize($email) ?>">
    <input type="hidden" name="token" value="<?= sanitize($tHex) ?>">

    <div>
      <label>New password</label>
      <input type="password" name="password" minlength="6" required>
    </div>
    <div>
      <label>Confirm password</label>
      <input type="password" name="password2" minlength="6" required>
    </div>
    <button class="btn">Update password</button>
  </form>
  <?php endif; ?>

  <p class="mt-3 center"><a href="<?= url('login.php') ?>">Back to login</a></p>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
