<?php

/**
 * Renders the reports page
 *
 * @access  public
 * @since   1.8
*/
function rcp_reports_page() {
	$current_page = admin_url( 'admin.php?page=rcp-reports' );
	$active_tab = isset( $_GET[ 'tab' ] ) ? $_GET[ 'tab' ] : 'earnings';
	?>
	<div class="wrap">
		<h2 class="nav-tab-wrapper">
			<a href="<?php echo add_query_arg( array( 'tab' => 'earnings' ), $current_page ); ?>" class="nav-tab <?php echo $active_tab == 'earnings' ? 'nav-tab-active' : ''; ?>"><?php _e( 'Earnings', 'rcp' ); ?></a>
			<a href="<?php echo add_query_arg( array( 'tab' => 'signups' ), $current_page ); ?>" class="nav-tab <?php echo $active_tab == 'signups' ? 'nav-tab-active' : ''; ?>"><?php _e( 'Signups', 'rcp' ); ?></a>
			<?php do_action( 'rcp_reports_tabs' ); ?>
		</h2>

		<?php
		do_action( 'rcp_reports_page_top' );
		do_action( 'rcp_reports_tab_' . $active_tab );
		do_action( 'rcp_reports_page_bottom' );
		?>
	</div><!-- .wrap -->
	<?php
}

