<?php
/**
 * GoldSlotPalace Game Callback Handler
 * 
 * Menerima callback transaksi game (Bet, Win, BetCancel, Deposit, Withdraw, BonusCall)
 * dari GoldSlotPalace API.
 * 
 * Callback Token: fe5c7c62-9495-41d4-9834-2d19575f81fb
 * URL ini harus didaftarkan ke GoldSlotPalace sebagai Callback URL
 */
require_once 'connect.php';
require_once 'class.goldslot.php';

// Callback token untuk verifikasi
$CALLBACK_TOKEN = 'fe5c7c62-9495-41d4-9834-2d19575f81fb';

// Ambil data mentah dari GoldSlotPalace
$rawInput = file_get_contents('php://input');
$payload = json_decode($rawInput, true);

// Log semua callback untuk debug
$logFile = __DIR__ . '/log_goldslot_callback.txt';
file_put_contents($logFile, "=== " . date('Y-m-d H:i:s') . " ===\n" . $rawInput . "\n\n", FILE_APPEND);

// Validasi payload
if (!$payload || !isset($payload['code'])) {
    file_put_contents($logFile, "[ERROR] Invalid callback payload\n\n", FILE_APPEND);
    http_response_code(400);
    echo json_encode(['code' => 1002, 'message' => 'Invalid payload']);
    exit;
}

// Optional: verifikasi callback token jika disediakan
if (isset($payload['callback_token']) && $payload['callback_token'] !== $CALLBACK_TOKEN) {
    file_put_contents($logFile, "[ERROR] Invalid callback token\n\n", FILE_APPEND);
    http_response_code(401);
    echo json_encode(['code' => 1009, 'message' => 'Invalid callback token']);
    exit;
}

// ================================================================
// TRANSACTION TYPES (sesuai dokumentasi):
// 1   = Bet
// 2   = Win
// 4   = Deposit
// 8   = Withdraw
// 16  = BetCancel
// 32  = BonusCall
// 64+ = Other
// ================================================================

$data = $payload['data'] ?? [];
$list = $data['list'] ?? [];

// Jika format callback adalah list transaksi
if (!empty($list) && is_array($list)) {
    foreach ($list as $transaction) {
        processTransaction($transaction, $koneksi, $logFile);
    }
}

// Jika format callback adalah single transaction
if (isset($payload['data']['trans_id'])) {
    processTransaction($payload['data'], $koneksi, $logFile);
}

// Beri respon sukses ke GoldSlotPalace (WAJIB HTTP 200 OK dengan code 0)
http_response_code(200);
header('Content-Type: application/json');
echo json_encode(['code' => 0, 'message' => 'OK']);
exit;

/* ================================================================
   PROCESS SINGLE TRANSACTION
   ================================================================ */
