<?php

date_default_timezone_set('Asia/Ho_Chi_Minh');
ini_set('display_errors', true);
error_reporting(E_ALL);
define('KEY_FILE', __DIR__ . '/service-account-credentials.json');
require_once __DIR__ . '/../vendor/autoload.php';

/*
10 => 'Chí Tôn Võ Lâm',
18 => 'Võ Lâm Tuyệt Kỹ',
23 => 'Tào Tháo PK',
24 => 'Tam Quốc Phán Xử',
25 => 'Học Viện Thú Cưng',
26 => '3Q VL', // wallet
27 => 'Liên Quân Manga', // wallet
28 => 'Võ Lâm Thiên Hạ'
31 => 'Bá Đao Nhất Kiếm'
36 => 'Chí Tôn 3D'
 */
$game_id = '38';

$client = new Google_Client();
$client->setAuthConfig(KEY_FILE);
$client->setScopes([Google_Service_AndroidPublisher::ANDROIDPUBLISHER]);

$endTime = time() * 1000 - 5 * 60 * 1000;
$startTime = $endTime - 48 * 60 * 60 * 1000;

$service = new Google_Service_AndroidPublisher($client);
$where = ['maxResults' => 100, 'startTime' => $startTime, 'endTime' => $endTime];
$results = $service->purchases_voidedpurchases->listPurchasesVoidedpurchases('vn.kynguyen.thiensu', $where);
process($results);

/** @var Google_Service_AndroidPublisher_VoidedPurchasesListResponse $results */
function process($results)
{
    global $service, $game_id, $where;

    // echo 'COUNT:' . count($results) . PHP_EOL;
    foreach ($results as $result) {

        $last_time = (int)@file_get_contents('last_time_chiton.txt');
        if (!empty($last_time) && $last_time >= $result->voidedTimeMillis) continue;

        // var_dump($result->kind);
        // var_dump(date('Y-m-d H:i:s', (int)($result->purchaseTimeMillis / 1000)));
        // var_dump($result->purchaseToken);
        // var_dump(date('Y-m-d H:i:s', (int)($result->voidedTimeMillis / 1000)));

        $url = sprintf('http://baokim-wallet.viga.mobi/google/refund?game_id=%s&kind=%s&purchaseTimeMillis=%s&purchaseToken=%s&voidedTimeMillis=%s', $game_id, base64_encode($result->kind), $result->purchaseTimeMillis, $result->purchaseToken, $result->voidedTimeMillis);
        file_get_contents($url);
        file_put_contents(__DIR__ . '/last_time_chiton.txt', $result->voidedTimeMillis);
    }

    $page = $results->getTokenPagination();
    if (empty($page) || empty($page->getNextPageToken())) return;

    $results = $service->purchases_voidedpurchases->listPurchasesVoidedpurchases('vn.kynguyen.thiensu', array_merge($where, ['token' => $page->getNextPageToken()]));
    process($results);

}

echo 'DONE';