<?php

class fiver
{
    private $agent;
    private $token;
    private $url;

    public function __construct($call)
    {
        $cfg = $this->getApiConfig($call);

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

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

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

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

    public function agentbalance()
    {
        $param = [
            'method' => 'money_info',
            'agent_code' => $this->agent,
            'agent_token' => $this->token
        ];

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

    public function allUserBalances()
    {
        $param = [
            'method' => 'money_info',
            'agent_code' => $this->agent,
            'agent_token' => $this->token,
            'all_users' => true,
        ];

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

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

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

    public function withdraw($username, $amount, $agentSign = null)
    {
        $agentSign = trim((string)($agentSign ?? ''));
        if ($agentSign === '') {
            $agentSign = $this->makeAgentSign('WD', $username);
        }

        $param = [
            'method' => 'user_withdraw',
            'agent_code' => $this->agent,
            'agent_token' => $this->token,
            'user_code' => $username,
            'amount' => $amount,
            'agent_sign' => $agentSign
        ];

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

    public function resetBalance($username)
    {
        $param = [
            'method' => 'user_withdraw_reset',
            'agent_code' => $this->agent,
            'agent_token' => $this->token,
            'user_code' => $username,
        ];

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

    public function resetAllBalance()
    {
        $param = [
            'method' => 'user_withdraw_reset',
            'agent_code' => $this->agent,
            'agent_token' => $this->token,
            'all_users' => true,
        ];

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

    public function controlUsersRtp(array $userCodes, int $rtp)
    {
        $userCodes = array_values(array_filter(array_map('strval', $userCodes), static function ($userCode) {
            return trim($userCode) !== '';
        }));

        $param = [
            'method' => 'control_users_rtp',
            'agent_code' => $this->agent,
            'agent_token' => $this->token,
            'user_codes' => json_encode($userCodes),
            'rtp' => $rtp,
        ];

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

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

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

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

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

    public function callList($provider, $gamecode)
    {
        $param = [
            'method' => 'call_list',
            'agent_code' => $this->agent,
            'agent_token' => $this->token,
            'provider_code' => $provider,
            'game_code' => $gamecode
        ];

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

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

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

    public function callCancel($callid)
    {
        $param = [
            'method' => 'call_cancel',
            'agent_code' => $this->agent,
            'agent_token' => $this->token,
            'call_id' => $callid
        ];

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

    public function callHistory()
    {
        $param = [
            'method' => 'call_history',
            'agent_code' => $this->agent,
            'agent_token' => $this->token,
            'offset' => '0',
            'limit' => '100'
        ];

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

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

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

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

        $url = $this->url;
        return $this->connect($url, $param);
    }
    private function getApiConfig($call)
    {
        $q = mysqli_query(
            $call,
            "SELECT api_url, agent_code, secret_key
             FROM tb_api_config
             WHERE api_name='NEXUSGGR'
             LIMIT 1"
        );
        if (!$q || mysqli_num_rows($q) === 0) {
            throw new Exception('NEXUSGGR API CONFIG NOT FOUND');
        }
        return mysqli_fetch_assoc($q);
    }

    private function makeAgentSign($prefix, $username)
    {
        $cleanUser = preg_replace('/[^A-Za-z0-9_-]/', '', (string)$username);
        $cleanUser = substr($cleanUser ?: 'USER', 0, 20);

        try {
            $random = bin2hex(random_bytes(6));
        } catch (Throwable $exception) {
            $random = str_replace('.', '', uniqid('', true));
        }

        return strtoupper((string)$prefix) . '_' . $cleanUser . '_' . date('YmdHis') . '_' . $random;
    }

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

        $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_ENCODING, 'gzip');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);

        $res = curl_exec($ch);
        if ($res === false) {
            $error = curl_error($ch);
            curl_close($ch);

            return [
                'status' => 0,
                'msg' => $error !== '' ? $error : 'NEXUSGGR_CURL_ERROR',
            ];
        }
        curl_close($ch);

        $decoded = json_decode($res, true);
        if (!is_array($decoded)) {
            return [
                'status' => 0,
                'msg' => 'NEXUSGGR_INVALID_JSON_RESPONSE',
            ];
        }

        return $decoded;
    }
}
?>