/**
 * Displays the earnings graph.
 *
 * @access  public
 * @since   1.8
*/
function rcp_earnings_graph() {
	global $rcp_options, $wpdb;

	// Retrieve the queried dates
	$dates = rcp_get_report_dates();

	// Determine graph options
	switch ( $dates['range'] ) :
		case 'today' :
			$time_format 	= '%d/%b';
			$tick_size		= 'hour';
			$day_by_day		= true;
			break;
		case 'last_year' :
			$time_format 	= '%b';
			$tick_size		= 'month';
			$day_by_day		= false;
			break;
		case 'this_year' :
			$time_format 	= '%b';
			$tick_size		= 'month';
			$day_by_day		= false;
			break;
		case 'last_quarter' :
			$time_format	= '%b';
			$tick_size		= 'month';
			$day_by_day 	= false;
			break;
		case 'this_quarter' :
			$time_format	= '%b';
			$tick_size		= 'month';
			$day_by_day 	= false;
			break;
		case 'other' :
			if( ( $dates['m_end'] - $dates['m_start'] ) >= 2 ) {
				$time_format	= '%b';
				$tick_size		= 'month';
				$day_by_day 	= false;
			} else {
				$time_format 	= '%d/%b';
				$tick_size		= 'day';
				$day_by_day 	= true;
			}
			break;
		default:
			$time_format 	= '%d/%b'; 	// Show days by default
			$tick_size		= 'day'; 	// Default graph interval
			$day_by_day 	= true;
			break;
	endswitch;

	$time_format 	= apply_filters( 'rcp_graph_timeformat', $time_format );
	$tick_size 		= apply_filters( 'rcp_graph_ticksize', $tick_size );
	$earnings 		= (float) 0.00; // Total earnings for time period shown
	$subscription   = isset( $_GET['subscription'] ) ? absint( $_GET['subscription'] ) : false;
	$payments_db    = new RCP_Payments;

	$args = array(
		'subscription' => rcp_get_subscription_name( $subscription ),
		'date' => array()
	);

	ob_start(); ?>
	<script type="text/javascript">
	   jQuery( document ).ready( function($) {
	   		$.plot(
	   			$("#rcp_earnings_graph"),
	   			[{
   					data: [
	   					<?php

	   					if( $dates['range'] == 'this_week' || $dates['range'] == 'last_week'  ) {

							//Day by day
							$day     = $dates['day'];
							$day_end = $dates['day_end'];
	   						$month   = $dates['m_start'];

							while ( $day <= $day_end ) :

		   						$args = array(
		   							'date' => array(
		   								'day'   => $day,
		   								'month' => $month,
		   								'year'  => $dates['year']
		   							),
		   							'fields' => 'amount'
		   						);

		   						$args['date'] = array( 'day' => $day, 'month' => $month, 'year' => $dates['year'] );
								$payments = $payments_db->get_earnings( $args );
								$earnings += $payments;
								$date = mktime( 0, 0, 0, $month, $day, $dates['year'] ); ?>
								[<?php echo $date * 1000; ?>, <?php echo $payments; ?>],
								<?php
								$day++;
							endwhile;

						} else {

							$y = $dates['year'];
							while( $y <= $dates['year_end'] ) :

								if( $dates['year'] == $dates['year_end'] ) {
									$month_start = $dates['m_start'];
									$month_end   = $dates['m_end'];
								} elseif( $y == $dates['year'] ) {
									$month_start = $dates['m_start'];
									$month_end   = 12;
								} else {
									$month_start = 1;
									$month_end   = 12;
								}

								$i = $month_start;
								while ( $i <= $month_end ) :
									if ( $day_by_day ) :
										$num_of_days 	= cal_days_in_month( CAL_GREGORIAN, $i, $y );
										$d 				= 1;
										while ( $d <= $num_of_days ) :
											$args['date'] = array( 'day' => $d, 'month' => $i, 'year' => $y );
											$payments = $payments_db->get_earnings( $args );
											$earnings += $payments;
											$date = mktime( 0, 0, 0, $i, $d, $y ); ?>
											[<?php echo $date * 1000; ?>, <?php echo $payments; ?>],
										<?php
										$d++;
										endwhile;
									else :

										$args['date'] = array( 'day' => null, 'month' => $i, 'year' => $y );
										$payments = $payments_db->get_earnings( $args );
										$earnings += $payments;
										$date = mktime( 0, 0, 0, $i, 1, $y );
										?>
										[<?php echo $date * 1000; ?>, <?php echo $payments; ?>],
									<?php
									endif;
									$i++;
								endwhile;

								$y++;
							endwhile;

	   					}

	   					?>,
	   				],
	   				yaxis: 2,
   					label: "<?php _e( 'Earnings', 'rcp' ); ?>",
   					id: 'sales'
   				}],
	   		{
               	series: {
                   lines: { show: true },
                   points: { show: true }
            	},
            	grid: {
           			show: true,
					aboveData: false,
					color: '#ccc',
					backgroundColor: '#fff',
					borderWidth: 2,
					borderColor: '#ccc',
					clickable: false,
					hoverable: true
           		},
            	xaxis: {
	   				mode: "time",
	   				timeFormat: "<?php echo $time_format; ?>",
	   				minTickSize: [1, "<?php echo $tick_size; ?>"]
   				},
   				yaxis: {
   					min: 0,
   					minTickSize: 1,
   					tickDecimals: 0
   				}

            });

			function rcp_flot_tooltip(x, y, contents) {
		        $('<div id="rcp-flot-tooltip">' + contents + '</div>').css( {
		            position: 'absolute',
		            display: 'none',
		            top: y + 5,
		            left: x + 5,
		            border: '1px solid #fdd',
		            padding: '2px',
		            'background-color': '#fee',
		            opacity: 0.80
		        }).appendTo("body").fadeIn(200);
		    }

		    var previousPoint = null;
		    $("#rcp_earnings_graph").bind("plothover", function (event, pos, item) {
	            if (item) {
	                if (previousPoint != item.dataIndex) {
	                    previousPoint = item.dataIndex;
	                    $("#rcp-flot-tooltip").remove();
	                    var x = item.datapoint[0].toFixed(2),
                        y = item.datapoint[1].toFixed(2);
                    	if( rcp_vars.currency_pos == 'before' ) {
							rcp_flot_tooltip( item.pageX, item.pageY, item.series.label + ' ' + rcp_vars.currency_sign + y );
                    	} else {
							rcp_flot_tooltip( item.pageX, item.pageY, item.series.label + ' ' + y + rcp_vars.currency_sign );
                    	}
	                }
	            } else {
	                $("#rcp-flot-tooltip").remove();
	                previousPoint = null;
	            }
		    });
	   });
    </script>
	<h2><?php _e( 'Earnings Report', 'rcp' ); ?></h2>
	<div class="metabox-holder" style="padding-top: 0;">
		<div class="postbox">
			<div class="inside">
				<?php rcp_reports_graph_controls(); ?>
				<div id="rcp_earnings_graph" style="height: 300px;"></div>
				<p class="rcp_graph_totals"><strong><?php _e( 'Total earnings for period shown: ', 'rcp' ); echo rcp_currency_filter( number_format_i18n( $earnings, 2 ) ); ?></strong></p>
			</div>
		</div>
	</div>
	<?php
	echo ob_get_clean();
}
add_action( 'rcp_reports_tab_earnings', 'rcp_earnings_graph' );

