<?php
declare(strict_types=1);

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

header('Content-Type: application/json; charset=utf-8');

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

mocker_require_csrf_post();

$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;
if ($uid <= 0) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth'], JSON_UNESCAPED_UNICODE);
    exit;
}

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
$maxLen = 512;

$clean = static function ($v) use ($maxLen): string {
    $s = trim((string) $v);
    if (strlen($s) > $maxLen) {
        $s = substr($s, 0, $maxLen);
    }
    return $s;
};

$fields = [
    'btc' => $clean($input['btc'] ?? ''),
    'eth' => $clean($input['eth'] ?? ''),
    'usdtErc20' => $clean($input['usdtErc20'] ?? $input['usdt_erc20'] ?? ''),
    'usdtTrc20' => $clean($input['usdtTrc20'] ?? $input['usdt_trc20'] ?? ''),
    'ltc' => $clean($input['ltc'] ?? ''),
    'trx' => $clean($input['trx'] ?? ''),
    'doge' => $clean($input['doge'] ?? ''),
    'other' => $clean($input['other'] ?? ''),
];

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 1 FROM users WHERE id = :id LIMIT 1');
$st->execute([':id' => $uid]);
if (!$st->fetch()) {
    unset($_SESSION['mocker_user_id']);
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth'], JSON_UNESCAPED_UNICODE);
    exit;
}

$now = time();
$ins = $pdo->prepare(
    'INSERT INTO user_crypto_wallets (user_id, btc, eth, usdt_erc20, usdt_trc20, ltc, trx, doge, other, updated_at)
     VALUES (:uid, :btc, :eth, :ue, :ut, :ltc, :trx, :doge, :oth, :t)
     ON CONFLICT(user_id) DO UPDATE SET
       btc = excluded.btc,
       eth = excluded.eth,
       usdt_erc20 = excluded.usdt_erc20,
       usdt_trc20 = excluded.usdt_trc20,
       ltc = excluded.ltc,
       trx = excluded.trx,
       doge = excluded.doge,
       other = excluded.other,
       updated_at = excluded.updated_at'
);
$ins->execute([
    ':uid' => $uid,
    ':btc' => $fields['btc'],
    ':eth' => $fields['eth'],
    ':ue' => $fields['usdtErc20'],
    ':ut' => $fields['usdtTrc20'],
    ':ltc' => $fields['ltc'],
    ':trx' => $fields['trx'],
    ':doge' => $fields['doge'],
    ':oth' => $fields['other'],
    ':t' => $now,
]);

echo json_encode(
    [
        'ok' => true,
        'crypto' => [
            'btc' => $fields['btc'],
            'eth' => $fields['eth'],
            'usdtErc20' => $fields['usdtErc20'],
            'usdtTrc20' => $fields['usdtTrc20'],
            'ltc' => $fields['ltc'],
            'trx' => $fields['trx'],
            'doge' => $fields['doge'],
            'other' => $fields['other'],
            'updatedAt' => $now,
        ],
    ],
    JSON_UNESCAPED_UNICODE
);