function processTransaction($trx, $koneksi, $logFile) {
    // Validasi data minimal
    if (!isset($trx['trans_id']) || !isset($trx['user_code'])) {
        file_put_contents($logFile, "[WARN] Skipping transaction - missing trans_id or user_code\n", FILE_APPEND);
        return;
    }

    $transId      = $trx['trans_id'];
    $userCode     = $trx['user_code'];
    $transType    = $trx['trans_type'] ?? 0;
    $amount       = $trx['trans_amount'] ?? 0;
    $balance      = $trx['balance'] ?? 0;
    $preBalance   = $trx['prebalance'] ?? 0;
    $roundId      = $trx['round_id'] ?? '';
    $providerId   = $trx['provider_id'] ?? 0;
    $providerName = $trx['provider_name'] ?? '';
    $gameCode     = $trx['game_code'] ?? '';
    $gameName     = $trx['game_name'] ?? '';
    $category     = $trx['category'] ?? '';
    $regdate      = $trx['regdate'] ?? date('Y-m-d H:i:s');

    $userCodeEsc     = mysqli_real_escape_string($koneksi, $userCode);
    $roundIdEsc      = mysqli_real_escape_string($koneksi, $roundId);
    $providerNameEsc = mysqli_real_escape_string($koneksi, $providerName);
    $gameCodeEsc     = mysqli_real_escape_string($koneksi, $gameCode);
    $gameNameEsc     = mysqli_real_escape_string($koneksi, $gameName);
    $categoryEsc     = mysqli_real_escape_string($koneksi, $category);
    $regdateEsc      = mysqli_real_escape_string($koneksi, $regdate);

    // Cek duplikasi transaksi
    $checkDup = mysqli_query($koneksi, "SELECT id FROM tb_goldslot_transactions WHERE trans_id = '$transId' LIMIT 1");
    if (mysqli_num_rows($checkDup) > 0) {
        file_put_contents($logFile, "[INFO] Duplicate transaction trans_id=$transId, skipped.\n", FILE_APPEND);
        return;
    }

    // Insert log transaksi
    $sql = "INSERT INTO tb_goldslot_transactions 
            (trans_id, user_code, round_id, trans_type, provider_id, provider_name, game_code, game_name, category, 
             prebalance, trans_amount, balance, regdate, created_at) 
            VALUES 
            ('$transId', '$userCodeEsc', '$roundIdEsc', '$transType', '$providerId', '$providerNameEsc', '$gameCodeEsc', '$gameNameEsc', '$categoryEsc',
             '$preBalance', '$amount', '$balance', '$regdateEsc', NOW())";

    $insertResult = mysqli_query($koneksi, $sql);

    if (!$insertResult) {
        file_put_contents($logFile, "[ERROR] Failed to insert transaction trans_id=$transId: " . mysqli_error($koneksi) . "\n", FILE_APPEND);
        return;
    }

    // ================================================================
    // PROCESS BY TRANSACTION TYPE (update saldo user jika perlu)
    // ================================================================
    
    // Cari user lokal berdasarkan goldslot user_code
    // Asumsi: user_code GoldSlotPalace disimpan di tb_users atau tabel mapping
    $findUser = mysqli_query($koneksi, "SELECT id, username FROM tb_user WHERE goldslot_user_code = '$userCodeEsc' LIMIT 1");

    if (mysqli_num_rows($findUser) > 0) {
        $user = mysqli_fetch_assoc($findUser);
        $localUserId   = $user['id'];
        $localUsername = $user['username'];

        switch ($transType) {
            case 1: // Bet - kurangi saldo
                $updateSaldo = mysqli_query($koneksi, "UPDATE tb_saldo SET active = active - $amount WHERE id_user = '$localUsername'");
                if ($updateSaldo) {
                    file_put_contents($logFile, "[BET] User $localUsername bet $amount, saldo dikurangi.\n", FILE_APPEND);
                }
                break;

            case 2: // Win - tambah saldo
                $updateSaldo = mysqli_query($koneksi, "UPDATE tb_saldo SET active = active + $amount WHERE id_user = '$localUsername'");
                if ($updateSaldo) {
                    file_put_contents($logFile, "[WIN] User $localUsername win $amount, saldo ditambah.\n", FILE_APPEND);
                }
                break;

            case 16: // BetCancel - refund saldo
                $updateSaldo = mysqli_query($koneksi, "UPDATE tb_saldo SET active = active + $amount WHERE id_user = '$localUsername'");
                if ($updateSaldo) {
                    file_put_contents($logFile, "[BET_CANCEL] User $localUsername bet cancelled, refund $amount.\n", FILE_APPEND);
                }
                break;

            case 32: // BonusCall win - tambah saldo
                $updateSaldo = mysqli_query($koneksi, "UPDATE tb_saldo SET active = active + $amount WHERE id_user = '$localUsername'");
                if ($updateSaldo) {
                    file_put_contents($logFile, "[BONUS_CALL] User $localUsername bonus call win $amount, saldo ditambah.\n", FILE_APPEND);
                }
                break;

            case 4:  // Deposit (dari agent ke user)
            case 8:  // Withdraw (dari user ke agent)
                // Transaksi wallet Transfer Mode - saldo sudah ter-update di GoldSlotPalace
                // Bisa digunakan untuk sinkronisasi jika diperlukan
                file_put_contents($logFile, "[WALLET] trans_type=$transType amount=$amount for user $localUsername.\n", FILE_APPEND);
                break;

            default:
                file_put_contents($logFile, "[INFO] Unknown trans_type=$transType amount=$amount for user $localUsername.\n", FILE_APPEND);
                break;
        }
    } else {
        file_put_contents($logFile, "[INFO] User with goldslot_user_code=$userCode not found in local DB. Transaction logged only.\n", FILE_APPEND);
    }

    file_put_contents($logFile, "[OK] Transaction trans_id=$transId processed successfully.\n", FILE_APPEND);
}