/**
 * Displays the earnings graph.
 *
 * @access  public
 * @since   1.8
*/
function rcp_signups_graph() {
	global $rcp_options, $wpdb;

	// Retrieve the queried dates
	$dates = rcp_get_report_dates();

	// Determine graph options
	switch ( $dates['range'] ) :
		case 'today' :
			$time_format 	= '%d/%b';
			$tick_size		= 'hour';
			$day_by_day		= true;
			break;
		case 'last_year' :
			$time_format 	= '%b';
			$tick_size		= 'month';
			$day_by_day		= false;
			break;
		case 'this_year' :
			$time_format 	= '%b';
			$tick_size		= 'month';
			$day_by_day		= false;
			break;
		case 'last_quarter' :
			$time_format	= '%b';
			$tick_size		= 'month';
			$day_by_day 	= false;
			break;
		case 'this_quarter' :
			$time_format	= '%b';
			$tick_size		= 'month';
			$day_by_day 	= false;
			break;
		case 'other' :
			if( ( $dates['m_end'] - $dates['m_start'] ) >= 2 ) {
				$time_format	= '%b';
				$tick_size		= 'month';
				$day_by_day 	= false;
			} else {
				$time_format 	= '%d/%b';
				$tick_size		= 'day';
				$day_by_day 	= true;
			}
			break;
		default:
			$time_format 	= '%d/%b'; 	// Show days by default
			$tick_size		= 'day'; 	// Default graph interval
			$day_by_day 	= true;
			break;
	endswitch;

	$time_format 	= apply_filters( 'rcp_graph_timeformat', $time_format );
	$tick_size 		= apply_filters( 'rcp_graph_ticksize', $tick_size );
	$signups 		= 0; // Total signups for time period shown

	$payments_db = new RCP_Payments;

	ob_start(); ?>
	<script type="text/javascript">
	   jQuery( document ).ready( function($) {
	   		$.plot(
	   			$("#rcp_signups_graph"),
	   			[{
   					data: [
	   					<?php

	   					if( $dates['range'] == 'this_week' || $dates['range'] == 'last_week'  ) {

							//Day by day
							$day     = $dates['day'];
							$day_end = $dates['day_end'];
	   						$month   = $dates['m_start'];

							while ( $day <= $day_end ) :

		   						$args = array(
		   							'date' => array(
		   								'day'   => $day,
		   								'month' => $month,
		   								'year'  => $dates['year']
		   							),
		   							'fields' => 'amount'
		   						);

		   						$users = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(ID) FROM $wpdb->users WHERE (%d = MONTH ( user_registered ) AND %d = YEAR ( user_registered ) AND %d = DAY ( user_registered ))", $month, $dates['year'], $day ) );
								$signups += $users;
								$date = mktime( 0, 0, 0, $month, $day, $dates['year'] ); ?>
								[<?php echo $date * 1000; ?>, <?php echo $users; ?>],
								<?php
								$day++;
							endwhile;

						} else {

							$y = $dates['year'];
							while( $y <= $dates['year_end'] ) :

								if( $dates['year'] == $dates['year_end'] ) {
									$month_start = $dates['m_start'];
									$month_end   = $dates['m_end'];
								} elseif( $y == $dates['year'] ) {
									$month_start = $dates['m_start'];
									$month_end   = 12;
								} else {
									$month_start = 1;
									$month_end   = 12;
								}

								$i = $month_start;
								while ( $i <= $month_end ) :
									if ( $day_by_day ) :
										$num_of_days 	= cal_days_in_month( CAL_GREGORIAN, $i, $y );
										$d 				= 1;
										while ( $d <= $num_of_days ) :
											$users = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(ID) FROM $wpdb->users WHERE (%d = MONTH ( user_registered ) AND %d = YEAR ( user_registered ) AND %d = DAY ( user_registered ))", $i, $y, $d ) );
											$signups += $users;
											$date = mktime( 0, 0, 0, $i, $d, $y ); ?>
											[<?php echo $date * 1000; ?>, <?php echo $users; ?>],
										<?php
										$d++;
										endwhile;
									else :
										$users = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(ID) FROM $wpdb->users WHERE (%d = MONTH ( user_registered ) AND %d = YEAR ( user_registered ) )", $i, $y ) );
										$signups += $users;
										$date = mktime( 0, 0, 0, $i, 1, $y );
										?>
										[<?php echo $date * 1000; ?>, <?php echo $users; ?>],
									<?php
									endif;
									$i++;
								endwhile;

								$y++;
							endwhile;
	   					}

	   					?>,
	   				],
	   				yaxis: 2,
   					label: "<?php _e( 'Signups', 'rcp' ); ?>",
   					id: 'sales'
   				}],
	   		{
               	series: {
                   lines: { show: true },
                   points: { show: true }
            	},
            	grid: {
           			show: true,
					aboveData: false,
					color: '#ccc',
					backgroundColor: '#fff',
					borderWidth: 2,
					borderColor: '#ccc',
					clickable: false,
					hoverable: true
           		},
            	xaxis: {
	   				mode: "time",
	   				timeFormat: "<?php echo $time_format; ?>",
	   				minTickSize: [1, "<?php echo $tick_size; ?>"]
   				},
   				yaxis: [
   					{ min: 0, tickSize: 1, tickDecimals: 2 },
   					{ min: 0, tickDecimals: 0 }
   				]

            });

			function rcp_flot_tooltip(x, y, contents) {
		        $('<div id="rcp-flot-tooltip">' + contents + '</div>').css( {
		            position: 'absolute',
		            display: 'none',
		            top: y + 5,
		            left: x + 5,
		            border: '1px solid #fdd',
		            padding: '2px',
		            'background-color': '#fee',
		            opacity: 0.80
		        }).appendTo("body").fadeIn(200);
		    }

		    var previousPoint = null;
		    $("#rcp_signups_graph").bind("plothover", function (event, pos, item) {
	            if (item) {
	                if (previousPoint != item.dataIndex) {
	                    previousPoint = item.dataIndex;
	                    $("#rcp-flot-tooltip").remove();
	                    var x = item.datapoint[0].toFixed(2),
	                        y = item.datapoint[1].toFixed(2);
		                rcp_flot_tooltip( item.pageX, item.pageY, item.series.label + ' ' + y.replace( '.00', '' ) );
	                }
	            } else {
	                $("#rcp-flot-tooltip").remove();
	                previousPoint = null;
	            }
		    });

	   });
    </script>
	<h2><?php _e( 'Signups Report', 'rcp' ); ?></h2>
	<div class="metabox-holder" style="padding-top: 0;">
		<div class="postbox">
			<div class="inside">
				<?php rcp_reports_graph_controls(); ?>
				<div id="rcp_signups_graph" style="height: 300px;"></div>
				<p class="rcp_graph_totals"><strong><?php _e( 'Total signups for period shown: ', 'rcp' ); echo $signups; ?></strong></p>
			</div>
		</div>
	</div>
	<?php
	echo ob_get_clean();
}
add_action( 'rcp_reports_tab_signups', 'rcp_signups_graph' );

