<?php
/**
 * Withdraw / Exit Game Handler — GoldSlotPalace API
 * 
 * Flow: Cek saldo di GSP → Tarik semua saldo → Kembalikan ke saldo lokal
 */
session_start();

include "../../function/connect.php";

// Load GoldSlotPalace class
if (file_exists('../../function/class.goldslot.php')) {
    require_once '../../function/class.goldslot.php';
} else {
    require_once '../function/class.goldslot.php';
}

$extplayer = $_SESSION['extplayer'] ?? '';

if (!$extplayer) {
    http_response_code(401);
    exit;
}

// ================================================================
// INIT GOLDSLOT PALACE API
// ================================================================
$apiConfig = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT api_token, callback_token FROM tb_goldslot_config LIMIT 1"));

if (!$apiConfig || empty($apiConfig['api_token'])) {
    echo json_encode(['status' => 'error', 'msg' => 'GoldSlotPalace config not found']);
    exit;
}

$gsp = new GoldSlotPalace($apiConfig['api_token'], $apiConfig['callback_token']);

// ================================================================
// GET USER CODE
// ================================================================
$safeExt = mysqli_real_escape_string($koneksi, $extplayer);
$q = mysqli_query($koneksi, "SELECT goldslot_user_code FROM tb_user WHERE extplayer = '$safeExt' OR username = '$safeExt' LIMIT 1");
$row = mysqli_fetch_assoc($q);
$userCode = (int)($row['goldslot_user_code'] ?? 0);

if ($userCode === 0) {
    // User belum punya goldslot account — tidak ada saldo di GSP
    $qSaldo = mysqli_query($koneksi, "SELECT active FROM tb_saldo WHERE id_user='$safeExt' LIMIT 1");
    $rowSaldo = mysqli_fetch_assoc($qSaldo);
    $saldoLocal = intval($rowSaldo['active'] ?? 0);
    
    echo json_encode([
        'status'  => 'ok',
        'wd'      => 0,
        'balance' => number_format($saldoLocal, 0, ',', '.'),
        'msg'     => 'No GSP account yet'
    ]);
    exit;
}

// ================================================================
// CEK SALDO DI GSP
// ================================================================
$infoRes = $gsp->getUserInfo($userCode);

if (!GoldSlotPalace::isSuccess($infoRes)) {
    echo json_encode([
        'status' => 'error',
        'msg'    => 'Failed to get GSP balance: ' . GoldSlotPalace::getErrorMessage($infoRes)
    ]);
    exit;
}

$gspBalance = (float)($infoRes['data']['balance'] ?? 0);

// ================================================================
// WITHDRAW ALL DARI GSP (JIKA ADA SALDO)
// ================================================================
$withdrawnAmount = 0;

if ($gspBalance > 0) {
    $wdRes = $gsp->withdrawAll($userCode);
    
    if (!GoldSlotPalace::isSuccess($wdRes)) {
        echo json_encode([
            'status' => 'error',
            'msg'    => 'Failed to withdraw from GSP: ' . GoldSlotPalace::getErrorMessage($wdRes)
        ]);
        exit;
    }
    
    $withdrawnAmount = (float)($wdRes['data']['amount'] ?? $gspBalance);
    
    // Tambahkan ke saldo lokal
    mysqli_query($koneksi, "UPDATE tb_saldo SET active = active + $withdrawnAmount WHERE id_user='$safeExt'");
    
    // Log transaksi
    $trxId = 'GSP_WD_' . time() . '_' . rand(100, 999);
    mysqli_query($koneksi, "INSERT INTO tb_transaksi (gambar, tanggal, transaksi, total, dari_bank, metode, bonus, keterangan, status, id_user, reff_id) VALUES ('', NOW(), 'Wd Game', '$withdrawnAmount', '', 'GOLDSLOT', 'tanpabonus', 'Auto Withdraw dari Game Wallet', 'Success', '$safeExt', '$trxId')");
}

// ================================================================
// AMBIL SALDO TERBARU LOKAL
// ================================================================
$qSaldo = mysqli_query($koneksi, "SELECT active FROM tb_saldo WHERE id_user='$safeExt' LIMIT 1");
$rowSaldo = mysqli_fetch_assoc($qSaldo);
$saldoTerbaru = intval($rowSaldo['active'] ?? 0);

echo json_encode([
    'status'  => 'ok',
    'wd'      => $withdrawnAmount,
    'balance' => number_format($saldoTerbaru, 0, ',', '.'),
    'msg'     => $withdrawnAmount > 0 ? "Withdraw $withdrawnAmount dari game wallet" : "No balance to withdraw"
]);