<?php
namespace Kanews;

class Currencies {

  private static $instance;
  private static $preparedData = null;
  private static $optionCache = array();

  public static function getInstance() {
    if ( null === static::$instance ) {
      static::$instance = new static();
    }
    return static::$instance;
  }

  var $option = 'Kanews\Currencies';

  private static function get_option_cached($key, $default = null) {
    if(!array_key_exists($key, self::$optionCache)) {
      self::$optionCache[$key] = kanews_get_option($key, $default);
    }

    return self::$optionCache[$key];
  }

  private static function decode_local_json($path) {
    $contents = get_local_file_contents($path);
    if(empty($contents))
    return array();

    $decoded = json_decode($contents, true);
    return (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) ? $decoded : array();
  }

  private static function safe_number($array, $key, $default = 0) {
    return ( isset($array[$key]) && is_numeric($array[$key]) ) ? $array[$key] : $default;
  }

  private static function fetch_coingecko_crypto($index) {
    if( !function_exists('kanews_crypto_data') ) {
      return array();
    }

    $raw = kanews_crypto_data($index);
    if( empty($raw) ) {
      return array();
    }

    $decoded = json_decode($raw, true);
    if( json_last_error() !== JSON_ERROR_NONE || !is_array($decoded) ) {
      return array();
    }

    $mapped = array();
    foreach($decoded as $coin) {
      if( !is_array($coin) ) {
        continue;
      }
      $symbol = isset($coin['symbol']) ? strtoupper($coin['symbol']) : '';
      if( empty($symbol) ) {
        continue;
      }
      $price         = self::safe_number($coin, 'current_price');
      $high24        = self::safe_number($coin, 'high_24h');
      $low24         = self::safe_number($coin, 'low_24h');
      $changePercent = self::safe_number($coin, 'price_change_percentage_24h');
      $changeValue   = self::safe_number($coin, 'price_change_24h');

      $mapped[$symbol] = array(
        'price'        => $price,
        'high24h'      => $high24,
        'high_24h'     => $high24,
        'low_24h'      => $low24,
        'change24h'    => $changePercent,
        'change_value' => $changeValue,
        'market_cap'   => self::safe_number($coin, 'market_cap'),
        'total_volume' => self::safe_number($coin, 'total_volume'),
      );
    }

    return $mapped;
  }

  private static function fetch_crypto_data($index) {
    if( $coingecko = self::fetch_coingecko_crypto($index) ) {
      return $coingecko;
    }

    $response = wp_remote_get(KAN_API_URL2."/crypto/?currency=$index&api_key=kanews-theme");
    if (is_wp_error($response)) {
      return array();
    }

    $body = wp_remote_retrieve_body($response);
    $decoded = json_decode($body, true);
    if( json_last_error() !== JSON_ERROR_NONE || !is_array($decoded) ) {
      return array();
    }

    if( isset($decoded['data']) && is_array($decoded['data']) ) {
      return $decoded['data'];
    }

    return $decoded;
  }

  private static function array_get($source, $keys, $default = 0) {
    $value = $source;
    foreach((array) $keys as $key) {
      if(!is_array($value) || !isset($value[$key])) {
        return $default;
      }
      $value = $value[$key];
    }
    return is_numeric($value) ? $value : $value;
  }

  private static function to_object($data) {
    $object = new \stdClass();
    foreach($data as $key => $item) {
      $object->{$key} = (object) $item;
    }
    return $object;
  }

