<?php
// Location: taka26.site/public_html/aviator_bridge_api.php

require_once __DIR__ . '/auth_helper.php';
require_once __DIR__ . '/aviator_bridge_config.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

function aviator_api_out($data, $code = 200) {
    http_response_code($code);
    echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

function aviator_b64url_decode_home($data) {
    $data = strtr($data, '-_', '+/');
    $pad = strlen($data) % 4;
    if ($pad) {
        $data .= str_repeat('=', 4 - $pad);
    }
    return base64_decode($data, true);
}

function aviator_verify_token_home($token) {
    $parts = explode('.', $token, 2);

    if (count($parts) !== 2) {
        aviator_api_out(['ok' => false, 'message' => 'Invalid token format.'], 401);
    }

    $body = $parts[0];
    $sig = $parts[1];

    $expected = hash_hmac('sha256', $body, AVIATOR_BRIDGE_SECRET);

    if (!hash_equals($expected, $sig)) {
        aviator_api_out(['ok' => false, 'message' => 'Invalid token signature.'], 401);
    }

    $json = aviator_b64url_decode_home($body);
    $payload = is_string($json) ? json_decode($json, true) : null;

    if (!is_array($payload)) {
        aviator_api_out(['ok' => false, 'message' => 'Invalid token payload.'], 401);
    }

    $exp = isset($payload['exp']) ? (int)$payload['exp'] : 0;

    if ($exp < time()) {
        aviator_api_out(['ok' => false, 'message' => 'Aviator session expired. Open Aviator again from main site.'], 401);
    }

    $uid = isset($payload['uid']) ? (string)$payload['uid'] : '';

    if ($uid === '') {
        aviator_api_out(['ok' => false, 'message' => 'Token user missing.'], 401);
    }

    return $payload;
}

function aviator_public_user_home($user) {
    $status = strtolower((string)($user['status'] ?? 'active'));
    $restricted = in_array($status, ['blocked', 'banned', 'restricted', 'inactive', 'disabled'], true);

    $displayId = (string)($user['phone'] ?? $user['id'] ?? '000000');

    return [
        'id' => $displayId,
        'uid' => $displayId,
        'home_user_id' => (string)($user['id'] ?? ''),
        'balance' => round(max(0, (float)($user['balance'] ?? 0)), 2),
        'status' => $restricted ? 'RESTRICTED' : 'ACTIVE',
        'currency' => 'BDT',
        'source' => 'dkwin',
    ];
}

$serverKey = (string)($_POST['server_key'] ?? $_GET['server_key'] ?? '');

if (!hash_equals(AVIATOR_REMOTE_SERVER_KEY, $serverKey)) {
    aviator_api_out(['ok' => false, 'message' => 'Remote server key rejected.'], 403);
}

$token = trim((string)($_POST['token'] ?? $_GET['token'] ?? ''));
$payload = aviator_verify_token_home($token);

$userId = (string)$payload['uid'];
$action = strtolower(trim((string)($_POST['action'] ?? $_GET['action'] ?? 'status')));
$amount = round(max(0, (float)($_POST['amount'] ?? $_GET['amount'] ?? 0)), 2);

try {
    $user = findUserById($userId);

    if (!$user) {
        aviator_api_out(['ok' => false, 'message' => 'Main site user not found.'], 404);
    }

    if ($action === 'status' || $action === 'check' || $action === 'player_status') {
        aviator_api_out([
            'ok' => true,
            'visitor' => aviator_public_user_home($user)
        ]);
    }

    if ($amount <= 0) {
        aviator_api_out([
            'ok' => false,
            'message' => 'Invalid amount.',
            'visitor' => aviator_public_user_home($user)
        ], 400);
    }

    $publicBefore = aviator_public_user_home($user);

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

    $currentBalance = round(max(0, (float)($user['balance'] ?? 0)), 2);
    $newBalance = $currentBalance;
    $txType = 'aviator';
    $note = 'Aviator balance update.';

    if (in_array($action, ['balance_sub', 'sub'], true)) {
        if ($currentBalance < $amount) {
            aviator_api_out([
                'ok' => false,
                'message' => 'Insufficient balance.',
                'visitor' => $publicBefore
            ], 400);
        }

        $newBalance = $currentBalance - $amount;
        $txType = 'aviator_bet';
        $note = 'Aviator bet placed.';

    } elseif (in_array($action, ['balance_refund', 'refund'], true)) {

        $newBalance = $currentBalance + $amount;
        $txType = 'aviator_refund';
        $note = 'Aviator bet refunded.';

    } elseif (in_array($action, ['balance_add', 'add', 'balance_win', 'win'], true)) {

        $newBalance = $currentBalance + $amount;
        $txType = 'aviator_win';
        $note = 'Aviator win/cashout.';

    } elseif (in_array($action, ['balance_set', 'set'], true)) {

        $newBalance = $amount;
        $txType = 'aviator_balance_set';
        $note = 'Aviator balance set.';

    } else {
        aviator_api_out([
            'ok' => false,
            'message' => 'Unknown action.',
            'visitor' => $publicBefore
        ], 400);
    }

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

    updateUserById((string)$user['id'], [
        'balance' => $newBalance
    ]);

    if (function_exists('addTransaction')) {
        addTransaction((string)$user['id'], $txType, $amount, 'success', $note);
    }

    $fresh = findUserById((string)$user['id']);

    aviator_api_out([
        'ok' => true,
        'visitor' => aviator_public_user_home($fresh ? $fresh : $user)
    ]);

} catch (Throwable $e) {
    aviator_api_out([
        'ok' => false,
        'message' => $e->getMessage()
    ], 500);
}