<?php
use Joomla\CMS\Version;
use Joomla\Registry\Registry;
use Joomla\CMS\Http\HttpFactory;

/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

//jimport('joomla.plugin.plugin');

class plgDjcatalog2currencyNbp extends JPlugin {
	public function onDJCatalog2FetchExchangeRates() {
		
		$date = JFactory::getDate();
		$db = JFactory::getDbo();
		$offset = 3600;
		
		$db->setQuery('select last_check from #__djc2_plg_currency_nbp', 0, 1);
		$lastCheck = $db->loadResult();
		
		if ($lastCheck) {
			if (JFactory::getDate($lastCheck)->toUnix() + $offset > $date->toUnix()) {
				return;
			}
		}
		$db->setQuery('select * from #__djc2_currencies');
		$allcurrencies = $db->loadObjectList();
		
		$db->setQuery('select * from #__djc2_currencies where currency <>' . $db->quote('PLN'));
		$currencies = $db->loadObjectList();
		
		$db->setQuery('select * from #__djc2_currencies where currency=' . $db->quote('PLN'));
		$plnRow = $db->loadObject();
		
		if (empty($plnRow)) return;
		
		foreach($currencies as $currency) {
			if ($currency->id == $plnRow->id) continue;
			
			$rate = $this->fetchLatestRate($currency->currency);
			if (empty($rate)) continue;
			
			//$original_rate = $rate->target_rate;
			
			// 1 ABC => x PLN
			$db->setQuery('select count(*) from #__djc2_currency_exchange where target_id=' . $plnRow->id.' AND base_id=' . $currency->id.' AND DATE(rate_date) = '.$db->quote($rate->rate_date));
			$exists = $db->loadResult();
			if (!$exists) {
				$rate->id = null;
				$rate->target_id = $plnRow->id;
				$rate->base_id = $currency->id;
				
				// margin
				$rate->target_rate = $rate->target_rate;//round(($rate->target_rate * 103) / 100, 4);
				
				$db->insertObject('#__djc2_currency_exchange', $rate, 'id');
			}
			
			foreach($allcurrencies as $xcurrency) {
				if ($xcurrency->id == $currency->id) continue;
				
				$db->setQuery('select count(*) from #__djc2_currency_exchange where base_id=' . $xcurrency->id.' AND target_id=' . $currency->id.' AND DATE(rate_date) = '.$db->quote($rate->rate_date));
				$exists2 = $db->loadResult();
				if ($exists2) continue;
				
				if ($xcurrency->id == $plnRow->id) {
					// 1 PLN => x ABC
					
					$rate2 = clone $rate;
					$rate2->id = null;
					$rate2->target_id = $currency->id;
					$rate2->base_id = $xcurrency->id;
					$rate2->target_rate = round(1 / $rate2->target_rate, 4);
					
					$db->insertObject('#__djc2_currency_exchange', $rate2, 'id');
				} else {
					// 1 ABC => x ZYX
					$xrate = $this->fetchLatestRate($xcurrency->currency);
					if (empty($xrate)) continue;
					
					$rate2 = clone $rate;
					$rate2->id = null;
					$rate2->target_id = $currency->id;
					$rate2->base_id = $xcurrency->id;
					$rate2->target_rate = $xrate->target_rate / $rate->target_rate;
					$db->insertObject('#__djc2_currency_exchange', $rate2, 'id');
				}
			}
		}
		
		$db->setQuery('delete from #__djc2_plg_currency_nbp');
		$db->execute();
		$db->setQuery('insert into #__djc2_plg_currency_nbp (last_check) values (' . $db->quote($date->toSql()).')');
		$db->execute();
		
	}
	
	protected function fetchLatestRate($currency) {
		$version    = new Version();
		$httpOption = new Registry();
		$httpOption->set('userAgent', $version->getUserAgent('Joomla', true, false));
		
		$url = 'https://api.nbp.pl/api/exchangerates/rates/a/' . $currency . '/?format=json';
		
		try
		{
			$http = HttpFactory::getHttp($httpOption);
			$response = $http->get($url, array(), 20);
		}
		catch (\RuntimeException $e)
		{
			$response = null;
		}
		
		
		if (!empty($response) && strpos($response->code, '2') === 0 && $response->body != '') {
			$json = json_decode($response->body, true);
			if (isset($json['rates']) && isset($json['rates'][0])) {
				$rate = $json['rates'][0];
				$row = new stdClass();
				$row->id = null;
				$row->rate_date = $rate['effectiveDate'];
				$row->target_rate = $rate['mid'];
				
				return $row;
			}
		}
		
		return false;
	}
}