<?php
if (substr(PHP_SAPI_NAME(), 0, 3) !== 'cli') {
    die("The program runs only in CLI mode!");
}
date_default_timezone_set('UTC');
$sid =$lid =1;
include_once dirname(__FILE__) . "/crontab.inc.php";
include_once dirname(__FILE__) . "/../com.php";
set_time_limit(0);
$tb = otable::vipPaymentLog();
$now = time();
$date = empty($argv[1]) ? date('Ymd', $now -  86400) : $argv[1];

$dirName = __DIR__. "/../deBUG/logs2/{$date}/";
$logFile = $dirName. "vip.log";
if(file_exists($logFile)){
    echo $logFile . ':';
    $insertArr = [];
    $f = fopen($logFile, 'r');
    while(!feof($f)){
        $line = fgets($f);
        $line = @json_decode($line, true);
        if(empty($line['message']['data']))continue;

        $line['msg-data'] = @base64_decode($line['message']['data']);
        $line['msg-data'] = @json_decode($line['msg-data'], true);
        $insertArr[] = [
            'uid' => $line['msg-data']['uid'] ?? 0,
            'data' => json_encode($line),
            'purchaseToken' => $line['msg-data']['subscriptionNotification']['purchaseToken'] ?? ($line['msg-data']['oneTimeProductNotification']['purchaseToken'] ?? ''),
            'datetime' => empty($line['msg-data']['eventTimeMillis']) ? 0 : intval($line['msg-data']['eventTimeMillis']/1000),
        ];
    }
    fclose($f);
    $sql = funs::db_intsertArrSQL($tb, ['uid','data','purchaseToken','datetime'], $insertArr);
    $res = oo::commonOprDb('api_log')->query($sql);
    var_dump($res);
    echo PHP_EOL;
}

$logFile = $dirName. "paymentLog.log";
if(file_exists($logFile)) {
    echo $logFile . ':';
    $insertArr = [];
    $f = fopen($logFile, 'r');
    while (!feof($f)) {
        $line = fgets($f);
        $arr = @json_decode($line, true);
        if (empty($arr)) continue;

        if(!empty($arr['actExtraData']) && is_string($arr['actExtraData'])){
            $arr['actExtraData'] = @json_decode($arr['actExtraData'], true);
        }
        $arr['signedData'] = @json_decode(@base64_decode($arr['signedData']), true);
        $arr['extraData'] = @json_decode(@base64_decode($arr['extraData']), true);
        $insertArr[] = [
            'uid' => $arr['uid'] ?? 0,
            'data' => json_encode($arr),
            'purchaseToken' => $arr['subscriptionNotification']['purchaseToken'] ?? '',
            'datetime' => empty($arr['time']) ? 0 : intval($arr['time'] / 1000),
        ];
    }
    fclose($f);
    $sql = funs::db_intsertArrSQL($tb, ['uid','data','purchaseToken','datetime'], $insertArr);
    $res = oo::commonOprDb('api_log')->query($sql);
    var_dump($res);
    echo PHP_EOL;
}