<?php
declare(strict_types=1);

$user = Auth::requireLogin();
Csrf::check();

$current = (string) post('current_password', '');
$new     = (string) post('new_password', '');

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

$hash = (string) Database::scalar('SELECT password_hash FROM users WHERE id = :id', ['id' => $user['id']]);

if ($hash === '' || !password_verify($current, $hash)) {
    Flash::add('error', t('login_failed'));
    redirect('auth', 'account');
}

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

Audit::log('update', 'user', (int) $user['id'], ['password' => 'changed']);
Flash::add('ok', t('password_changed'));
redirect('auth', 'account');
