<?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) ?: [];
$entries = $input['entries'] ?? null;
if (!is_array($entries)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'entries'], 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;
}

$now = time();

try {
    $pdo->beginTransaction();
    $del = $pdo->prepare('DELETE FROM user_sponsor_accounts WHERE user_id = :uid');
    $del->execute([':uid' => $uid]);

    $ins = $pdo->prepare(
        'INSERT INTO user_sponsor_accounts (user_id, sponsor_id, sponsor_title, account_value, updated_at)
         VALUES (:uid, :sid, :st, :val, :t)'
    );

    foreach ($entries as $row) {
        if (!is_array($row)) continue;
        $sid = trim((string) ($row['sponsorId'] ?? ''));
        $st = trim((string) ($row['sponsorTitle'] ?? ''));
        $val = trim((string) ($row['accountValue'] ?? ''));
        if ($sid === '') continue;
        if ($val === '') continue;
        if (mb_strlen($val) > 200) {
            $val = mb_substr($val, 0, 200);
        }
        $ins->execute([
            ':uid' => $uid,
            ':sid' => $sid,
            ':st' => $st !== '' ? $st : null,
            ':val' => $val,
            ':t' => $now,
        ]);
    }
    $pdo->commit();
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'server'], JSON_UNESCAPED_UNICODE);
    exit;
}

$stOut = $pdo->prepare(
    'SELECT sponsor_id, sponsor_title, account_value, updated_at
     FROM user_sponsor_accounts
     WHERE user_id = :uid
     ORDER BY updated_at DESC, sponsor_id ASC'
);
$stOut->execute([':uid' => $uid]);
$out = [];
foreach ($stOut->fetchAll() as $r) {
    $out[] = [
        'sponsorId' => (string) $r['sponsor_id'],
        'sponsorTitle' => $r['sponsor_title'] !== null ? (string) $r['sponsor_title'] : '',
        'accountValue' => $r['account_value'] !== null ? (string) $r['account_value'] : '',
        'updatedAt' => $r['updated_at'] !== null ? (int) $r['updated_at'] : null,
    ];
}

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

