<?php
/**
 * DK Win <-> Aviator balance bridge
 * This connects Aviator balance with DK Win logged-in user balance.
 */

declare(strict_types=1);

function aviator_dkwin_auth_file(): ?string
{
    /*
     * Robust DKWin auth helper finder.
     * Your project may be uploaded in different ways on InfinityFree:
     *   1) htdocs/auth_helper.php                  (contents of home/ uploaded to root)
     *   2) htdocs/home/auth_helper.php             (this ZIP structure kept as-is)
     *   3) htdocs/dkwin/auth_helper.php            (older DKWin folder structure)
     *   4) htdocs/spribe/aviator inside DKWin root
     * The old bridge mostly checked /dkwin/auth_helper.php only, so this ZIP could not
     * see the logged-in DKWin session and fell back to local Aviator balance.
     */
    $candidates = [];

    if (defined('DKWIN_AUTH_FILE')) {
        $candidates[] = (string) constant('DKWIN_AUTH_FILE');
    }

    $aviatorDir = __DIR__;
    $projectRoot = realpath($aviatorDir . '/../..'); // htdocs when path is htdocs/spribe/aviator
    $parentRoot  = realpath($aviatorDir . '/../../..');

    foreach ([$projectRoot, $parentRoot, $aviatorDir] as $root) {
        if (!$root) continue;
        $root = rtrim((string) $root, '/\\');
        $candidates[] = $root . '/auth_helper.php';
        $candidates[] = $root . '/home/auth_helper.php';
        $candidates[] = $root . '/dkwin/auth_helper.php';
        $candidates[] = $root . '/DKWIN/auth_helper.php';
    }

    // If Aviator is inside DKWin directly: htdocs/dkwin/aviator/
    $candidates[] = $aviatorDir . '/../auth_helper.php';
    $candidates[] = $aviatorDir . '/../dkwin/auth_helper.php';
    $candidates[] = $aviatorDir . '/../../auth_helper.php';
    $candidates[] = $aviatorDir . '/../../home/auth_helper.php';
    $candidates[] = $aviatorDir . '/../../dkwin/auth_helper.php';

    if (!empty($_SERVER['DOCUMENT_ROOT'])) {
        $docRoot = rtrim((string) $_SERVER['DOCUMENT_ROOT'], '/\\');
        $candidates[] = $docRoot . '/auth_helper.php';
        $candidates[] = $docRoot . '/home/auth_helper.php';
        $candidates[] = $docRoot . '/dkwin/auth_helper.php';
        $candidates[] = $docRoot . '/../auth_helper.php';
        $candidates[] = $docRoot . '/../home/auth_helper.php';
        $candidates[] = $docRoot . '/../dkwin/auth_helper.php';
    }

    $seen = [];
    foreach ($candidates as $file) {
        if (!$file) continue;
        $real = realpath($file);
        if (!$real || isset($seen[$real])) continue;
        $seen[$real] = true;
        if (is_file($real)) {
            return $real;
        }
    }

    return null;
}

function aviator_dkwin_load(): bool
{
    static $loaded = null;

    if ($loaded !== null) {
        return $loaded;
    }

    $file = aviator_dkwin_auth_file();

    if (!$file) {
        $loaded = false;
        return false;
    }

    require_once $file;

    $loaded = function_exists('findUserById') && function_exists('updateUserById');
    return $loaded;
}

function aviator_dkwin_current_user(): ?array
{
    if (!aviator_dkwin_load()) {
        return null;
    }

    if (session_status() === PHP_SESSION_NONE) {
        @session_start();
    }

    if (empty($_SESSION['user_id'])) {
        return null;
    }

    $user = findUserById((string) $_SESSION['user_id']);

    return is_array($user) ? $user : null;
}

function aviator_dkwin_status(array $user): string
{
    $status = strtolower((string) ($user['status'] ?? 'active'));

    if (in_array($status, ['blocked', 'banned', 'restricted', 'inactive'], true)) {
        return 'RESTRICTED';
    }

    return 'ACTIVE';
}

function aviator_account_from_dkwin_user(array $user): array
{
    return [
        'source' => 'dkwin',
        'id' => (string) ($user['id'] ?? 'DKWIN'),
        'balance' => round(max(0, (float) ($user['balance'] ?? 0)), 2),
        'status' => aviator_dkwin_status($user),
        'restrict_limit' => 0.00,
        'total_added' => 0.00,
        'total_bet' => 0.00,
        'total_win' => 0.00,
        'user' => $user,
    ];
}

