<?php
namespace Xxxwraithxxx\PayraCashCryptoPayment;

use Web3\Web3;
use Web3\Utils;
use Web3\Contract;
use Web3\Contracts\Ethabi;
use Web3\Providers\HttpProvider;

if (!defined('ABSPATH')) exit;

class VerifyPayment
{
    public function get_order_status($order_prefix_id, $merchant_id, $rpc_url, $payra_gateway_contract_address)
    {
        try {
            $provider = new HttpProvider($rpc_url, 5);
            $web3 = new Web3($provider);
            $ethabi = new Ethabi;

            $payra_abi = file_get_contents(dirname(__DIR__) . '/contracts/payraABI.json');
            $contract = new Contract($web3->provider, $payra_abi);

            $result_value = null;
            $done = false;

            //$user_data_addr = null;
            $contract->at($payra_gateway_contract_address)->call('getRegistryDetails', function ($err, $res) use ($contract, $merchant_id, $order_prefix_id, &$result_value, &$done) {
                if ($err !== null) {
                    error_log("Contract error: " . $err->getMessage());
                    $done = true;
                    return;
                }

                if (!empty($res['userData'])) {
                    $contract->at($res['userData'])->call('getOrderDetails', $merchant_id, $order_prefix_id, function ($err, $resOrder) use (&$result_value, &$done) {
                        if ($err !== null) {
                            error_log("OrderDetails Error: " . $err->getMessage());
                            $done = true;
                            return;
                        }
                        
                        $result_value = [
                            "paid"      => (bool)$resOrder['paid'],
                            "token"     => $resOrder['token'],
                            "amount"    => $resOrder['amount']->toString(),
                            "fee"       => $resOrder['fee']->toString(),
                            "timestamp" => $resOrder['timestamp']->toString(),
                        ];

                        $done = true;
                    });
                } else {
                    $done = true;
                }
            });

            $timeout = 0;
            while (!$done && $timeout < 10000) {
                usleep(1000);
                $timeout++;
            }

            return $result_value;

        } catch (\Throwable $e) {
            error_log("RPC URLS error: " . $e->getMessage());
            return $result_value = ["paid" => null];
        }
    }

}
