<?php
/**
 * Game Launch Handler — GoldSlotPalace API
 * 
 * Flow: Buat user di GSP → Deposit saldo → Buka game
 */
session_start();
header('Content-Type: application/json');

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

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

// ================================================================
// GET PARAMETERS
// ================================================================
$provider  = $_POST['provider']  ?? '';
$gameCode  = $_POST['game_code'] ?? '';
$lang      = $_POST['ln'] ?? 'id';
$extplayer = $_SESSION['extplayer'] ?? '';

if ($provider === '' || $gameCode === '' || $extplayer === '') {
    echo json_encode(['status' => 0, 'msg' => 'Invalid parameter']);
    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' => 0, 'msg' => 'GoldSlotPalace config not found']);
    exit;
}

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

// ================================================================
// HELPER: Get provider_id dari nama provider (dengan alias + auto-sync)
// ================================================================
function getProviderId($koneksi, $providerName, $gsp = null) {
    // Alias mapping: nama lama (config.php) → nama di GoldSlotPalace
    $aliasMap = [
        'PGSOFT'        => 'Pocket Games Soft',
        'PG SOFT'       => 'Pocket Games Soft',
        'PRAGMATIC'     => 'Pragmatic Play',
        'PRAGMATICLIVE' => 'Pragmatic Play',
        'SPRIBE'        => 'Spribe',
        'EVOPLAY'       => 'Pragmatic Play',
        'TOPTREND'      => 'Pragmatic Play',
        'DREAMTECH'     => 'Pragmatic Play',
        'REELKINGDOM'   => 'Pragmatic Play',
        'FATPANDA'      => 'Pragmatic Play',
        'BOOONGO'       => 'Booongo',
        'SPORTSBOOK'    => 'Pragmatic Play',
    ];
    
    // Normalize input
    $lookup = strtoupper(trim($providerName));
    
    // Cek alias dulu
    if (isset($aliasMap[$lookup])) {
        $searchName = $aliasMap[$lookup];
    } else {
        $searchName = $providerName;
    }
    
    // Search in database by provider_name
    $safeName = mysqli_real_escape_string($koneksi, $searchName);
    $q = mysqli_query($koneksi, "SELECT provider_id FROM tb_goldslot_providers WHERE provider_name LIKE '%$safeName%' LIMIT 1");
    if ($q && $row = mysqli_fetch_assoc($q)) {
        return (int)$row['provider_id'];
    }
    
    // Fallback: search by LIKE
    $q2 = mysqli_query($koneksi, "SELECT provider_id, provider_name FROM tb_goldslot_providers LIMIT 50");
    while ($r = mysqli_fetch_assoc($q2)) {
        similarText(strtoupper($r['provider_name']), strtoupper($providerName), $percent);
        similarText(strtoupper($r['provider_name']), strtoupper($searchName), $percent2);
        if ($percent > 60 || $percent2 > 60) {
            return (int)$r['provider_id'];
        }
    }
    
    // ================================================================
    // AUTO-SYNC: Jika tidak ditemukan & GSP object tersedia, sync dari API
    // ================================================================
    if ($gsp !== null) {
        $providersRes = $gsp->getProviders(1);
        if (GoldSlotPalace::isSuccess($providersRes)) {
            foreach (($providersRes['data'] ?? []) as $p) {
                $pid   = (int)$p['provider_id'];
                $pname = mysqli_real_escape_string($koneksi, $p['provider_name']);
                $lname = mysqli_real_escape_string($koneksi, $p['locale_name'] ?? $p['provider_name']);
                $stat  = (int)$p['status'];
                
                mysqli_query($koneksi, "INSERT INTO tb_goldslot_providers (provider_id, provider_name, locale_name, status, last_sync) 
                    VALUES ('$pid', '$pname', '$lname', '$stat', NOW()) 
                    ON DUPLICATE KEY UPDATE provider_name='$pname', locale_name='$lname', status='$stat', last_sync=NOW()");
            }
            
            // Coba search lagi setelah sync
            $qRetry = mysqli_query($koneksi, "SELECT provider_id FROM tb_goldslot_providers WHERE provider_name LIKE '%$safeName%' LIMIT 1");
            if ($qRetry && $row2 = mysqli_fetch_assoc($qRetry)) {
                return (int)$row2['provider_id'];
            }
        }
    }
    
    return 0;
}

// ================================================================
// HELPER: Get or create GoldSlotPalace user_code
// ================================================================
function getOrCreateGspUser($koneksi, $gsp, $extplayer) {
    // Cek apakah user sudah punya goldslot_user_code di tb_user
    $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");
    
    if ($q && $row = mysqli_fetch_assoc($q)) {
        if (!empty($row['goldslot_user_code']) && $row['goldslot_user_code'] > 0) {
            return (int)$row['goldslot_user_code'];
        }
    }
    
    // Buat user baru di GoldSlotPalace
    $sanitizedName = preg_replace('/[^a-zA-Z0-9_]/', '', $extplayer);
    $sanitizedName = substr($sanitizedName, 0, 50);
    if (strlen($sanitizedName) < 2) {
        $sanitizedName = 'user_' . uniqid();
    }
    
    $createRes = $gsp->createUser($sanitizedName);
    
    if (!GoldSlotPalace::isSuccess($createRes)) {
        return 0;
    }
    
    $userCode = (int)($createRes['data']['user_code'] ?? 0);
    
    if ($userCode > 0) {
        // Simpan ke tb_user
        if ($q && $row) {
            mysqli_query($koneksi, "UPDATE tb_user SET goldslot_user_code = '$userCode' WHERE extplayer = '$safeExt' OR username = '$safeExt'");
        } else {
            mysqli_query($koneksi, "UPDATE tb_user SET goldslot_user_code = '$userCode' WHERE extplayer = '$safeExt' OR id = '$safeExt'");
        }
    }
    
    return $userCode;
}

// ================================================================
// GET PROVIDER ID
// ================================================================
$providerId = getProviderId($koneksi, $provider);

if ($providerId === 0) {
    echo json_encode(['status' => 0, 'msg' => "Provider '$provider' not found. Please sync providers first."]);
    exit;
}

// ================================================================
// CREATE OR GET GSP USER
// ================================================================
$userCode = getOrCreateGspUser($koneksi, $gsp, $extplayer);

if ($userCode === 0) {
    echo json_encode(['status' => 0, 'msg' => 'Failed to create user in GoldSlotPalace']);
    exit;
}

// ================================================================
// PASTIKAN USER ADA DI DB LOKAL
// ================================================================
$safeExt = mysqli_real_escape_string($koneksi, $extplayer);
$qUser = mysqli_query($koneksi, "SELECT id FROM tb_user WHERE extplayer='$safeExt' LIMIT 1");

if (!mysqli_fetch_assoc($qUser)) {
    mysqli_query($koneksi, "INSERT INTO tb_user (username,extplayer,password,email,no_hp,level,refferal,status,status_game,goldslot_user_code) VALUES ('$safeExt','$safeExt','','','','user','$safeExt','Active','ongame','$userCode')");
    mysqli_query($koneksi, "INSERT INTO tb_saldo (id_user,active) VALUES ('$safeExt',0)");
}

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

// ================================================================
// DEPOSIT SALDO KE GSP WALLET (JIKA ADA)
// ================================================================
if ($saldo > 0) {
    $depRes = $gsp->deposit($userCode, $saldo);
    
    if (!GoldSlotPalace::isSuccess($depRes)) {
        echo json_encode(['status' => 0, 'msg' => 'Deposit to game wallet failed: ' . GoldSlotPalace::getErrorMessage($depRes)]);
        exit;
    }
    
    // Nolkan saldo lokal
    mysqli_query($koneksi, "UPDATE tb_saldo SET active = 0 WHERE id_user='$safeExt'");
    
    // 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', '$saldo', '', 'GOLDSLOT', 'tanpabonus', 'Auto Transfer ke Game Wallet', 'Success', '$safeExt', '$trxId')");
}

// ================================================================
// GAME CODE RESOLVER: Jika game_code tidak ditemukan, cari by name
// ================================================================
function resolveGameCode($gsp, $providerId, $gameCode, $gspLang) {
    // Coba langsung dengan game_code asli
    $testRes = $gsp->getGameUrl(1, $providerId, $gameCode, $gspLang);
    if (GoldSlotPalace::isSuccess($testRes)) {
        return $gameCode;
    }
    
    // Jika GAME_NOT_FOUND, cari di game list
    $gamesRes = $gsp->getGames($providerId, $gspLang);
    if (!GoldSlotPalace::isSuccess($gamesRes)) {
        return $gameCode; // return original, biar error ditangani nanti
    }
    
    // Convert game_code yang mungkin pakai format berbeda
    // Contoh: old "mahjong-ways-2" → new format dari GSP
    $searchTerms = [];
    
    // Original code as search term
    $searchTerms[] = strtolower($gameCode);
    
    // Clean: remove dashes, underscores, spaces
    $clean = str_replace(['-', '_', ' '], '', strtolower($gameCode));
    $searchTerms[] = $clean;
    
    // Try to match by game_code or game_name
    foreach (($gamesRes['data'] ?? []) as $game) {
        $gCode = strtolower($game['game_code'] ?? '');
        $gName = strtolower($game['game_name'] ?? '');
        $lName = strtolower($game['locale_name'] ?? '');
        
        foreach ($searchTerms as $term) {
            // Exact match game_code
            if ($gCode === $term) {
                return $game['game_code'];
            }
            // Partial match game_code
            if (strpos($gCode, $term) !== false || strpos($term, $gCode) !== false) {
                return $game['game_code'];
            }
            // Match in game name
            if (strpos($gName, $term) !== false || strpos($lName, $term) !== false) {
                return $game['game_code'];
            }
            // Clean name matching
            $cleanName = str_replace(['-', '_', ' ', '™', '&', '.', ',', '\'', '"'], '', $gName);
            if (strpos($cleanName, $term) !== false) {
                return $game['game_code'];
            }
        }
    }
    
    return $gameCode; // return original if no match
}

// ================================================================
// LANGUAGE MAPPING
// ================================================================
$langMap = [
    'id' => 1,   // English fallback (Indonesian not in GSP)
    'en' => 1,
    'cn' => 11,  // Chinese Simplified
    'th' => 3,   // Thai
    'vi' => 12,  // Vietnamese
    'jp' => 5,   // Japanese
    'kr' => 2,   // Korean
];
$gspLang = $langMap[$lang] ?? 1;

// ================================================================
// RESOLVE GAME CODE (auto-cari jika nama beda format)
// ================================================================
$resolvedCode = resolveGameCode($gsp, $providerId, $gameCode, $gspLang);

// ================================================================
// OPEN GAME
// ================================================================
$launchRes = $gsp->getGameUrl($userCode, $providerId, $resolvedCode, $gspLang);

if (!GoldSlotPalace::isSuccess($launchRes)) {
    echo json_encode(['status' => 0, 'msg' => 'Open game failed: ' . GoldSlotPalace::getErrorMessage($launchRes)]);
    exit;
}

$gameUrl = $launchRes['data']['game_url'] ?? '';

if (empty($gameUrl)) {
    echo json_encode(['status' => 0, 'msg' => 'Game URL is empty']);
    exit;
}

// ================================================================
// RESPONSE
// ================================================================
echo json_encode([
    'status' => 1,
    'url'    => $gameUrl
]);