function aviator_account_from_local_visitor(array $visitor): array
{
    return [
        'source' => 'local',
        'id' => (string) ($visitor['id'] ?? '000000'),
        'balance' => round(max(0, (float) ($visitor['balance'] ?? 0)), 2),
        'status' => (string) ($visitor['status'] ?? 'ACTIVE'),
        'restrict_limit' => round(max(0, (float) ($visitor['restrict_limit'] ?? 0)), 2),
        'total_added' => round(max(0, (float) ($visitor['total_added'] ?? 0)), 2),
        'total_bet' => round(max(0, (float) ($visitor['total_bet'] ?? 0)), 2),
        'total_win' => round(max(0, (float) ($visitor['total_win'] ?? 0)), 2),
        'visitor' => $visitor,
    ];
}

function aviator_current_account(array $localVisitor): array
{
    $dkUser = aviator_dkwin_current_user();

    if ($dkUser) {
        return aviator_account_from_dkwin_user($dkUser);
    }

    return aviator_account_from_local_visitor($localVisitor);
}

function aviator_public_account(array $account): array
{
    return [
        'id' => (string) ($account['id'] ?? '000000'),
        'source' => (string) ($account['source'] ?? 'local'),
        'balance' => round((float) ($account['balance'] ?? 0), 2),
        'status' => (string) ($account['status'] ?? 'ACTIVE'),
        'restrict_limit' => round((float) ($account['restrict_limit'] ?? 0), 2),
        'total_added' => round((float) ($account['total_added'] ?? 0), 2),
        'total_bet' => round((float) ($account['total_bet'] ?? 0), 2),
        'total_win' => round((float) ($account['total_win'] ?? 0), 2),
    ];
}

function aviator_dkwin_set_balance(string $userId, float $newBalance, string $txType, float $txAmount, string $note): array
{
    if (!aviator_dkwin_load()) {
        return [
            'ok' => false,
            'message' => 'DK Win auth_helper.php not found. Check dkwin_bridge.php path.'
        ];
    }

    $newBalance = round(max(0, $newBalance), 2);

    $ok = updateUserById($userId, [
        'balance' => $newBalance
    ]);

    if (!$ok) {
        return [
            'ok' => false,
            'message' => 'DK Win user balance update failed.'
        ];
    }

    if (function_exists('addTransaction') && $txType !== '') {
        addTransaction($userId, $txType, round(max(0, $txAmount), 2), 'success', $note);
    }

    $updated = findUserById($userId);

    if (!is_array($updated)) {
        return [
            'ok' => false,
            'message' => 'DK Win user not found after update.'
        ];
    }

    return [
        'ok' => true,
        'account' => aviator_account_from_dkwin_user($updated)
    ];
}

function aviator_dkwin_apply_action(string $action, float $amount): array
{
    $user = aviator_dkwin_current_user();

    if (!$user) {
        return [
            'ok' => false,
            'message' => 'No DK Win logged-in user found.'
        ];
    }

    $userId = (string) ($user['id'] ?? '');
    $current = round(max(0, (float) ($user['balance'] ?? 0)), 2);

    if (aviator_dkwin_status($user) === 'RESTRICTED') {
        return [
            'ok' => false,
            'message' => 'Account is restricted.',
            'account' => aviator_account_from_dkwin_user($user)
        ];
    }

    if ($action === 'balance_sub' || $action === 'sub') {
        if ($amount <= 0) {
            return ['ok' => false, 'message' => 'Invalid amount.'];
        }

        if ($current < $amount) {
            return [
                'ok' => false,
                'message' => 'Insufficient balance.',
                'account' => aviator_account_from_dkwin_user($user)
            ];
        }

        return aviator_dkwin_set_balance(
            $userId,
            $current - $amount,
            'aviator_bet',
            $amount,
            'Aviator bet placed'
        );
    }

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

        return aviator_dkwin_set_balance(
            $userId,
            $current + $amount,
            'aviator_refund',
            $amount,
            'Aviator bet cancelled/refunded'
        );
    }

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

        return aviator_dkwin_set_balance(
            $userId,
            $current + $amount,
            'aviator_win',
            $amount,
            'Aviator win/cashout added'
        );
    }

    if ($action === 'balance_set' || $action === 'set') {
        return aviator_dkwin_set_balance(
            $userId,
            $amount,
            'aviator_balance_set',
            $amount,
            'Aviator balance set'
        );
    }

    return [
        'ok' => false,
        'message' => 'Invalid DK Win balance action.'
    ];
}