  public static function update() {
    if( self::$preparedData !== null ) {
      return self::$preparedData;
    }

    $transient_name = 'kanews-currencies';
    if( ! $post_data = get_transient( $transient_name ) ){

      $currencies = self::decode_local_json(KAN_TEMPLATE_PATH."/inc/api/currencies/currencies.json");
      $gold = self::decode_local_json(KAN_TEMPLATE_PATH."/inc/api/gold/gold.json");
      
      $index = self::get_option_cached('crypto-page-index', 'try');
      $crypto_data = self::fetch_crypto_data($index);

      $post_data = array(
        'ukoil' => array(
          'name' => esc_html__( 'Petrol', 'kanews' ),
          'full' => 'Brent Petrol',
          'value' => self::array_get($currencies, array('data','BRENT','Selling')),
          'shutdown' => self::array_get($currencies, array('data','BRENT','Buying')),
          'change_percent' => self::array_get($currencies, array('data','BRENT','Change')),
          'change_value' => 0,
        ),
        'ise-100' => array(
          'name' => 'BIST',
          'full' => 'Bist 100',
          'value' => self::array_get($currencies, array('data','BIST','Selling')),
          'shutdown' => self::array_get($currencies, array('data','BIST','Buying')),
          'change_percent' => self::array_get($currencies, array('data','BIST','Change')),
          'change_value' => 0,  
        ),
        'usd' => array(
          'name' => 'USD',
          'full' => 'Amerikan Doları',
          'value' => self::array_get($currencies, array('data','USD','Selling')),
          'shutdown' => self::array_get($currencies, array('data','USD','Buying')),
          'change_percent' => self::array_get($currencies, array('data','USD','Change')),
          'change_value' => 0,  
        ),
        'euro' => array(
          'name' => 'EURO',
          'full' => 'Euro',
          'value' => self::array_get($currencies, array('data','EUR','Selling')),
          'shutdown' => self::array_get($currencies, array('data','EUR','Buying')),
          'change_percent' => self::array_get($currencies, array('data','EUR','Change')),
          'change_value' => 0,  
        ),
        'gbp' => array(
          'name' => 'GBP',
          'full' => 'İngiliz Sterlini',
          'value' => self::array_get($currencies, array('data','GBP','Selling')),
          'shutdown' => self::array_get($currencies, array('data','GBP','Buying')),
          'change_percent' => self::array_get($currencies, array('data','GBP','Change')),
          'change_value' => 0,
  
        ),
        'eur-usd' => array(
          'name' => 'EURO/USD',
          'full' => esc_html__( 'Euro Amerikan Doları', 'kanews' ),
          'value' => self::array_get($currencies, array('data','EURUSD','Selling')),
          'shutdown' => self::array_get($currencies, array('data','EURUSD','Buying')),
          'change_percent' => self::array_get($currencies, array('data','EURUSD','Change')),
          'change_value' => 0,
  
        ),
        'chf' => array(
          'name' => 'CHF',
          'full' => 'İsviçre Frangı',
          'value' => self::array_get($currencies, array('data','CHF','Selling')),
          'change_percent' => self::array_get($currencies, array('data','CHF','Change')),
          'change_value' => 0,
     
        ),
        'cny' => array(
          'name' => 'CNY',
          'full' => 'Çin Yuanı',
          'value' => self::array_get($currencies, array('data','CNY','Selling')),
          'change_percent' => self::array_get($currencies, array('data','CNY','Change')),
          'change_value' => 0,
        ),
        'jpy' => array(
            'name' => 'JPY',
            'full' => 'Japon Yeni',
            'value' => self::array_get($currencies, array('data','JPY','Selling')),
            'change_percent' => self::array_get($currencies, array('data','JPY','Change')),
            'change_value' => 0,
        ),
        'rub' => array(
            'name' => 'RUB',
            'full' => 'Rus Rublesi',
            'value' => self::array_get($currencies, array('data','RUB','Selling')),
            'change_percent' => self::array_get($currencies, array('data','RUB','Change')),
            'change_value' => 0,
        ),
        'gau' => array(
            'name' => 'GR. ALTIN',
            'full' => 'Gram Altın',
            'value' => self::array_get($gold, array('data','GRA','Selling')),
            'shutdown' => self::array_get($gold, array('data','GRA','Buying')),
            'change_percent' => self::array_get($gold, array('data','GRA','Change')),
            'change_value' => 0,
        ),
        'btc' => array(
          'name' => 'BTC',
          'full' => 'Bitcoin',
          'value' => self::array_get($crypto_data, array('BTC','price')),
          'shutdown' => self::array_get($crypto_data, array('BTC','high24h')),
          'change_percent' => self::array_get($crypto_data, array('BTC','change24h')),
          'change_value' => self::array_get($crypto_data, array('BTC','change_value')),
          'market_cap' => self::array_get($crypto_data, array('BTC','market_cap')),
          'total_volume' => self::array_get($crypto_data, array('BTC','total_volume')),
          'low_24h' => self::array_get($crypto_data, array('BTC','low_24h')),
        ),
        'eth' => array(
          'name' => 'ETH',
          'full' => 'Ethereum',
          'value' => self::array_get($crypto_data, array('ETH','price')),
          'shutdown' => self::array_get($crypto_data, array('ETH','high24h')),
          'change_percent' => self::array_get($crypto_data, array('ETH','change24h')),
          'change_value' => self::array_get($crypto_data, array('ETH','change_value')),
          'market_cap' => self::array_get($crypto_data, array('ETH','market_cap')),
          'total_volume' => self::array_get($crypto_data, array('ETH','total_volume')),
          'low_24h' => self::array_get($crypto_data, array('ETH','low_24h')),
        ),
        'xrp' => array(
          'name' => 'XRP',
          'full' => 'Ripple',
          'value' => self::array_get($crypto_data, array('XRP','price')),
          'shutdown' => self::array_get($crypto_data, array('XRP','high24h')),
          'change_percent' => self::array_get($crypto_data, array('XRP','change24h')),
          'change_value' => 0,
        ),
        'bch' => array(
          'name' => 'BCH',
          'full' => 'Bitcoin Cash',
          'value' => self::array_get($crypto_data, array('BCH','price')),
          'shutdown' => self::array_get($crypto_data, array('BCH','high24h')),
          'change_percent' => self::array_get($crypto_data, array('BCH','change24h')),
          'change_value' => 0,
        ),
        'ltc' => array(
          'name' => 'LTC',
          'full' => 'Litecoin',
          'value' => self::array_get($crypto_data, array('LTC','price')),
          'shutdown' => self::array_get($crypto_data, array('LTC','high24h')),
          'change_percent' => self::array_get($crypto_data, array('LTC','change24h')),
          'change_value' => 0,
        ),
        'bnb' => array(
          'name' => 'BNB',
          'full' => 'Binance Coin',
          'value' => self::array_get($crypto_data, array('BNB','price')),
          'shutdown' => self::array_get($crypto_data, array('BNB','high24h')),
          'change_percent' => self::array_get($crypto_data, array('BNB','change24h')),
          'change_value' => 0,
        ),
        'sol' => array(
          'name' => 'SOL',
          'full' => 'Solana',
          'value' => self::array_get($crypto_data, array('SOL','price')),
          'shutdown' => self::array_get($crypto_data, array('SOL','high24h')),
          'change_percent' => self::array_get($crypto_data, array('SOL','change24h')),
          'change_value' => 0,
        ),
        'avax' => array(
          'name' => 'AVAX',
          'full' => 'Avalanche',
          'value' => self::array_get($crypto_data, array('AVAX','price')),
          'shutdown' => self::array_get($crypto_data, array('AVAX','high24h')),
          'change_percent' => self::array_get($crypto_data, array('AVAX','change24h')),
          'change_value' => 0,
        ),
        'ada' => array(
          'name' => 'ADA',
          'full' => 'Cardano',
          'value' => self::array_get($crypto_data, array('ADA','price')),
          'shutdown' => self::array_get($crypto_data, array('ADA','high24h')),
          'change_percent' => self::array_get($crypto_data, array('ADA','change24h')),
          'change_value' => 0,
        ),
        'dot' => array(
          'name' => 'DOT',
          'full' => 'Polkadot',
          'value' => self::array_get($crypto_data, array('DOT','price')),
          'shutdown' => self::array_get($crypto_data, array('DOT','high24h')),
          'change_percent' => self::array_get($crypto_data, array('DOT','change24h')),
          'change_value' => 0,
        ),
        'doge' => array(
          'name' => 'DOGE',
          'full' => 'Dogecoin',
          'value' => self::array_get($crypto_data, array('DOGE','price')),
          'shutdown' => self::array_get($crypto_data, array('DOGE','high24h')),
          'change_percent' => self::array_get($crypto_data, array('DOGE','change24h')),
          'change_value' => 0,
        ),
        'shib' => array(
          'name' => 'SHIB',
          'full' => 'Shiba Inu',
          'value' => self::array_get($crypto_data, array('SHIB','price')),
          'shutdown' => self::array_get($crypto_data, array('SHIB','high24h')),
          'change_percent' => self::array_get($crypto_data, array('SHIB','change24h')),
          'change_value' => 0,
        ),
      );
      $post_data = self::to_object($post_data);
      set_transient( $transient_name, $post_data, HOUR_IN_SECONDS );
    }

    self::$preparedData = $post_data;
    return self::$preparedData;
  }

