<?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')) {
    updateOpenOrders0();
    sleep(1);
}


function updateOpenOrders0()
{
    $link = '/v2/spot/pending-order?market_type=SPOT';
    $orders = curlCoinex($link);
    if (isset($orders->message) && $orders->message == 'OK') {
        $openOrders0['orders'] = [];
        foreach ($orders->data as $order) {
            if ($order->market)
                $openOrders0['orders'][] = $order;
        }

        $oldOpenOrders = file_get_contents("data/openOrders.json");
        $oldOpenOrders = json_decode($oldOpenOrders);
        if (isset($oldOpenOrders->orders) && isset($orders->orders))
            foreach ($oldOpenOrders->orders as $order) {
                foreach ($orders->orders as $order2) {
                    if ($order->order_id == $order2->order_id) continue 2;
                }
                cancelOrder($order->order_id, $order->market);
            }

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

//============================================================= done orders

        usleep(400000);

        $link = '/v2/spot/finished-order?market_type=SPOT&page=1&limit=60';
        $doneorders = curlCoinex($link);

        if (isset($doneorders->message) && $doneorders->message == 'OK') {

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


function curlCoinex($request_path, $method = 'GET', $data = [])
{
    global $AccessID;
    global $SecretKey;

    $url = 'https://api.coinex.com' . $request_path;

    $timestamp = round(microtime(true) * 1000);

    if ($method === 'POST' && !empty($data)) {
        $request_path = $request_path . $data;
    }

    $prepared_str = $method . $request_path . $timestamp;


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

    $headers = [
        'Accept: application/json',
        'Content-Type: 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);
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    $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);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return [
            'error' => 'Invalid JSON response: ' . json_last_error_msg(),
            'raw_response' => $response // بازگرداندن پاسخ خام برای بررسی بیشتر
        ];
    }
    return $decoded_response;
}


function cancelOrder($id, $market)
{
    $link = '/v2/spot/cancel-order';
    $method = 'POST';
    $data = json_encode([
        'order_id' => $id,
        'market' => $market,
        'market_type' => 'SPOT'
    ]);

    return curlCoinex($link, $method, $data);
}