<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';

mocker_admin_require_permission('members');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

mocker_require_csrf_post();

require_once __DIR__ . '/db.php';

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
$userId = (int) ($input['userId'] ?? 0);
$password = (string) ($input['password'] ?? '');

if ($userId <= 0) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'user'], JSON_UNESCAPED_UNICODE);
    exit;
}
if (strlen($password) < 8) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'password'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

$st = $pdo->prepare('SELECT id FROM users WHERE id = :id LIMIT 1');
$st->execute([':id' => $userId]);
if (!$st->fetch()) {
    http_response_code(404);
    echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
    exit;
}

$hash = password_hash($password, PASSWORD_DEFAULT);
require_once __DIR__ . '/user_auth_lib.php';
mocker_user_auth_migrate($pdo);

$up = $pdo->prepare('UPDATE users SET password_hash = :h, must_change_password = 0 WHERE id = :id');
$up->execute([':h' => $hash, ':id' => $userId]);

require_once __DIR__ . '/admin_audit_lib.php';
mocker_admin_audit_write($pdo, $userId, 'user_password_reset', [
    'userId' => $userId,
]);

echo json_encode(
    [
        'ok' => true,
        'userId' => $userId,
    ],
    JSON_UNESCAPED_UNICODE
);
