<?php
ob_start();
session_start();
date_default_timezone_set("Asia/Jakarta");
include('../config/koneksi.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'];
$pengguna = $s0['user'];
$keywords = $s0['keyword'];
$deskripsi = $s0['deskripsi'];
$deskripsi = $s0['deskripsi'];
$pengumuman = $s0['pengumuman'];
$unik = $s0['unik'];
$alert = $s0['news'];
$instansi = $s0['instansi'];

$sql_1 = mysqli_query($conn,"SELECT * FROM `tb_user` WHERE cuid = 1") or die(mysqli_error());
$s1b = mysqli_fetch_array($sql_1);

$sql_1 = mysqli_query($conn,"SELECT * FROM `tb_social` WHERE cuid = 1") or die(mysqli_error());
$s1a = mysqli_fetch_array($sql_1);

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

$user =mysqli_query($conn,"SELECT * FROM `tb_user` WHERE user = '".$_SESSION['user']."'") or die (mysqli_error());
$u = mysqli_fetch_array($user);
$users = $u['user'];
$id_user = $u['cuid'];
$userID = $u['cuid'];
$externalPlayerId = $u['extplayer'];
$token_id = isset($u['token_id']) ? $u['token_id'] : false;
$level = isset($u['level']) ? $u['level'] : false;
// Pastikan response dari API berisi balance, jika tidak ada default ke 0
//$balance = isset($getBalanceResponse['balance']) ? $getBalanceResponse['balance'] : 0;

$bal = $kingisback->getBalance($externalPlayerId);
if ((int)$bal['status'] === 200) {
    $getBalanceResponse = $bal['data']['balance'] ?? 0;
} else {
    $getBalanceResponse = 0;
}

// Update balance in database menggunakan mysqli_query biasa
$query = "UPDATE tb_balance SET active = '$getBalanceResponse' WHERE userID = '$userID'";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));

$sql_3 = mysqli_query($conn,"SELECT * FROM `tb_balance` WHERE userID = '$userID'") or die(mysqli_error());
$s3 = mysqli_fetch_array($sql_3);

$sql_balance = mysqli_query($conn, "SELECT * FROM `tb_balance` WHERE userID = '$userID'") or die(mysqli_error());
$sb = mysqli_fetch_array($sql_balance);

$sql_banks = mysqli_query($conn,"SELECT * FROM `tb_bank` WHERE userID = '$userID'") or die(mysqli_error());
$sbs = mysqli_fetch_array($sql_banks);
?>