  public static function get_currencies($s, $percent = true, $echo = true, $custom = false) {
    $option = self::update();
    $out = '';

    if($option) {
      if ($s == 'all') {
        foreach ($option as $currency) {
          // KAPANIS
          if($currency->value == 0)
          $currency->value = number_format((float)$currency->shutdown, 3,",",".");
        

          $name = '<span class="site-currencies-name">'.$currency->name.'</span>';
          $value = '<span class="site-currencies-value">'. currency_format_number((float)$currency->value) .'</span>';
          $change =  $currency->change_percent;
          if ($change < 0) {
            $class = 'site-currencies-down-item';
            $icon = '<svg class="icon-trending" xmlns="http://www.w3.org/2000/svg" height="16" width="18" fill="currentColor"><path d="M3.062 15 2 13.938l5.854-5.855 3.167 3.167 4.417-4.396H13v-1.5h5v5h-1.5V7.917l-5.479 5.458-3.167-3.167Z"/></svg>';
          } else {
            $class = 'site-currencies-up-item';
            $icon = '<svg class="icon-trending" xmlns="http://www.w3.org/2000/svg" height="16" width="18" fill="currentColor"><path d="M3.062 15 2 13.938l5.854-5.855 3.167 3.167 4.417-4.396H13v-1.5h5v5h-1.5V7.917l-5.479 5.458-3.167-3.167Z"/></svg>';
          }
          if ($percent == true)
          $change = '<span class="site-currencies-change">'.$icon.' %'.$change.'</span>';
          else
          $change = '<span class="site-currencies-change">'.$icon.'</i></span>';

          // Output
          $out .= '<div class="site-currencies-item '.$class.'">'.$name.$value.$change.'</div>';
        }
      } else {
        if(!$s)
        return;
        $header_layout = self::get_option_cached('header-layout', '');
        foreach($s as $currency) {
          if( !isset($option->$currency) ) {
            continue;
          }
          
          // KAPANIS
          if($option->$currency->value === 0)
          $option->$currency->value = currency_format_number((float)$option->$currency->shutdown);

          $name = '<span class="site-currencies-name">'.$option->$currency->name.'</span>';
          $value = '<span class="site-currencies-value">'. currency_format_number((float)$option->$currency->value) .'</span>';
          $change =  $option->$currency->change_percent;
          if ($change < 0) {
            $class = 'site-currencies-down-item';
            $icon = '<i class="icon-caret"></i>';
          } else {
            $class = 'site-currencies-up-item';
            $icon = '<i class="icon-caret"></i>';
          }
   
          $change = '<span class="site-currencies-change"><div>'.$icon.'</div> <div>%'.$change.'</i></div></span>';

          

          // Output
          if( !$custom ) {
            if($header_layout == 'style-3') {
              $out .= '<div class="site-currencies-item '.$class.'">'.$name.$value.$change.'</div>';
            } else {
              $out .= '<div class="site-currencies-item '.$class.'">'.$name.$value.$change.'</div>';
            }
          } else {
            $out .= '<div class="site-currencies-item '.$class.'"><div class="d-flex flex-column justify-content-center g-10">'.$name.$value.'</div>'.$change.'</div>';
          }


        }
      }

      if(!$echo)
      return $out;

      echo $out;
    } else {
      if( $return_empty = get_option('_transient_kanews-currencies') ) {
        if(!$echo)
        return  $return_empty;
        echo  $return_empty;
      } else {
        if(!$echo)
        return esc_html__( 'Veri alınamadı!', 'kanews' );
        echo esc_html__( 'Veri alınamadı!', 'kanews' );
      }
    }

  }

}