<?php
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';

if (!store_is_open()) { require __DIR__ . '/coming-soon.php'; exit; }

if (current_customer()) redirect('/account');

$errors  = [];
$step    = 1; // 1 = username+key form, 2 = set new password form

if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify()) {
    if ($_POST['step'] ?? '' === '2') {
        // ---- Step 2: set new password (keyfile already verified) ----
        $uid  = (int) ($_SESSION['pw_reset_uid'] ?? 0);
        if (!$uid) redirect('/forgot-password');

        $pass  = $_POST['password']  ?? '';
        $pass2 = $_POST['password2'] ?? '';

        if (strlen($pass) < 8) $errors['password']  = 'Password must be at least 8 characters.';
        if ($pass !== $pass2)  $errors['password2'] = 'Passwords do not match.';

        if (!$errors) {
            $pdo->prepare('UPDATE customers SET password_hash=? WHERE id=?')
                ->execute([password_hash($pass, PASSWORD_BCRYPT, ['cost' => 12]), $uid]);
            unset($_SESSION['pw_reset_uid']);
            flash('Password updated. You can now sign in.');
            redirect('/login');
        }

        $step = 2;

    } else {
        // ---- Step 1: verify username + keyfile ----
        if (rate_limit('forgot_pw', 5, 600)) {
            $errors['username'] = 'Too many attempts. Please wait a few minutes.';
        }

        $username = trim($_POST['username'] ?? '');
        if (!$errors && $username === '') $errors['username'] = 'Username required.';

        $raw_key = '';
        if (!$errors) {
            if (!empty($_FILES['keyfile']['tmp_name'])) {
                if ($_FILES['keyfile']['size'] > 8192) {
                    $errors['keyfile'] = 'Invalid keyfile.';
                } else {
                    $content = @file_get_contents($_FILES['keyfile']['tmp_name']);
                    $raw_key = $content !== false ? parse_login_key($content) : '';
                }
            }
            if ($raw_key === '') {
                $pasted  = trim($_POST['keytext'] ?? '');
                $raw_key = $pasted !== '' ? parse_login_key($pasted) : '';
            }
            if ($raw_key === '') $errors['keyfile'] = 'No valid keyfile or key provided.';
        }

        if (!$errors) {
            $key_hash = hash('sha256', $raw_key);
            $s = $pdo->prepare('SELECT * FROM customers WHERE username=? AND login_key_hash=? AND active=1');
            $s->execute([strtolower($username), $key_hash]);
            $cust = $s->fetch();
            if ($cust) {
                $_SESSION['pw_reset_uid'] = (int) $cust['id'];
                $step = 2;
            } else {
                // Generic error — don't reveal whether username or key was wrong
                $errors['username'] = 'Username and keyfile did not match any account.';
            }
        }
    }
}

// If session already has a verified uid (e.g. page reload) stay on step 2
if (!$errors && isset($_SESSION['pw_reset_uid']) && $_SESSION['pw_reset_uid'] > 0 && $step === 1) {
    $step = 2;
}

$page_title = 'Account recovery';
require __DIR__ . '/includes/header.php';
?>

<div id="page-body">
<main class="content" id="main-content" style="max-width:440px;">

<h2 class="page-heading">Account recovery</h2>

<?php if ($step === 2): ?>

<div class="panel" style="margin-bottom:14px; background:#f0f7f0; border:1px solid #b8d4b8;">
    <div class="panel-body" style="font-size:1.1em; color:#2d5a2d;">
        &#10003; Keyfile verified. Set a new password below.
    </div>
</div>

<form method="post" action="/forgot-password">
  <?= csrf_field() ?>
    <input type="hidden" name="step" value="2">
    <div class="form-row">
        <label>New password</label>
        <input type="password" name="password" autocomplete="new-password" autofocus>
        <?php if (isset($errors['password'])): ?><div class="form-error"><?= esc($errors['password']) ?></div><?php endif; ?>
    </div>
    <div class="form-row">
        <label>Confirm new password</label>
        <input type="password" name="password2" autocomplete="new-password">
        <?php if (isset($errors['password2'])): ?><div class="form-error"><?= esc($errors['password2']) ?></div><?php endif; ?>
    </div>
    <button type="submit" class="btn btn-primary">Set new password</button>
</form>

<?php else: ?>

<p style="margin-bottom:14px; font-size:1.1em; color:#555; line-height:1.6;">
    Enter your username and upload your login keyfile to verify your identity and reset your password.
</p>

<form method="post" action="/forgot-password" enctype="multipart/form-data">
  <?= csrf_field() ?>
    <input type="hidden" name="step" value="1">
    <div class="form-row">
        <label>Username</label>
        <input type="text" name="username" value="<?= esc($_POST['username'] ?? '') ?>" autocomplete="username" autofocus>
        <?php if (isset($errors['username'])): ?><div class="form-error"><?= esc($errors['username']) ?></div><?php endif; ?>
    </div>
    <div class="form-row">
        <label>Upload keyfile</label>
        <input type="file" name="keyfile" accept=".key,.txt,text/plain" style="font-size:12px;">
        <?php if (isset($errors['keyfile'])): ?><div class="form-error"><?= esc($errors['keyfile']) ?></div><?php endif; ?>
    </div>
    <div class="form-row" style="margin-top:4px;">
        <label>Or paste key <span class="muted" style="font-weight:normal;">(64-char hex)</span></label>
        <textarea name="keytext" rows="2" style="width:100%; padding:5px 7px; border:1px solid #bbb; font-size:11px; font-family:monospace; resize:vertical;" placeholder="Paste the NXTGN_LOGIN_KEY= value or bare 64-character key"></textarea>
    </div>
    <button type="submit" class="btn btn-primary">Verify identity</button>
    <span style="margin-left:10px; font-size:1.1em;"><a href="/login">&larr; Sign in</a></span>
</form>

<div class="panel" style="margin-top:20px; background:#f8f8f4;">
    <div class="panel-body" style="font-size:1.1em; line-height:1.7; color:#666;">
        <strong>No keyfile?</strong> If you no longer have your keyfile and have also forgotten your password, your account cannot be recovered. This is by design — the keyfile is your proof of identity.
    </div>
</div>

<?php endif; ?>

</main>
</div>

<?php require __DIR__ . '/includes/footer.php'; ?>
