<?php
/**
 * @brief		Currencies
 *
 * @copyright	(c) 2001 - SVN_YYYY Invision Power Services, Inc.
 *
 * @package		IPS Social Suite
 * @subpackage	Nexus
 * @since		26 Mar 2014
 * @version		SVN_VERSION_NUMBER
 */

namespace IPS\nexus\modules\admin\payments;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * Currencies
 */
class _currencies extends \IPS\Dispatcher\Controller
{
	/**
	 * Execute
	 *
	 * @return	void
	 */
	public function execute()
	{
		\IPS\Dispatcher::i()->checkAcpPermission( 'currencies_manage' );
		parent::execute();
	}

	/**
	 * Manage
	 *
	 * @return	void
	 */
	public function manage()
	{
		$languages = \IPS\Lang::languages();
		
		$matrix = new \IPS\Helpers\Form\Matrix;
		$matrix->langPrefix = 'currency_';
		$matrix->columns = array(
			'code'		=> function( $key, $value, $data )
			{
				return new \IPS\Helpers\Form\Text( $key, $value, FALSE, array( 'minLength' => 3, 'maxLength' => 3, 'placeholder' => 'USD' ) );
			},
			'default'	=> function( $key, $value, $data ) use ( $languages )
			{
				if ( count( $languages ) === 1 )
				{
					return new \IPS\Helpers\Form\Checkbox( $key, $value );
				}
				else
				{
					$options = array();
					foreach ( $languages as $k => $v )
					{
						$options[ $v->id ] = $v->_title;
					}
					
					return new \IPS\Helpers\Form\Select( $key, $value, FALSE, array( 'options' => $options, 'multiple' => TRUE ) );
				}
			}
		);
		
		if ( $currencies = json_decode( \IPS\Settings::i()->nexus_currency, TRUE ) )
		{
			foreach ( $currencies as $code => $defaults )
			{
				$matrix->rows[] = array(
					'code'		=> $code,
					'default'	=> $defaults
				);
			}
		}
		else
		{
			$matrix->rows[] = array(
				'code'		=> \IPS\Settings::i()->nexus_currency,
				'default'	=> count( $languages ) === 1 ? TRUE : array_keys( $languages )
			);
		}
		
		if ( $values = $matrix->values() )
		{
			$save = array();
			
			foreach ( $values as $data )
			{
				if ( $data['code'] )
				{
					$save[ $data['code'] ] = ( count( $languages ) === 1 ) ? ( $data['default'] ? array_keys( $languages ) : array() ) : $data['default'];
				}
			}
			
			\IPS\Db::i()->update( 'core_sys_conf_settings', array( 'conf_value' => json_encode( $save ) ), array( 'conf_key=?', 'nexus_currency' ) );
			\IPS\Settings::i()->nexus_currency	= json_encode( $save );									
			unset( \IPS\Data\Store::i()->settings );
			
			\IPS\Session::i()->log( 'acplogs__currencies' );		
			
			\IPS\Output::i()->redirect( \IPS\Http\Url::internal( 'app=nexus&module=payments&controller=paymentsettings&tab=currencies' ) );
		}
		
		\IPS\Output::i()->output = $matrix;
	}
}