<?php
/**
 * @brief		Dashboard extension: Income
 *
 * @copyright	(c) 2001 - SVN_YYYY Invision Power Services, Inc.
 *
 * @package		IPS Social Suite
 * @subpackage	
 * @since		18 Sep 2014
 * @version		SVN_VERSION_NUMBER
 */

namespace IPS\nexus\extensions\core\Dashboard;

/* 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;
}

/**
 * Dashboard extension: Income
 */
class _Income
{
	/** 
	 * Return the block HTML show on the dashboard
	 *
	 * @return	string
	 */
	public function getBlock()
	{
		$chart = new \IPS\Helpers\Chart;
		
		$chart->addHeader( "Day", 'date' );
		foreach ( \IPS\nexus\Money::currencies() as $currency )
		{
			$chart->addHeader( $currency, 'number' );
		}
		
		$firstOfMonth = mktime( 0, 0, 0, date('n'), 1, date('Y') );
		$lastOfMonth = mktime( 23, 59, 59, date('n') + 1, 0, date('Y') );
		
		$results = array();
		foreach( \IPS\Db::i()->select( "t_currency, DATE_FORMAT( FROM_UNIXTIME( t_date ), '%e %c %Y' ) AS date, SUM(t_amount)-SUM(t_partial_refund) AS amount", 'nexus_transactions', array( 't_date>? AND t_date<?', $firstOfMonth, $lastOfMonth ), NULL, NULL, array( 't_currency', 'date' ) ) as $result )
		{
			$results[ $result['date'] ][ $result['t_currency'] ] = $result['amount'];
		}
		
		$monthAndYear = date( 'n' ) . ' ' . date( 'Y' );
		foreach ( range( 1, date('t') ) as $day )
		{
			$datetime = new \IPS\DateTime;
			$datetime->setTime( 0, 0, 0 );
			$exploded = explode( ' ', "{$day} {$monthAndYear}" );
			$datetime->setDate( $exploded[2], $exploded[1], $exploded[0] );
			
			if ( isset( $results[ "{$day} {$monthAndYear}" ] ) )
			{
				$row = array( $datetime );
				
				foreach ( \IPS\nexus\Money::currencies() as $currency )
				{
					if ( !isset( $results[ "{$day} {$monthAndYear}" ][ $currency ] ) )
					{
						$row[] = 0;
					}
					else
					{
						$row[] = $results[ "{$day} {$monthAndYear}" ][ $currency ];
					}
				}
				
				$chart->addRow( $row );
			}
			else
			{
				$row = array( $datetime );
				foreach ( \IPS\nexus\Money::currencies() as $currency )
				{
					$row[] = 0;
				}
				$chart->addRow( $row );
			}
		}
		
		return $chart->render( 'LineChart' );
	}

	/** 
	 * Return the block information
	 *
	 * @return	array	array( 'name' => 'Block title', 'key' => 'unique_key', 'size' => [1,2,3], 'by' => 'Author name' )
	 */
	public function getInfo()
	{
		return array();
	}

	/**
	 * Save the block data submitted.  This method is only necessary if your block accepts some sort of submitted data to save (such as the 'admin notes' block).
	 *
	 * @return	void
	 * @throws	\LogicException
	 */
	public function saveBlock()
	{
	}
}