<?php

function curl_post($url, $data = [], $header = []){
    $ch = curl_init($url);
    $options = [
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_TIMEOUT => 15
    ];
    curl_setopt_array($ch, $options);
    $result = curl_exec($ch);
    curl_close($ch);
    return json_decode($result, true);
}

function faucet_alert($messages, $type){
    foreach($messages as $message){
        $icon = ($type == "danger")? "<i class='fa fa-exclamation-triangle'></i>" : (($type == "success")? "<i class='fa fa-check-circle'></i>" : "<i class='fa fa-info-circle'></i>");
        $alert = '<div class="alert alert-'. $type .'">'.$icon.' '. $message .'
                </div>';
        return $alert;
    }
}

function captcha($captcha, $captcha_key){

    $test_key = '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI';
    switch($captcha){
        case 'recaptcha':
            return '<div class="g-recaptcha d-flex justify-content-center my-3" data-sitekey="'. $captcha_key .'"></div>
                    <script src="https://www.google.com/recaptcha/api.js" async defer></script>';
            break;
        case 'hcaptcha':
            return '<div class="h-captcha d-flex justify-content-center my-3" data-sitekey="'. $captcha_key .'"></div>
                    <script src="https://hcaptcha.com/1/api.js" async defer></script>';
            break;
        case 'turnstile':
            return '<div class="cf-turnstile d-flex justify-content-center my-3" data-sitekey="'. $captcha_key .'"></div>
                    <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>';
            break;
        default:
            return '<div class="g-recaptcha d-flex justify-content-center my-3" data-sitekey="'. $test_key .'"></div>
                    <script src="https://www.google.com/recaptcha/api.js" async defer></script>';
    }
}

function verify_recaptcha($captcha, $captcha_secret){

    $captcha_url = 'https://www.google.com/recaptcha/api/siteverify';
    $captcha_data = ['secret' => $captcha_secret, 'response' => $captcha];

    return curl_post($captcha_url, $captcha_data);
}

function verify_hcaptcha($captcha, $captcha_secret){

    $captcha_url = 'https://hcaptcha.com/siteverify';
    $captcha_data = ['secret' => $captcha_secret, 'response' => $captcha];

    return curl_post($captcha_url, $captcha_data);
}

function verify_turnstile($captcha, $captcha_secret){

    $captcha_url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
    $captcha_data = ['response' => $captcha, 'secret' => $captcha_secret];

    return curl_post($captcha_url, $captcha_data);
}

function VpnIpApi($ipAddress){
    
    $url = 'http://ip-api.com/json/' . $ipAddress . '?fields=status,message,proxy,query';
    $data = curl_post($url);

    if (!empty($data)) {
        if ($data['status'] == 'success') {
            return $data['proxy'];
        } else {
            return false;
        }
    } else {
        return false;
    }
}
    
function VpnProxyCheck($ipAddress, $token){
    $url = "https://proxycheck.io/v2/". $ipAddress ."?key=". $token;
    $data = curl_post($url);

    return isset($data[$ipAddress]) && $data[$ipAddress]['proxy'] == 'yes';
}

function VpnIpHub($ipAddress, $apiKey){
    $url = "https://v2.api.iphub.info/ip/$ipAddress";
    $header = ['X-Key' => $apiKey,];
    $data = curl_post($url, [], $header);

    return $data['block'] == 1; 
}

function faucetpay($address, $ip_address, $amount, $api, $currency, $referral = false){
    $param = array(
        'api_key' => $api,
        'amount' => $amount,
        'to' => $address,
        'currency' => $currency,
        'ip_address' => $ip_address,
        'referral' => $referral
    );
    $url = 'https://faucetpay.io/api/v1/send';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, count($param));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    $result = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $result;
}

function zexpay($key, $amount, $to, $currency){
    $url = 'https://zexpay.io/api/v1/send-payment/';
    $fields = array(
        'amount' => $amount,
        'user' =>$to,
        'crypto' =>$currency
    );
    $header =  [
        'Content-Type: application/json',
        'api-key: '.$key
    ];
    
    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_POST, 1);
    curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //execute post
    $json = curl_exec($ch);
    $result = json_decode($json, true);
    //close connection
    curl_close($ch);
    log_message('debug', 'ZexPay Debug - Result: ' . json_encode($result));
    log_message('debug', 'ZexPay Debug - JSON: ' . json_encode($fields));
    return $result;
}
function currency_list($wallet = 'faucetpay'){
    if($wallet == 'faucetpay'){
        $Currencies = [
            "BTC" => "Bitcoin",
            "ETH" => "Ethereum",
            "DOGE" => "Dogecoin",
            "LTC" => "Litecoin",
            "BCH" => "Bitcoin Cash",
            "DASH" => "Dash",
            "DGB" => "DigiByte",
            "TRX" => "Tron",
            "USDT" => "Tether",
            "FEY" => "Feyorra",
            "ZEC" => "Zcash",
            "BNB" => "Binance Coin",
            "SOL" => "Solana",
            "XRP" => "Ripple",
            "MATIC" => "Polygon",
            "ADA" => "Cardano",
            "TON" => "Toncoin",
            "XLM" => "Stellar",
            "USDC" => "USD Coin",
            "XMR" => "Monero",
            "TARA" => "Taraxa",
            "TRUMP" => "official-trump",
            "PEPE" => "Pepe",
        ];
    }
    else if($wallet == 'zexpay'){
        $Currencies = [
            "BTC" => "Bitcoin",
            "ETH" => "Ethereum",
            "DOGE" => "Dogecoin",
            "LTC" => "Litecoin",
            "BCH" => "Bitcoin Cash",
            "TRX" => "Tron",
            "USDT" => "Tether",
            "BNB" => "Binance Coin",
            "SOL" => "Solana",
            "XRP" => "Ripple",
            "MATIC" => "Polygon",
            "GRAM" => "the-open-network",
            "USDC" => "USD Coin",
            "SHIB" => "Shiba-inu",
            "BONK" => "Bonk",
            "TRUMP" => "official-trump",
            "SUI" => "Sui",
            "FLOKI" => "Floki",
            "PEPE" => "Pepe",
            "BABYDOGE" => "baby-doge-coin",
            "DASH" => "dash",
            "DGB" => "digibyte",
            "ADA" => "cardano",
            "ATOM" => "cosmos"
        ];
    }
    return $Currencies;
}

