<?php
/**
 * GoldSlotPalace Game AJAX Handler
 * 
 * Menangani operasi: deposit, withdraw, open game, check balance
 * Dipanggil via AJAX dari frontend
 */
session_start();
header('Content-Type: application/json');

// Koneksi database
if (file_exists('../../function/connect.php')) {
    require_once '../../function/connect.php';
} else {
    require_once '../function/connect.php';
}

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

// ================================================================
// AMBIL KONFIGURASI DARI DATABASE
// ================================================================
$apiConfig = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT api_token, callback_token FROM tb_goldslot_config LIMIT 1"));

if (!$apiConfig) {
    echo json_encode(['status' => false, 'message' => 'GoldSlotPalace config not found in database']);
    exit;
}

$apiToken      = $apiConfig['api_token'];
$callbackToken = $apiConfig['callback_token'];

// Inisialisasi API
$goldslot = new GoldSlotPalace($apiToken, $callbackToken);

// ================================================================
// DAPATKAN PARAMETER DARI REQUEST
// ================================================================
$action   = $_POST['action']   ?? $_GET['action']   ?? '';
$provider = $_POST['provider'] ?? $_GET['provider'] ?? 'PRAGMATIC';
$gameCode = $_POST['game_code'] ?? $_GET['game_code'] ?? '';
$amount   = $_POST['amount']   ?? $_GET['amount']   ?? 0;
$lang     = $_POST['ln']       ?? $_GET['ln']       ?? 9; // 9 = Indonesian

// Sinkronisasi session player
$player = $_SESSION['extplayer'] ?? $_SESSION['id'] ?? $_SESSION['username'] ?? null;

if (!$player) {
    echo json_encode(['status' => false, 'message' => 'Error: Sesi login habis, silahkan login ulang!']);
    exit;
}

// ================================================================
// HELPER: Dapatkan goldslot user_code dari local user
// ================================================================
function getGoldSlotUserCode($koneksi, $player) {
    $playerEsc = mysqli_real_escape_string($koneksi, $player);
    $result = mysqli_query($koneksi, "SELECT goldslot_user_code FROM tb_user WHERE username = '$playerEsc' OR id = '$playerEsc' LIMIT 1");
    
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        if (!empty($row['goldslot_user_code'])) {
            return (int)$row['goldslot_user_code'];
        }
    }
    return 0; // Belum punya user_code
}

// ================================================================
// HELPER: Simpan goldslot user_code ke database
// ================================================================
function saveGoldSlotUserCode($koneksi, $player, $userCode) {
    $playerEsc  = mysqli_real_escape_string($koneksi, $player);
    $userCode   = (int)$userCode;
    
    // Update existing record
    $update = mysqli_query($koneksi, "UPDATE tb_user SET goldslot_user_code = '$userCode' WHERE username = '$playerEsc' OR id = '$playerEsc'");
    
    return $update;
}

// ================================================================
// HELPER: Format response (sesuai format yang dipakai existing)
// ================================================================
function jsonResponse($status, $msg, $extra = []) {
    $res = ['status' => $status, 'msg' => $msg];
    return json_encode(array_merge($res, $extra));
}

