<?php
declare(strict_types=1);

/**
 * CLI helper for the first passwords, since the seed leaves password_hash NULL.
 *
 *   php tools/set_password.php --list
 *   php tools/set_password.php moti "a long passphrase"
 */

if (PHP_SAPI !== 'cli') {
    exit("This script runs from the command line only.\n");
}

require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/helpers.php';
require_once dirname(__DIR__) . '/includes/Database.php';

$args = array_slice($argv, 1);

if ($args === [] || $args[0] === '--list') {
    $rows = Database::all(
        'SELECT id, username, full_name, role, is_active,
                (password_hash IS NULL) AS needs_password, last_login_at
           FROM users ORDER BY id'
    );
    printf("%-4s %-12s %-20s %-9s %-7s %s\n", 'ID', 'USERNAME', 'NAME', 'ROLE', 'ACTIVE', 'PASSWORD');
    foreach ($rows as $r) {
        printf("%-4d %-12s %-20s %-9s %-7s %s\n",
            $r['id'], $r['username'], $r['full_name'], $r['role'],
            $r['is_active'] ? 'yes' : 'no',
            $r['needs_password'] ? 'NOT SET' : 'set');
    }
    exit(0);
}

$username = $args[0] ?? null;
$password = $args[1] ?? null;

if ($username === null || $password === null) {
    exit("Usage: php tools/set_password.php <username> <password>\n"
       . "       php tools/set_password.php --list\n");
}

if (mb_strlen($password) < MIN_PASSWORD_LENGTH) {
    exit('Password must be at least ' . MIN_PASSWORD_LENGTH . " characters.\n");
}

$user = Database::one('SELECT id, full_name FROM users WHERE username = :u', ['u' => $username]);
if ($user === null) {
    exit("No user named '{$username}'. Run with --list to see the accounts.\n");
}

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

echo "Password set for {$user['full_name']} ({$username}).\n";
