<?php
ob_start();
session_start();
include('config/koneksi.php');
include('config/class_softgaming.php');

// Fungsi Logging Sederhana
function write_bal_log($message) {
    $log_file = 'api_balance.log';
    $current_time = date('Y-m-d H:i:s');
    file_put_contents($log_file, "[$current_time] $message" . PHP_EOL, FILE_APPEND);
}

if (!isset($_SESSION['user'])) {
    echo "0,00";
    exit();
}

$userQuery = "SELECT cuid, username FROM `tb_user` WHERE username = ?";
$userStmt = $conn->prepare($userQuery);
$userStmt->bind_param("s", $_SESSION['user']);
$userStmt->execute();
$u = $userStmt->get_result()->fetch_assoc();

if (!$u) {
    echo "0,00";
    exit();
}

$users = $u['username'];
$id_user = $u['cuid'];

// 1. Panggil API NexusGGR (Kebenaran Mutlak)
$WL = new fiver();
$apiBalance = $WL->userbalance($users);

$final_balance = 0;
$api_connected = false;

// 2. Evaluasi Respon API
if (isset($apiBalance['status']) && $apiBalance['status'] == 1) {
    if (isset($apiBalance['user']['balance'])) {
        $final_balance = floatval($apiBalance['user']['balance']);
        $api_connected = true;
        write_bal_log("SUCCESS: User $users | API Bal: $final_balance");
    } else {
        write_bal_log("WARNING: API Success but balance field missing for $users");
    }
} else {
    $error_msg = isset($apiBalance['msg']) ? $apiBalance['msg'] : 'Unknown Error';
    write_bal_log("ERROR: API Failed for $users | Msg: $error_msg");
}

// 3. Fallback ke Database Lokal jika API Down
if (!$api_connected) {
    $checkLocal = mysqli_query($conn, "SELECT active FROM `tb_balance` WHERE userID = '$id_user'");
    if ($row = mysqli_fetch_assoc($checkLocal)) {
        $final_balance = floatval($row['active']);
        write_bal_log("FALLBACK: Using local DB balance for $users | Bal: $final_balance");
    }
}

// 4. Sinkronisasi Database (Paksa DB mengikuti API)
$checkExist = mysqli_query($conn, "SELECT userID FROM `tb_balance` WHERE userID = '$id_user'");
if (mysqli_num_rows($checkExist) > 0) {
    $updateStmt = $conn->prepare("UPDATE tb_balance SET active = ? WHERE userID = ?");
    $updateStmt->bind_param("di", $final_balance, $id_user);
    $updateStmt->execute();
    $updateStmt->close();
} else {
    $insertStmt = $conn->prepare("INSERT INTO tb_balance (userID, active, pending, transfer, payout, created_date) VALUES (?, ?, 0, 0, 0, NOW())");
    $insertStmt->bind_param("id", $id_user, $final_balance);
    $insertStmt->execute();
    $insertStmt->close();
}

// 5. Output String untuk Header
echo number_format($final_balance, 2, ',', '.');
exit();