<?php
declare(strict_types=1);

if (!defined('DKWIN_AUTH_FILE')) { define('DKWIN_AUTH_FILE', (string)$_SERVER['DOCUMENT_ROOT'] . '/home/auth_helper.php'); }

require_once __DIR__ . '/core.php';
require_once __DIR__ . '/dkwin_bridge.php';

$ip = aviator_client_ip();
$localVisitor = aviator_ensure_visitor_by_ip($ip);
$account = aviator_current_account($localVisitor);
$action = (string) ($_POST['action'] ?? $_GET['action'] ?? 'status');

function aviator_api_send_account(array $account): void
{
    $public = aviator_public_account($account);

    aviator_json_response([
        'ok' => true,
        'status' => $public['status'],
        'balance' => $public['balance'],
        'id' => $public['id'],
        'source' => $public['source'],
        'visitor' => $public,
    ]);
}

if ($action === 'status' || $action === 'check') {
    aviator_api_send_account($account);
}

$amount = aviator_amount($_POST['amount'] ?? $_GET['amount'] ?? 0);

/*
|--------------------------------------------------------------------------
| DK Win connected balance
|--------------------------------------------------------------------------
| If user is logged in from DK Win, Aviator will use DK Win users.json balance.
*/
if (($account['source'] ?? 'local') === 'dkwin') {
    $result = aviator_dkwin_apply_action($action, $amount);

    if (!($result['ok'] ?? false)) {
        $payload = [
            'ok' => false,
            'message' => $result['message'] ?? 'Balance update failed.'
        ];

        if (isset($result['account']) && is_array($result['account'])) {
            $payload['visitor'] = aviator_public_account($result['account']);
            $payload['balance'] = $payload['visitor']['balance'];
            $payload['status'] = $payload['visitor']['status'];
            $payload['id'] = $payload['visitor']['id'];
            $payload['source'] = $payload['visitor']['source'];
        }

        aviator_json_response($payload, 400);
    }

    aviator_api_send_account($result['account']);
}

/*
|--------------------------------------------------------------------------
| Old Aviator local balance fallback
|--------------------------------------------------------------------------
| If user opens Aviator directly without DK Win login,
| old visitors.json balance system will still work.
*/
if ($action === 'balance_sub' || $action === 'sub') {
    if ($amount <= 0) {
        aviator_json_response(['ok' => false, 'message' => 'Invalid amount.'], 400);
    }

    if (($localVisitor['status'] ?? 'ACTIVE') === 'RESTRICTED') {
        aviator_json_response([
            'ok' => false,
            'message' => 'Account is restricted.',
            'visitor' => aviator_public_account(aviator_account_from_local_visitor($localVisitor))
        ], 403);
    }

    if ((float) $localVisitor['balance'] < $amount) {
        aviator_json_response([
            'ok' => false,
            'message' => 'Insufficient balance.',
            'visitor' => aviator_public_account(aviator_account_from_local_visitor($localVisitor))
        ], 400);
    }

    $updated = aviator_update_visitor_by_id((string) $localVisitor['id'], function (&$v) use ($amount): void {
        $v['balance'] = round((float) $v['balance'] - $amount, 2);
        $v['total_bet'] = round((float) ($v['total_bet'] ?? 0) + $amount, 2);
    });

    if (!($updated['ok'] ?? false)) {
        aviator_json_response([
            'ok' => false,
            'message' => $updated['message'] ?? 'Balance update failed.'
        ], 400);
    }

    aviator_api_send_account(aviator_account_from_local_visitor($updated['visitor']));
}

if ($action === 'balance_refund' || $action === 'refund') {
    if ($amount <= 0) {
        aviator_json_response(['ok' => false, 'message' => 'Invalid amount.'], 400);
    }

    $updated = aviator_update_visitor_by_id((string) $localVisitor['id'], function (&$v) use ($amount): void {
        $v['balance'] = round((float) $v['balance'] + $amount, 2);
    });

    if (!($updated['ok'] ?? false)) {
        aviator_json_response([
            'ok' => false,
            'message' => $updated['message'] ?? 'Balance update failed.'
        ], 400);
    }

    aviator_api_send_account(aviator_account_from_local_visitor($updated['visitor']));
}

if ($action === 'balance_add' || $action === 'add' || $action === 'balance_win' || $action === 'win') {
    if ($amount <= 0) {
        aviator_json_response(['ok' => false, 'message' => 'Invalid amount.'], 400);
    }

    $updated = aviator_update_visitor_by_id((string) $localVisitor['id'], function (&$v) use ($amount): void {
        $v['balance'] = round((float) $v['balance'] + $amount, 2);
        $v['total_win'] = round((float) ($v['total_win'] ?? 0) + $amount, 2);
    });

    if (!($updated['ok'] ?? false)) {
        aviator_json_response([
            'ok' => false,
            'message' => $updated['message'] ?? 'Balance update failed.'
        ], 400);
    }

    aviator_api_send_account(aviator_account_from_local_visitor($updated['visitor']));
}

if ($action === 'balance_set' || $action === 'set') {
    $updated = aviator_update_visitor_by_id((string) $localVisitor['id'], function (&$v) use ($amount): void {
        $v['balance'] = $amount;
    });

    if (!($updated['ok'] ?? false)) {
        aviator_json_response([
            'ok' => false,
            'message' => $updated['message'] ?? 'Balance update failed.'
        ], 400);
    }

    aviator_api_send_account(aviator_account_from_local_visitor($updated['visitor']));
}

aviator_json_response(['ok' => false, 'message' => 'Invalid action.'], 400);