<?php

//die();
ini_set("memory_limit", "-1");
set_time_limit(0);

error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'functionsT.php';

$time = time();
$min = date('i');
while ($min == date('i')) {
    $walletsJson = updateWallets();
    $walletsJson = json_encode($walletsJson, JSON_PRETTY_PRINT);

    $myfile = fopen("data/wallets.json", "w") or die("Unable to open file!");
    if (flock($myfile, LOCK_EX)) {
        fwrite($myfile, $walletsJson);
        flock($myfile, LOCK_UN);
    }
    fclose($myfile);
    sleep(1);
}

function updateWallets()
{
    global $AccessID;
    global $SecretKey;

    $method = 'GET';
    $request_path = '/v2/assets/spot/balance';
    $url = 'https://api.coinex.com' . $request_path;

    $timestamp = round(microtime(true) * 1000);
    $prepared_str = $method . $request_path . $timestamp;

    $signed_str = hash_hmac('sha256', $prepared_str, $SecretKey);
    $signed_str = strtolower($signed_str);

    $headers = [
        'Accept: application/json',
        'X-COINEX-KEY: ' . $AccessID,
        'X-COINEX-SIGN: ' . $signed_str,
        'X-COINEX-TIMESTAMP: ' . $timestamp
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);

    if ($response === false) {
        $error = curl_error($ch);
        curl_close($ch);
        return ['error' => $error];
    }
    curl_close($ch);
    $decoded_response = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return ['error' => 'Invalid JSON response'];
    }
    return $decoded_response;
}


