<?php

namespace App\Game\Services;

use App\Util;
use GuzzleHttp\Client;

class PgSoftService
{
    protected $client;
    protected $baseUrl;
    public $secretKey;

    public $token;

    public $salt;

    public function __construct()
    {
        //N-cf_29a0
        $this->client = new Client();
        $this->baseUrl = "https://api.pg-bo.co";
        $this->secretKey = "29a03bca22da48b0806b5854e59148c8";
        $this->token = "N-cfa64541-6c36-4507-b221-a7128d7d5364";
        $this->salt = "d1a3466f5d5e46ad9f97069bc63b1b0a";
//        $this->client = new Client();
//        $this->baseUrl = "https://api.pg-bo.me";
//        $this->secretKey = "98d2e7bd8d6a49588a68ee25f0072e4f";
//        $this->token = "I-226f37ece4604f19a926c0cd709a995c";
//        $this->salt = "ec064b935d794d49b8a31062420d451a";
    }


    function generateGUID() {
        // Generate 16 random bytes
        $data = openssl_random_pseudo_bytes(16);

        // Set the version to 4 (random UUID)
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
        // Set the variant to DCE 1.1
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);

        // Format the byte data into a GUID string
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }


    // 发送POST请求
    protected function postRequest($endpoint, $data,$json = true)
    {
        $post = http_build_query($data);
        $headers = ['Content-Type' => 'application/x-www-form-urlencoded'];
        $rs = Util::curlPost2($this->baseUrl . $endpoint.'?trace_id='.$this->generateGUID(),$post,true,$headers);
        Util::WriteLog('24680_pg_rs', $post);
        Util::WriteLog('24680_pg_rs', $rs);
        if(!$json){
            return $rs;
        }
        return json_decode($rs, true);
    }

    public function getGamesList($lang='pt',$currency=null)
    {
        $currency=$currency||env('CONFIG_24680_CURRENCY');
        $data = [
            'operator_token' => $this->token,
            'secret_key' => $this->secretKey,
            'currency' => $currency,
            'language' => $lang,
            'status' => 1
        ];
        return $this->postRequest('/external/Game/v2/Get',$data);
    }

    public function getLaunchURLHTML($gameId,$playerId,$ip='',$lang='zh')
    {
        ///external-game-launcher/api/v1/GetLaunchURLHTML
        $extraArgs = [
            'btt' => 1,
            'ops' => $playerId,
            'l' => $lang,
        ];
        $data = [
            'operator_token' => $this->token,
            'path' => "/{$gameId}/index.html",
            'extra_args' => http_build_query($extraArgs),
            'url_type' => 'game-entry',
            'client_ip' => $ip
        ];
        return $this->postRequest('/external-game-launcher/api/v1/GetLaunchURLHTML',$data,false);
    }

    public function verifySession($token,$secretKey)
    {
        return $token == $this->token && $secretKey == $this->secretKey;
    }
}