// ================================================================
// PROSES BERDASARKAN ACTION
// ================================================================
try {
    switch ($action) {

        /* ----------------------------------------------------------
           GET PROVIDERS LIST
           ---------------------------------------------------------- */
        case 'provider_list':
        case 'providers':
            $res = $goldslot->getProviders($lang);
            
            if (!GoldSlotPalace::isSuccess($res)) {
                echo jsonResponse(false, GoldSlotPalace::getErrorMessage($res));
                exit;
            }
            
            $providers = [];
            if (!empty($res['data'])) {
                foreach ($res['data'] as $p) {
                    // Hanya provider yang aktif
                    if ((int)$p['status'] === 1) {
                        $providers[] = [
                            'code' => strtolower($p['provider_name']),
                            'id'   => $p['provider_id'],
                            'name' => $p['locale_name'] ?? $p['provider_name']
                        ];
                    }
                }
            }
            
            echo json_encode(['success' => true, 'providers' => $providers]);
            break;

        /* ----------------------------------------------------------
           GET GAMES LIST
           ---------------------------------------------------------- */
        case 'game_list':
        case 'games':
            $providerId = $_POST['provider_id'] ?? $_GET['provider_id'] ?? 0;
            
            if (!$providerId) {
                echo jsonResponse(false, 'Provider ID diperlukan');
                exit;
            }
            
            $res = $goldslot->getGames($providerId, $lang);
            
            if (!GoldSlotPalace::isSuccess($res)) {
                echo jsonResponse(false, GoldSlotPalace::getErrorMessage($res));
                exit;
            }
            
            $games = [];
            if (!empty($res['data'])) {
                foreach ($res['data'] as $g) {
                    $games[] = [
                        'game_code'  => $g['game_code'],
                        'game_name'  => $g['locale_name'] ?? $g['game_name'],
                        'image'      => $g['game_image'] ?? '',
                        'category'   => $g['category'] ?? 'Slots',
                        'launchable' => $g['launch_enable'] ?? true
                    ];
                }
            }
            
            echo json_encode(['success' => true, 'games' => $games]);
            break;

        /* ----------------------------------------------------------
           CREATE USER & GET USER CODE
           ---------------------------------------------------------- */
        case 'create_user':
        case 'register':
            // Cek apakah user sudah punya goldslot_user_code
            $existingCode = getGoldSlotUserCode($koneksi, $player);
            
            if ($existingCode > 0) {
                echo json_encode([
                    'status'    => true,
                    'user_code' => $existingCode,
                    'message'   => 'User already registered'
                ]);
                exit;
            }
            
            // Buat user baru di GoldSlotPalace
            // Nama user harus alphanumeric + underscore, 2-50 chars
            $sanitizedName = preg_replace('/[^a-zA-Z0-9_]/', '', $player);
            $sanitizedName = substr($sanitizedName, 0, 50);
            if (strlen($sanitizedName) < 2) {
                $sanitizedName = 'user_' . uniqid();
            }
            
            $res = $goldslot->createUser($sanitizedName);
            
            if (!GoldSlotPalace::isSuccess($res)) {
                echo jsonResponse(false, GoldSlotPalace::getErrorMessage($res));
                exit;
            }
            
            $userCode = $res['data']['user_code'] ?? 0;
            
            if ($userCode > 0) {
                saveGoldSlotUserCode($koneksi, $player, $userCode);
            }
            
            echo json_encode([
                'status'    => true,
                'user_code' => $userCode,
                'is_new'    => $res['data']['is_new_user'] ?? true,
                'message'   => 'User registered successfully'
            ]);
            break;

        /* ----------------------------------------------------------
           DEPOSIT (Transfer saldo ke game wallet)
           ---------------------------------------------------------- */
        case 'deposit':
        case 'transfer_in':
            $userCode = getGoldSlotUserCode($koneksi, $player);
            
            // Auto create user jika belum punya
            if ($userCode === 0) {
                $sanitizedName = preg_replace('/[^a-zA-Z0-9_]/', '', $player);
                $sanitizedName = substr($sanitizedName, 0, 50);
                if (strlen($sanitizedName) < 2) {
                    $sanitizedName = 'user_' . uniqid();
                }
                
                $createRes = $goldslot->createUser($sanitizedName);
                if (!GoldSlotPalace::isSuccess($createRes)) {
                    echo jsonResponse(false, 'Gagal membuat user game: ' . GoldSlotPalace::getErrorMessage($createRes));
                    exit;
                }
                
                $userCode = $createRes['data']['user_code'] ?? 0;
                if ($userCode > 0) {
                    saveGoldSlotUserCode($koneksi, $player, $userCode);
                }
            }
            
            if (!$amount || $amount <= 0) {
                echo jsonResponse(false, 'Jumlah deposit tidak valid');
                exit;
            }
            
            // Kirim deposit ke GoldSlotPalace
            $res = $goldslot->deposit($userCode, $amount);
            
            if (!GoldSlotPalace::isSuccess($res)) {
                echo jsonResponse(false, GoldSlotPalace::getErrorMessage($res));
                exit;
            }
            
            $newBalance = $res['data']['balance'] ?? 0;
            $processed  = $res['data']['amount'] ?? $amount;
            
            // Kurangi saldo lokal user (saldo dipindahkan ke game wallet)
            $playerEsc = mysqli_real_escape_string($koneksi, $player);
            mysqli_query($koneksi, "UPDATE tb_saldo SET active = active - $processed WHERE id_user = '$playerEsc'");
            
            // Log transaksi
            $trxId = 'GSP_DEP_' . 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(), 'Trf Game', '$processed', '', 'GOLDSLOT', 'tanpabonus', 'Transfer ke Game Wallet', 'Success', '$playerEsc', '$trxId')");
            
            echo json_encode([
                'status'  => true,
                'balance' => $newBalance,
                'amount'  => $processed,
                'message' => 'Deposit berhasil! Saldo game: ' . number_format($newBalance)
            ]);
            break;

        /* ----------------------------------------------------------
           WITHDRAW (Tarik saldo dari game wallet)
           ---------------------------------------------------------- */
        case 'withdraw':
        case 'transfer_out':
            $userCode = getGoldSlotUserCode($koneksi, $player);
            
            if ($userCode === 0) {
                echo jsonResponse(false, 'User belum terdaftar di game provider');
                exit;
            }
            
            if (!$amount || $amount <= 0) {
                echo jsonResponse(false, 'Jumlah withdraw tidak valid');
                exit;
            }
            
            // Tarik dari GoldSlotPalace
            $res = $goldslot->withdraw($userCode, $amount);
            
            if (!GoldSlotPalace::isSuccess($res)) {
                echo jsonResponse(false, GoldSlotPalace::getErrorMessage($res));
                exit;
            }
            
            $newBalance = $res['data']['balance'] ?? 0;
            $processed  = $res['data']['amount'] ?? $amount;
            
            // Tambah saldo lokal user (saldo dikembalikan dari game wallet)
            $playerEsc = mysqli_real_escape_string($koneksi, $player);
            mysqli_query($koneksi, "UPDATE tb_saldo SET active = active + $processed WHERE id_user = '$playerEsc'");
            
            // 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', '$processed', '', 'GOLDSLOT', 'tanpabonus', 'Withdraw dari Game Wallet', 'Success', '$playerEsc', '$trxId')");
            
            echo json_encode([
                'status'  => true,
                'balance' => $newBalance,
                'amount'  => $processed,
                'message' => 'Withdraw berhasil! Sisa saldo game: ' . number_format($newBalance)
            ]);
            break;

        /* ----------------------------------------------------------
           WITHDRAW ALL (Tarik semua saldo dari game wallet)
           ---------------------------------------------------------- */
        case 'withdraw_all':
            $userCode = getGoldSlotUserCode($koneksi, $player);
            
            if ($userCode === 0) {
                echo jsonResponse(false, 'User belum terdaftar di game provider');
                exit;
            }
            
            $res = $goldslot->withdrawAll($userCode);
            
            if (!GoldSlotPalace::isSuccess($res)) {
                echo jsonResponse(false, GoldSlotPalace::getErrorMessage($res));
                exit;
            }
            
            $processed  = $res['data']['amount'] ?? 0;
            
            // Tambah saldo lokal user
            $playerEsc = mysqli_real_escape_string($koneksi, $player);
            mysqli_query($koneksi, "UPDATE tb_saldo SET active = active + $processed WHERE id_user = '$playerEsc'");
            
            $trxId = 'GSP_WDA_' . 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 All Game', '$processed', '', 'GOLDSLOT', 'tanpabonus', 'Withdraw All dari Game Wallet', 'Success', '$playerEsc', '$trxId')");
            
            echo json_encode([
                'status'  => true,
                'amount'  => $processed,
                'message' => 'Semua saldo ditarik: ' . number_format($processed)
            ]);
            break;

        /* ----------------------------------------------------------
           GET USER BALANCE (saldo di game wallet)
           ---------------------------------------------------------- */
        case 'balance':
        case 'user_info':
            $userCode = getGoldSlotUserCode($koneksi, $player);
            
            if ($userCode === 0) {
                echo json_encode(['status' => true, 'balance' => 0, 'message' => 'User belum terdaftar']);
                exit;
            }
            
            $res = $goldslot->getUserInfo($userCode);
            
            if (!GoldSlotPalace::isSuccess($res)) {
                echo jsonResponse(false, GoldSlotPalace::getErrorMessage($res));
                exit;
            }
            
            echo json_encode([
                'status'  => true,
                'balance' => $res['data']['balance'] ?? 0,
                'name'    => $res['data']['name'] ?? $player
            ]);
            break;

        /* ----------------------------------------------------------
           OPEN GAME (LAUNCH)
           ---------------------------------------------------------- */
        case 'open_game':
        case 'launch':
            $providerId = $_POST['provider_id'] ?? $_GET['provider_id'] ?? 0;
            
            if (!$providerId || !$gameCode) {
                echo jsonResponse(false, 'Provider ID dan Game Code diperlukan');
                exit;
            }
            
            // Dapatkan user_code
            $userCode = getGoldSlotUserCode($koneksi, $player);
            
            // Auto create user jika belum terdaftar
            if ($userCode === 0) {
                $sanitizedName = preg_replace('/[^a-zA-Z0-9_]/', '', $player);
                $sanitizedName = substr($sanitizedName, 0, 50);
                if (strlen($sanitizedName) < 2) {
                    $sanitizedName = 'user_' . uniqid();
                }
                
                $createRes = $goldslot->createUser($sanitizedName);
                if (!GoldSlotPalace::isSuccess($createRes)) {
                    echo jsonResponse(false, 'Gagal membuat user: ' . GoldSlotPalace::getErrorMessage($createRes));
                    exit;
                }
                
                $userCode = $createRes['data']['user_code'] ?? 0;
                if ($userCode > 0) {
                    saveGoldSlotUserCode($koneksi, $player, $userCode);
                }
            }
            
            // Ambil URL game
            $returnUrl = $web_sett['url'] ?? '';
            $res = $goldslot->getGameUrl($userCode, $providerId, $gameCode, $lang, $returnUrl);
            
            if (!GoldSlotPalace::isSuccess($res)) {
                echo jsonResponse(false, GoldSlotPalace::getErrorMessage($res));
                exit;
            }
            
            $gameUrl = $res['data']['game_url'] ?? '';
            
            if (empty($gameUrl)) {
                echo jsonResponse(false, 'Game URL kosong dari provider');
                exit;
            }
            
            echo json_encode([
                'status' => 1,
                'url'    => $gameUrl,
                'msg'    => 'Game ready'
            ]);
            break;

        /* ----------------------------------------------------------
           GET AGENT INFO
           ---------------------------------------------------------- */
        case 'agent_info':
            $res = $goldslot->getAgentInfo();
            
            if (!GoldSlotPalace::isSuccess($res)) {
                echo jsonResponse(false, GoldSlotPalace::getErrorMessage($res));
                exit;
            }
            
            echo json_encode([
                'status'   => true,
                'agent'    => $res['data']
            ]);
            break;

        /* ----------------------------------------------------------
           TEST CALLBACK
           ---------------------------------------------------------- */
        case 'test_callback':
            $res = $goldslot->testCallback();
            
            if (GoldSlotPalace::isSuccess($res)) {
                echo json_encode(['status' => true, 'message' => 'Callback test berhasil']);
            } else {
                echo jsonResponse(false, GoldSlotPalace::getErrorMessage($res));
            }
            break;

        /* ----------------------------------------------------------
           DEFAULT: ACTION NOT FOUND
           ---------------------------------------------------------- */
        default:
            echo jsonResponse(false, 'Action tidak dikenali: ' . $action);
            exit;
    }

} catch (Exception $e) {
    echo json_encode(['status' => false, 'message' => 'Error: ' . $e->getMessage()]);
}