<?php

namespace App\Game\Services;

use App\Util;
use GuzzleHttp\Client;

class TonGiftsService
{
    protected $client;
    protected $baseUrl;
    public $secretKey;
    public $id;

    public function __construct()
    {
        $this->client = new Client();
        $this->baseUrl = "https://HOST";
        $this->secretKey = "";
        $this->id = "";
    }


    public function register($name,$email)
    {
        return $this->postRequest('/api/merchants/register',['name' => $name,'email' => $email]);
    }

    public function updateTask($userIds,$taskId,$status){
        $data = [
            'userIds' => $userIds,
            'taskId' => $taskId,
            'status' => $status
        ];

        return $this->postRequest('/api/open/updateTask',$data);
    }


    // 发送POST请求
    protected function postRequest($endpoint, $data,$needSignature = true)
    {

        if($needSignature){
            if(!isset($data['t'])){
                $data['t'] = time();
            }
            $data['sign'] = $this->_generateSignature($data);
            $data['k'] = $this->id;
        }
        $post = json_encode($data);
        $headers = ['Content-Type' => 'application/json'];
        $rs = Util::curlPost2($this->baseUrl . $endpoint,$post,true,$headers);
        Util::WriteLog('TonGIfts', $post);
        Util::WriteLog('TonGIfts', $rs);

        return json_decode($rs, true);
    }


    private function _generateSignature($params)
    {
        ksort($params);
        $queryString = '';
        foreach ($params as $key => $value) {
            if(is_array($value)){
                $value = json_encode($value);
            }
            $queryString .= $key . '=' . $value . '&';
        }
        $queryString = rtrim($queryString, '&');
        $secretKey = $this->secretKey;
        return hash_hmac('sha256', $queryString, $secretKey);

    }



}

