<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';
require_once __DIR__ . '/admin_user_meta_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);
$note = isset($input['adminNote']) ? trim((string) $input['adminNote']) : '';
$tags = mocker_admin_tags_normalize_input($input['adminTags'] ?? []);

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

if (strlen($note) > 4000) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'note_length'], 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, admin_note, admin_tags FROM users WHERE id = :id LIMIT 1');
$st->execute([':id' => $userId]);
$prevRow = $st->fetch(PDO::FETCH_ASSOC);
if (!$prevRow) {
    http_response_code(404);
    echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
    exit;
}
$prevNote = isset($prevRow['admin_note']) && $prevRow['admin_note'] !== null ? (string) $prevRow['admin_note'] : '';
$prevTags = mocker_admin_tags_parse(isset($prevRow['admin_tags']) ? (string) $prevRow['admin_tags'] : null);

$tagsJson = json_encode($tags, JSON_UNESCAPED_UNICODE);
if ($tagsJson === false) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'json'], JSON_UNESCAPED_UNICODE);
    exit;
}

$up = $pdo->prepare('UPDATE users SET admin_note = :n, admin_tags = :t WHERE id = :id');
$up->execute([':n' => $note === '' ? null : $note, ':t' => $tagsJson, ':id' => $userId]);

require_once __DIR__ . '/admin_audit_lib.php';
mocker_admin_audit_write($pdo, $userId, 'user_meta', [
    'previousNote' => $prevNote,
    'previousTags' => $prevTags,
    'adminNote' => $note,
    'adminTags' => $tags,
]);

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