<?php
$title = $title ?? 'Admin: Reset';
$token = $token ?? '';
ob_start();
?>
<div class="card" style="max-width: 520px; margin: 0 auto;">
    <h2 style="margin-bottom:1rem;">Redefinir senha administrativa</h2>
    <p class="muted" style="margin-bottom:1rem;color:#555;">Informe a nova senha. O link expira em 15 minutos.</p>

    <div class="form-group">
        <label for="newpw">Nova senha</label>
        <input type="password" id="newpw" placeholder="Nova senha" required>
    </div>
    <div class="form-group">
        <label for="confirm">Confirmar senha</label>
        <input type="password" id="confirm" placeholder="Confirme a senha" required>
    </div>
    <div class="form-group">
        <label for="finger">Identificador do dispositivo (se usado)</label>
        <input type="text" id="finger" placeholder="ex.: o mesmo usado na solicitação">
    </div>

    <button class="btn" id="resetBtn">Redefinir senha</button>
    <div id="msg" class="alert" style="display:none;margin-top:1rem;"></div>

    <div style="margin-top:1rem;">
        <a class="btn btn-secondary" href="/admin/login">Voltar ao login</a>
    </div>
</div>

<script>
function getToken() {
    const fromPhp = <?php echo json_encode($token); ?>;
    if (fromPhp) return fromPhp;
    const qs = new URLSearchParams(location.search);
    return qs.get('token') || '';
}

async function verifyToken(token, finger) {
    const res = await fetch('/api/admin/auth/recovery/verify', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, device_fingerprint: finger })
    });
    return res.ok;
}

document.getElementById('resetBtn').addEventListener('click', async () => {
    const newpw = document.getElementById('newpw').value;
    const confirm = document.getElementById('confirm').value;
    const finger = document.getElementById('finger').value.trim();
    const msg = document.getElementById('msg');
    msg.style.display = 'none';
    if (newpw !== confirm) {
        msg.className = 'alert alert-error';
        msg.textContent = 'As senhas não coincidem';
        msg.style.display = 'block';
        return;
    }
    const token = getToken();
    if (!token) {
        msg.className = 'alert alert-error';
        msg.textContent = 'Token ausente';
        msg.style.display = 'block';
        return;
    }
    try {
        const ok = await verifyToken(token, finger);
        if (!ok) {
            msg.className = 'alert alert-error';
            msg.textContent = 'Token inválido ou expirado';
            msg.style.display = 'block';
            return;
        }
        const res = await fetch('/api/admin/auth/recovery/reset', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ token, new_password: newpw, device_fingerprint: finger })
        });
        const data = await res.json().catch(() => ({}));
        if (!res.ok) {
            msg.className = 'alert alert-error';
            msg.textContent = data.error || 'Falha ao redefinir';
        } else {
            msg.className = 'alert alert-success';
            msg.textContent = 'Senha redefinida com sucesso. Redirecionando para login...';
            setTimeout(() => { window.location.href = '/admin/login'; }, 1500);
        }
        msg.style.display = 'block';
    } catch (e) {
        msg.className = 'alert alert-error';
        msg.textContent = 'Erro de rede: ' + e.message;
        msg.style.display = 'block';
    }
});
</script>

<?php
$content = ob_get_clean();
echo $content;
?>