/**
 * Show report graph date filters
 *
 * @since 1.8
 * @return void
*/
function rcp_reports_graph_controls() {
	$date_options = apply_filters( 'rcp_report_date_options', array(
		'this_week' 	=> __( 'This Week', 'rcp' ),
		'last_week' 	=> __( 'Last Week', 'rcp' ),
		'this_month' 	=> __( 'This Month', 'rcp' ),
		'last_month' 	=> __( 'Last Month', 'rcp' ),
		'this_quarter'	=> __( 'This Quarter', 'rcp' ),
		'last_quarter'	=> __( 'Last Quarter', 'rcp' ),
		'this_year'		=> __( 'This Year', 'rcp' ),
		'last_year'		=> __( 'Last Year', 'rcp' ),
		'other'			=> __( 'Custom', 'rcp' )
	) );

	$dates          = rcp_get_report_dates();
	$display        = $dates['range'] == 'other' ? '' : 'style="display:none;"';
	$active_tab     = isset( $_GET[ 'tab' ] ) ? $_GET[ 'tab' ] : 'earnings';
	$selected_level = isset( $_GET['subscription'] ) ? absint( $_GET['subscription'] ) : false;
	?>
	<form id="rcp-garphs-filter" method="get">
		<div class="tablenav top">
			<div class="alignleft actions">

		       	<input type="hidden" name="page" value="rcp-reports"/>

		       	<select id="rcp-graphs-date-options" name="range">
		       		<?php
		       		foreach ( $date_options as $key => $option ) {
		       			echo '<option value="' . esc_attr( $key ) . '" ' . selected( $key, $dates['range'] ) . '>' . esc_html( $option ) . '</option>';
		       		}
		       		?>
		       	</select>

		       	<div id="rcp-date-range-options" <?php echo $display; ?>>
					<span><?php _e( 'From', 'rcp' ); ?>&nbsp;</span>
			       	<select id="rcp-graphs-month-start" name="m_start">
			       		<?php for ( $i = 1; $i <= 12; $i++ ) : ?>
			       			<option value="<?php echo absint( $i ); ?>" <?php selected( $i, $dates['m_start'] ); ?>><?php echo rcp_get_month_name( $i ); ?></option>
				       	<?php endfor; ?>
			       	</select>
			       	<select id="rcp-graphs-year" name="year">
			       		<?php for ( $i = 2007; $i <= $dates['year_end']; $i++ ) : ?>
			       			<option value="<?php echo absint( $i ); ?>" <?php selected( $i, $dates['year'] ); ?>><?php echo $i; ?></option>
				       	<?php endfor; ?>
			       	</select>
			       	<span><?php _e( 'To', 'rcp' ); ?>&nbsp;</span>
			       	<select id="rcp-graphs-month-start" name="m_end">
			       		<?php for ( $i = 1; $i <= 12; $i++ ) : ?>
			       			<option value="<?php echo absint( $i ); ?>" <?php selected( $i, $dates['m_end'] ); ?>><?php echo rcp_get_month_name( $i ); ?></option>
				       	<?php endfor; ?>
			       	</select>
			       	<select id="rcp-graphs-year" name="year_end">
			       		<?php for ( $i = 2007; $i <= $dates['year_end']; $i++ ) : ?>
			       			<option value="<?php echo absint( $i ); ?>" <?php selected( $i, $dates['year_end'] ); ?>><?php echo $i; ?></option>
				       	<?php endfor; ?>
			       	</select>
			    </div>

				<?php if( 'earnings' == $active_tab ) : $levels = rcp_get_subscription_levels(); ?>
					<select id="rcp-graphs-subscriptions" name="subscription">
						<option value="0"><?php _e( 'All Subscription Levels', 'rcp' ); ?></option>
						<?php foreach( $levels as $level ) : ?>
							<option value="<?php echo $level->id; ?>"<?php selected( $selected_level, $level->id ); ?>><?php echo $level->name; ?></option>
						<?php endforeach; ?>
					</select>
				<?php endif; ?>

			    <input type="hidden" name="rcp_action" value="" />
			    <input type="hidden" name="tab" value="<?php echo $active_tab ?>" />
		       	<input type="submit" class="button-secondary" value="<?php _e( 'Filter', 'rcp' ); ?>"/>
			</div>
		</div>
	</form>
	<?php
}

