<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Ambil agent & token otomatis dari database
include_once __DIR__ . "/../../function/connect.php"; // sesuaikan path koneksi

$cek = mysqli_query($koneksi, "SELECT * FROM tb_integrasi LIMIT 1");
if ($cek && mysqli_num_rows($cek) > 0) {
    $data = mysqli_fetch_assoc($cek);
    $autoAgent = $data['agent_code'] ?? '';
    $autoToken = $data['token_code'] ?? '';
} else {
    $autoAgent = '';
    $autoToken = '';
}

class fiver
{
    public $agen  = "";
    public $token = "";
    public $url   = "https://api.ngaming.xyz";

    public function __construct($agent='', $token='') {
        $this->agen  = $agent;
        $this->token = $token;
    }
    
    public function create($username)
    {
        $param = [
            'method' => 'user_create',
            'agent_code' => $this->agen,
            'agent_token' => $this->token,
            'user_code' => $username
        ];

        $url = $this->url;
        return $this->sg_connect($url, $param);
    }

    public function userbalance($username)
    {
        $param = [
            'method' => 'money_info',
            'agent_code' => $this->agen,
            'agent_token' => $this->token,
            'user_code' => $username
        ];

        $url = $this->url;
        return $this->sg_connect($url, $param);
    }
    public function agentbalance()
    {
        $param = [
            'method' => 'money_info',
            'agent_code' => $this->agen,
            'agent_token' => $this->token
        ];

        $url = $this->url;
        return $this->sg_connect($url, $param);
    }

    public function deposit($username, $amount)
    {
        $param = [
            'method' => 'user_deposit',
            'agent_code' => $this->agen,
            'agent_token' => $this->token,
            'user_code' => $username,
            'amount' => $amount
        ];

        $url = $this->url;
        return $this->sg_connect($url, $param);
    }

    public function withdraw($username, $amount)
    {
        $param = [
            'method' => 'user_withdraw',
            'agent_code' => $this->agen,
            'agent_token' => $this->token,
            'user_code' => $username,
            'amount' => $amount
        ];

        $url = $this->url;
        return $this->sg_connect($url, $param);
    }
    public function resetBalance()
    {
        $param = [
            'method' => 'user_withdraw_reset',
            'agent_code' => $this->agen,
            'agent_token' => $this->token,
            'all_users' => true
        ];

        $url = $this->url;
        return $this->sg_connect($url, $param);
    }

    public function gamelist($provider)
    {
        $param = [
            'method' => 'game_list',
            'agent_code' => $this->agen,
            'agent_token' => $this->token,
            'provider_code' => $provider
        ];

        $url = $this->url;
        return $this->sg_connect($url, $param);
    }

    public function callPlayer()
    {
        $param = [
            'method' => 'call_players',
            'agent_code' => $this->agen,
            'agent_token' => $this->token
        ];

        $url = $this->url;
        return $this->sg_connect($url, $param);
    }

    public function providerlist($provider, $gamecode, $username)
    {
        $param = [
            'method' => 'provider_list',
            'agent_code' => $this->agen,
            'agent_token' => $this->token,
            'provider_code' => $provider,
            'game_code' => $gamecode,
            'user_code' => $username
        ];

        $url = $this->url;
        return $this->sg_connect($url, $param);
    }

    public function callApply($provider, $gamecode, $username, $rtp, $type)
    {
        $param = [
            'method' => 'call_apply',
            'agent_code' => $this->agen,
            'agent_token' => $this->token,
            'provider_code' => $provider,
            'game_code' => $gamecode,
            'user_code' => $username,
            'call_rtp' => $rtp,
            'call_type' => $type,
        ];

        $url = $this->url;
        return $this->sg_connect($url, $param);
    }

    public function opengame($username, $gamecode, $game_provider, $type = '')
{
    $param = [
        'method' => 'game_launch',
        'agent_code' => $this->agen,
        'agent_token' => $this->token,
        'user_code' => $username,
        'game_code' => $gamecode,
        'provider_code' => $game_provider,
        'lang' => 'en',
    ];

    // 🔥 HANDLE SEMUA GAME TYPE
    if (!empty($type)) {

        // khusus sportbook
        if ($type == 'sportbook') {
            $param['type'] = 'sportbook';
        } 

        // selain sportbook → pakai game_type
        else {
            $param['game_type'] = strtolower($type);
        }
    }

    $url = $this->url;
    return $this->sg_connect($url, $param);
}

    public function historyPlay($username, $type, $start, $end, $page, $perpage)
    {
        $param = [
            'method' => 'get_game_log',
            'agent_code' => $this->agen,
            'agent_token' => $this->token,
            'user_code' => $username,
            'game_type' => $type,
            'start' => $start,
            'end' => $end,
            'page' => $page,
            'perPage' => $perpage,
        ];

        $url = $this->url;
        return $this->sg_connect($url, $param);
    }


    private function sg_connect($url, $postArray) {
        $jsonData = json_encode($postArray);
        $headerArray = ['Content-Type: application/json'];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.47 Safari/537.36');
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

        $res = curl_exec($ch);
        curl_close($ch);

        return json_decode($res, true);
    }
}
// Inisialisasi $SGX dengan agent/token otomatis
$SGX = new fiver($autoAgent, $autoToken);

// Fungsi untuk agent.php
function sendIntegration($agent_code, $token_code)
{
    global $SGX;

    if (empty($agent_code) || empty($token_code)) {
        return ['status'=>'error','message'=>'Agent code atau token tidak boleh kosong.'];
    }

    $SGX->agen  = $agent_code;
    $SGX->token = $token_code;

    $test = $SGX->agentbalance();
    if (!$test || !is_array($test)) {
        return ['status'=>'error','message'=>'Tidak ada respon dari server API.'];
    }

    $status = strtoupper(trim($test['status'] ?? 'UNKNOWN'));
    $msg    = trim($test['msg'] ?? '');

    if ($status === 'SUCCESS' || stripos($msg, 'SUCCESS') !== false) {
        return ['status'=>'success','message'=>'Terhubung ke API dengan sukses. (' . $msg . ')'];
    } else {
        return ['status'=>'error','message'=>'Gagal terhubung ke API: ' . $msg];
    }
}
?>