function timeSpan($timestamp) {
    $currentTime = time();
    $timeDiff = $currentTime - strtotime($timestamp);

    $seconds = $timeDiff;
    $minutes = round($timeDiff / 60);
    $hours = round($timeDiff / 3600);
    $days = round($timeDiff / 86400);
    $weeks = round($timeDiff / 604800);
    $months = round($timeDiff / 2419200);
    $years = round($timeDiff / 29030400);

    if ($seconds <= 60) {
        return "$seconds seconds ago";
    } elseif ($minutes <= 60) {
        return "$minutes minutes ago";
    } elseif ($hours <= 24) {
        $remainingMinutes = $minutes % 60;
        if ($remainingMinutes > 0) {
            return "$hours hours $remainingMinutes minutes ago";
        }
        return "$hours hours ago";
    } elseif ($days <= 7) {
        $remainingHours = $hours % 24;
        if ($remainingHours > 0) {
            return "$days days $remainingHours hours ago";
        }
        return "$days days ago";
    } elseif ($weeks <= 4) {
        $remainingDays = $days % 7;
        if ($remainingDays > 0) {
            return "$weeks weeks $remainingDays days ago";
        }
        return "$weeks weeks ago";
    } elseif ($months <= 12) {
        $remainingWeeks = $weeks % 4;
        if ($remainingWeeks > 0) {
            return "$months months $remainingWeeks weeks ago";
        }
        return "$months months ago";
    } else {
        $remainingMonths = $months % 12;
        if ($remainingMonths > 0) {
            return "$years years $remainingMonths months ago";
        }
        return "$years years ago";
    }
}

function getprice($currency){
    $cache = service('cache');
    
    // Convert currency name to CoinGecko coin ID
    $coinId = strtolower(str_replace(' ', '-', $currency));
    
    // Special case for Binance Coin
    if($currency == "Binance Coin"){
        $coinId = "binancecoin";
    }

    
    // Check cache first (5 minute cache)
    if(empty($cache->get($coinId)) || $cache->get($coinId."-last") < (time()-300)){
        $url = 'https://api.coingecko.com/api/v3/simple/price?ids=' . $coinId . '&vs_currencies=usd';
        
        $context = stream_context_create([
            'http' => [
                'timeout' => 10,
                'user_agent' => 'Mozilla/5.0 (compatible; CryptoApp/1.0)'
            ]
        ]);
        
        $response = @file_get_contents($url, false, $context);
        
        if($response !== false){
            $data = json_decode($response, true);
            
            // Check if we got valid data and the coin exists
            if(isset($data[$coinId]) && isset($data[$coinId]['usd'])){
                $price = $data[$coinId]['usd'];
                $cache->save($coinId, $price, 86400);
                $cache->save($coinId."-last", time(), 86400);
                return $price;
            }
        }
        
    }
    
    $cachedPrice = $cache->get($coinId) ?: 0;
    log_message('debug', 'GetPrice Debug - Using cached price: ' . $cachedPrice);
    return $cachedPrice;
}

function TrimTrailingZeroes($nbr) {
    return strpos($nbr,'.')!==false ? rtrim(rtrim($nbr,'0'),'.') : $nbr;
}

function format_amount($amount, $decimal){
    $formatted = number_format($amount, $decimal, '.', ',');
    return TrimTrailingZeroes($formatted);
}

function check_update($product, $version){
    $cache = service('cache');
    if(!$cache->get('update_check') || $cache->get('update_check_last') < (time()-86400)){
        $url = 'https://altercode.net/api/update_check.php?product='.$product;
        $response = json_decode(file_get_contents($url), true);
        if($response['code'] != '200'){
            return false;
        }else{
            $cache->save('update_check', $response, 86400);
            $cache->save('update_check_last', time(), 86400);
        }
    }
    $data = $cache->get('update_check');
    if(version_compare($version, $data['version'], '<')){
        return true;
    }
    return false;
}

?>