/**
 * Sets up the dates used to filter graph data
 *
 * Date sent via $_GET is read first and then modified (if needed) to match the
 * selected date-range (if any)
 *
 * @since 1.8
 * @return void
*/
function rcp_get_report_dates() {
	$dates = array();

	// Make sure the reports are based off of the correct timezone
	date_default_timezone_set( rcp_get_timezone_id() );

	$dates['range']      = isset( $_GET['range'] )   ? $_GET['range']   : 'this_month';
	$dates['day']        = isset( $_GET['day'] )     ? $_GET['day']     : null;
	$dates['m_start']    = isset( $_GET['m_start'] ) ? $_GET['m_start'] : 1;
	$dates['m_end']      = isset( $_GET['m_end'] )   ? $_GET['m_end']   : 12;
	$dates['year']       = isset( $_GET['year'] )    ? $_GET['year']    : date( 'Y' );
	$dates['year_end']   = isset( $_GET['y_end'] )   ? $_GET['y_end']   : date( 'Y' );

	// Modify dates based on predefined ranges
	switch ( $dates['range'] ) :

		case 'this_month' :
			$dates['m_start'] 	= date( 'n' );
			$dates['m_end']		= date( 'n' );
			$dates['year']		= date( 'Y' );
		break;

		case 'last_month' :
			if( $dates['m_start'] == 1 ) {
				$dates['m_start'] = 12;
				$dates['m_end']	  = 12;
				$dates['year']    = date( 'Y' ) - 1;
				$dates['year_end']= date( 'Y' ) - 1;
			} else {
				$dates['m_start'] = date( 'n' ) - 1;
				$dates['m_end']	  = date( 'n' ) - 1;
				$dates['year']    = date( 'Y' );
			}
		break;

		case 'this_week' :
			$dates['day']       = date( 'd', current_time( 'timestamp' ) - ( date( 'w' ) - 1 ) *60*60*24 ) - 1;
			$dates['day']      += get_option( 'start_of_week' );
			$dates['day_end']   = $dates['day'] + 6;
			$dates['m_start'] 	= date( 'n' );
			$dates['m_end']		= date( 'n' );
			$dates['year']		= date( 'Y' );
		break;

		case 'last_week' :
			$dates['day']       = date( 'd', current_time( 'timestamp' ) - ( date( 'w' ) - 1 ) *60*60*24 ) - 8;
			$dates['day']      += get_option( 'start_of_week' );
			$dates['day_end']   = $dates['day'] + 6;
			$dates['m_start'] 	= date( 'n' );
			$dates['m_end']		= date( 'n' );
			$dates['year']		= date( 'Y' );
		break;

		case 'this_quarter' :
			$month_now = date( 'n' );

			if ( $month_now <= 3 ) {

				$dates['m_start'] 	= 1;
				$dates['m_end']		= 3;
				$dates['year']		= date( 'Y' );

			} else if ( $month_now <= 6 ) {

				$dates['m_start'] 	= 4;
				$dates['m_end']		= 6;
				$dates['year']		= date( 'Y' );

			} else if ( $month_now <= 9 ) {

				$dates['m_start'] 	= 7;
				$dates['m_end']		= 9;
				$dates['year']		= date( 'Y' );

			} else {

				$dates['m_start'] 	= 10;
				$dates['m_end']		= 12;
				$dates['year']		= date( 'Y' );

			}
		break;

		case 'last_quarter' :
			$month_now = date( 'n' );

			if ( $month_now <= 3 ) {

				$dates['m_start'] 	= 10;
				$dates['m_end']		= 12;
				$dates['year']		= date( 'Y' ) - 1; // Previous year

			} else if ( $month_now <= 6 ) {

				$dates['m_start'] 	= 1;
				$dates['m_end']		= 3;
				$dates['year']		= date( 'Y' );

			} else if ( $month_now <= 9 ) {

				$dates['m_start'] 	= 4;
				$dates['m_end']		= 6;
				$dates['year']		= date( 'Y' );

			} else {

				$dates['m_start'] 	= 7;
				$dates['m_end']		= 9;
				$dates['year']		= date( 'Y' );

			}
		break;

		case 'this_year' :
			$dates['m_start'] 	= 1;
			$dates['m_end']		= 12;
			$dates['year']		= date( 'Y' );
		break;

		case 'last_year' :
			$dates['m_start'] 	= 1;
			$dates['m_end']		= 12;
			$dates['year']		= date( 'Y' ) - 1;
			$dates['year_end']  = date( 'Y' ) - 1;
		break;

	endswitch;

	return apply_filters( 'rcp_report_dates', $dates );
}

/**
 * Grabs all of the selected date info and then redirects appropriately
 *
 * @since 1.8
 * @return void
*/
function rcp_parse_report_dates() {

	if( ! isset( $_GET['rcp_action'] ) )
		return;

	if( 'filter_reports' != $_GET['rcp_action'] )
		return;

	$dates = rcp_get_report_dates();

	wp_redirect( add_query_arg( $dates, admin_url( 'admin.php?page=rcp-reports' ) ) ); exit;
}
add_action( 'admin_init', 'rcp_parse_report_dates' );