<?php 
ob_start();
session_start();
date_default_timezone_set("Asia/Jakarta");
include('../config/koneksi.php');
include('../config/class_softgaming.php');

$sid = session_id();
$sql_0 = mysqli_query($conn,"SELECT * FROM `tb_seo` WHERE cuid = 1") or die(mysqli_error());
$s0 = mysqli_fetch_array($sql_0);
$urlweb = $s0['urlweb'];
$urlwebs = $s0['urlweb'];

if (empty($_SESSION['user']) AND empty($_SESSION['pass'])){
  header('location:'.$urlwebs.'/index');
  exit;
}

$user = mysqli_query($conn,"SELECT * FROM `tb_user` WHERE username = '".$_SESSION['user']."'") or die (mysqli_error());
$u = mysqli_fetch_array($user);
$users = $u['username'];
$id_user = $u['cuid'];
$userID = $u['cuid'];

$WL = new fiver();

$apiBalance = $WL->userbalance($users);

$user_balance = 0;

if (isset($apiBalance['status']) && $apiBalance['status'] == 1) {
    if (isset($apiBalance['user']['balance'])) {
        $user_balance = floatval($apiBalance['user']['balance']);
    } else {
        $checkBalance = mysqli_query($conn, "SELECT active FROM `tb_balance` WHERE userID = '$userID'") or die(mysqli_error($conn));
        if (mysqli_num_rows($checkBalance) > 0) {
            $balanceRow = mysqli_fetch_array($checkBalance);
            $user_balance = floatval($balanceRow['active']);
        }
    }
} else {
    $checkBalance = mysqli_query($conn, "SELECT active FROM `tb_balance` WHERE userID = '$userID'") or die(mysqli_error($conn));
    if (mysqli_num_rows($checkBalance) > 0) {
        $balanceRow = mysqli_fetch_array($checkBalance);
        $user_balance = floatval($balanceRow['active']);
    }
}

$checkBalance = mysqli_query($conn, "SELECT userID FROM `tb_balance` WHERE userID = '$userID'") or die(mysqli_error($conn));

if (mysqli_num_rows($checkBalance) > 0) {
    $updateQuery = "UPDATE `tb_balance` SET `active` = '$user_balance' WHERE `userID` = '$userID'";
    mysqli_query($conn, $updateQuery) or die(mysqli_error($conn));
} else {
    $insertQuery = "INSERT INTO `tb_balance` (`userID`, `active`, `pending`, `payout`) VALUES ('$userID', '$user_balance', 0, 0)";
    mysqli_query($conn, $insertQuery) or die(mysqli_error($conn));
}

$saldo = number_format($user_balance, 2, ',', '.');

echo $saldo;
?>