<?php
require_once('session.php');

$userID = mysqli_real_escape_string($conn, $_POST['userID']);
$usere = strtolower($_POST['user']);
$useree = mysqli_real_escape_string($conn, $usere);
$user = str_replace(' ', '', $useree);
function generateRandomString($length = 20) {
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}
$randomString = generateRandomString();
$safeOutput = $randomString;
$extplayer = htmlspecialchars($safeOutput, ENT_QUOTES, 'UTF-8');
$externalPlayerId = htmlspecialchars($safeOutput, ENT_QUOTES, 'UTF-8');

// Update tb_user using prepared statement
$update1 = mysqli_prepare($conn, "UPDATE `tb_user` SET extplayer = ? WHERE cuid = ?");
mysqli_stmt_bind_param($update1, 'ss', $extplayer, $userID);
mysqli_stmt_execute($update1);

// Define $responses before using it
//$responses = /* Some value here */;

// Update tb_balance using prepared statement
$update2 = mysqli_prepare($conn, "UPDATE `tb_balance` SET active = ? WHERE userID = ?");
mysqli_stmt_bind_param($update2, 'ss', $responses, $userID);
mysqli_stmt_execute($update2);

// Close prepared statements
mysqli_stmt_close($update1);
mysqli_stmt_close($update2);

$sql_255 = mysqli_query($conn, "SELECT * FROM `tb_apigames` WHERE cuid = 1") or die(mysqli_error($conn));
$s255 = mysqli_fetch_array($sql_255);
            
// Panggil API untuk register user eksternal
$token = $s255['token'];
$owner = $s255['owner'];
$endpoint = $s255['endpoint'];
            
// Buat objek API dengan parameter yang diambil dari database
$api = new CxfteamsApi($token, $owner, $endpoint);
$registerResponse = $api->registerGame($extplayer);
$getBalanceResponse = $api->getBalance($externalPlayerId);

$query = "UPDATE tb_balance SET active = '$getBalanceResponse' WHERE userID = '$userID'";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));

// Redirect to balance page
header('location:../balance/');
exit();
?>
