<?php
//die();
date_default_timezone_set("Asia/Tehran");
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'functions.php';
$ch = null;
$symbols = [];

$min = date('i');
do {
    $symbols = readJson('data/symbols.json');
    if (!$symbols) sleep(2);
    else
        break;
} while ($min == date('i'));
$chunkSize = 40;
$totalChunks = ceil(count($symbols) / $chunkSize);
for ($i = 0; $i < $totalChunks; $i++) {
    $chunk = array_slice($symbols, $i * $chunkSize, $chunkSize);
    $data = getOHLCData($chunk);
    usleep(300000);
}

//========================================================== functions


function readJson($path)
{
    if (!filesize($path))
        usleep(300000);

    if (!filesize($path))
        return [];

    $file = fopen($path, "r");
    $response = fread($file, filesize($path));
    fclose($file);

    return json_decode($response);
}

function getOHLCData($symbols)
{
    $multiCurl = curl_multi_init();
    $curlHandles = [];
    foreach ($symbols as $symbol) {

//        $symbolFormatted = str_replace(['100K_', '1M_', '1B_'], ['', '', '1M'], $symbol);

        $url = 'api.coinex.com/v2/spot/kline?market=' . $symbol . '&limit=180&period=1min';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20); // تنظیم تایم اوت
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // غیرفعال کردن SSL (در صورت نیاز)

        $curlHandles[$symbol] = $ch;
        curl_multi_add_handle($multiCurl, $ch);
    }

    $running = null;
    do {
        curl_multi_exec($multiCurl, $running);
        curl_multi_select($multiCurl);
    } while ($running > 0);

    foreach ($symbols as $market) {
        if (isset($curlHandles[$market])) {
            $response = curl_multi_getcontent($curlHandles[$market]);

            // بررسی وضعیت HTTP
            $httpCode = curl_getinfo($curlHandles[$market], CURLINFO_HTTP_CODE);
            if ($httpCode != 200) {
                echo "HTTP Error Code: $httpCode for $market\n";
                $error = curl_error($curlHandles[$market]);
                $errno = curl_errno($curlHandles[$market]);
                echo "CURL Error: $error (Error Code: $errno)\n";
                curl_multi_remove_handle($multiCurl, $curlHandles[$market]);
                curl_close($curlHandles[$market]);
                continue;
            }

            if ($response) {
                $jsonData = json_decode($response, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $filePath = 'data/CoinexOHLC/' . $market . '.json';
                    file_put_contents($filePath, json_encode($jsonData, JSON_PRETTY_PRINT));
//                    echo " $market \n";
                } else {
                    echo "Failed to fetch valid JSON data for $market.\n";
                }
            } else {
                echo "No response for $market.\n";
            }

            curl_multi_remove_handle($multiCurl, $curlHandles[$market]);
            curl_close($curlHandles[$market]);
        } else {
            echo "Curl handle for $market not found.\n";
        }

    }

    curl_multi_close($multiCurl);
}
