<?php
declare(strict_types=1);

Auth::requireRole('admin');
Csrf::check();

$id = (int) post('id', 0);
$new = (string) post('new_password', '');

if (mb_strlen($new) < MIN_PASSWORD_LENGTH) {
    Flash::add('error', t('password_too_short', ['n' => MIN_PASSWORD_LENGTH]));
    redirect('users', 'index', ['edit' => $id]);
}

$user = Database::one('SELECT id, username FROM users WHERE id = :id', ['id' => $id]);
if ($user === null) {
    Flash::add('warn', 'That user no longer exists.');
    redirect('users', 'index');
}

Database::run('UPDATE users SET password_hash = :h WHERE id = :id', [
    'h'  => password_hash($new, PASSWORD_BCRYPT, ['cost' => BCRYPT_COST]),
    'id' => $id,
]);

// Any bearer tokens issued to this account stop working too.
Database::run('DELETE FROM api_tokens WHERE user_id = :id', ['id' => $id]);

Audit::log('update', 'user', $id, ['password' => 'set by admin']);
Flash::add('ok', t('password_changed'));
redirect('users', 'index', ['edit' => $id]);
