<?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);
$username = trim((string) ($input['username'] ?? ''));
$email = trim((string) ($input['email'] ?? ''));

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

if (strlen($username) < 2 || strlen($username) > 64) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'username'], JSON_UNESCAPED_UNICODE);
    exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'email'], 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, username, email FROM users WHERE id = :id LIMIT 1');
$st->execute([':id' => $userId]);
$prev = $st->fetch(PDO::FETCH_ASSOC);
if (!$prev) {
    http_response_code(404);
    echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
    exit;
}
$oldUsername = (string) ($prev['username'] ?? '');
$oldEmail = (string) ($prev['email'] ?? '');

$stU = $pdo->prepare('SELECT id FROM users WHERE LOWER(username) = LOWER(:u) AND id != :id LIMIT 1');
$stU->execute([':u' => $username, ':id' => $userId]);
if ($stU->fetch()) {
    http_response_code(409);
    echo json_encode(['ok' => false, 'error' => 'username_taken'], JSON_UNESCAPED_UNICODE);
    exit;
}

$stE = $pdo->prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(:e) AND id != :id LIMIT 1');
$stE->execute([':e' => $email, ':id' => $userId]);
if ($stE->fetch()) {
    http_response_code(409);
    echo json_encode(['ok' => false, 'error' => 'email_taken'], JSON_UNESCAPED_UNICODE);
    exit;
}

$up = $pdo->prepare('UPDATE users SET username = :u, email = :e WHERE id = :id');
$up->execute([':u' => $username, ':e' => $email, ':id' => $userId]);

require_once __DIR__ . '/admin_audit_lib.php';
mocker_admin_audit_write($pdo, $userId, 'user_profile', [
    'previousUsername' => $oldUsername,
    'previousEmail' => $oldEmail,
    'username' => $username,
    'email' => $email,
]);

header('Content-Type: application/json; charset=utf-8');
echo json_encode(
    [
        'ok' => true,
        'userId' => $userId,
        'username' => $username,
        'email' => $email,
    ],
    JSON_UNESCAPED_UNICODE
);
