<?php
$isPopup = ( $_GET[ 'popup' ] ? true : false );
$hideSlider = ( $_REQUEST[ 'hideSlider' ] ? true : false );
if( $isPopup ){
?>
	<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,800">
	<link href="/assets/css/core/core.css" media="screen" rel="stylesheet" type="text/css" />
	<script src="/assets/js/core/core.js" type="text/javascript"></script>
	<script src="/assets/js/highcharts.src.js" type="text/javascript"></script>
<?
}


	// group up the data by order of data items recieved
	// 0: X
	// 1: Y
	// 2: Group

	$categories = [];
	$ys = [];
	$group = [];

	// set up x labels and empty objects
	foreach ($data as $item) {
		$vars = get_object_vars($item);

		// X
		$xName = key($vars);
		$x = array_shift($vars);
		$xs[$x] = true;


		$yName = key($vars);
		$y = array_shift($vars);

		$group = array_shift($vars);

		$ys[$group] = [];

	}

	$hasResults = true;

	if( count( $xs ) == 0 ){
		$hasResults = false;
	}

	if( $hasResults ){

		foreach ($xs as $k => $v) {
			$xx .= "'".str_replace("'","\\'",$k)."', ";
		}
		$xx = substr($xx,0,-2);

		// fill empty columns
		foreach ($xs as $k => $v) {
			foreach ($ys as $kk => $vv) {
				$ys[$kk][$k] = 0;
			}
		}


		// gather data
		foreach ($data as $item) {
			$vars = get_object_vars($item);

			// X
			$x = array_shift($vars);
			$xs[$x] = true;

			// Y & group
			$y = array_shift($vars);

			$groupName = key($vars);
			$group = array_shift($vars);

			$ys[$group][$x] = $y;

		}

		$applyCommunityFilter = false;

		foreach ($ys as $k => $v) {
			if( $_GET[ 'filter' ] && $_GET[ 'filter' ] == 'community' ){
				if( $_GET[ 'community' ] && $_GET[ 'community' ] != '' && strtolower( $_GET[ 'community' ] ) != 'all' ){
					if( strtolower( $_GET[ 'community' ] ) == strtolower( $k ) ){
						$applyCommunityFilter = true;
					}
				}
			}
		}

		// remove assoc vals and add proper keys
		foreach ($ys as $k => $v) {
			$ys[$k] = array_values($ys[$k]);
			$visible = true;
			if( $applyCommunityFilter && $_GET[ 'filter' ] && $_GET[ 'filter' ] == 'community' ){
				if( $_GET[ 'community' ] && $_GET[ 'community' ] != '' && strtolower( $_GET[ 'community' ] ) != 'all' ){
					if( strtolower( $_GET[ 'community' ] ) == strtolower( $k ) ){
						$visible = true;
					} else {
						$visible = false;
					}
				}
			}
			$ys[$k] = [
				'name' => $k,
				'visible' => $visible,
				'data' => $ys[$k]
			];
		}


		$jsData = [
			'xs' => array_keys($xs),
			'ys' => array_values($ys)
		];
	}
?>
<?php if( $interval == 'hour' && $_GET[ 'day' ] ){
	$chartId .= $_GET[ 'day' ];
} ?>
<div class="row-fluid">
	<div class="row-fluid">
		<div class="span12">
			<h4 style="text-align:center;">
				<?php echo $title; ?> <?php if( $interval == 'hour' && $_GET[ 'day' ] ){ echo $_GET[ 'day' ]; } ?>
				<?php if( !$isPopup ){
					$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&popup=1";
					echo '&nbsp;&nbsp;<a href="' . $url . '" target="_blank" title="Zoom this chart"><i class="icon-zoom-in"></i></a>';
					}?>
			</h4>
		</div>
	</div>
	<?php if( $hasResults ){ ?>
	<div id="chart-<?=$chartId?>" style="min-width: 100%; <?php if( $isPopup ){ echo 'height:90%;'; }else{ echo 'height:250px;'; } ?> margin: 0 auto"></div>
<center style="height:60px;">
	<?php if( $subtitle != '' ){ ?>
		<div style="font-size:10px;"><?php echo $subtitle; ?></div>
	<?php } ?>
	<?php echo $description; ?>
</center>
	<div id="options-<?=$divId?>" style="height:110px;background:#F5F5F5;overflow-x:auto;width:99%;overflow-y:hidden;<?php if( $isPopup || $interval == 'hour' ){ echo 'display:none'; } ?>">
		<table>
			<tr>
			<?php
				if( $groups ){ ?>
				<td class="padded" nowrap="">
					<select style="width:100px;font-size:10px;" class="charts-select" id="select-<?=$chartId?>" data-divId="<?php echo $divId; ?>" onchange="loadSubChart( this.id )">
						<?php foreach ( $groups as $key => $value ) {
							$selected = ( $key == $chartId ) ? 'selected="selected"' : '';
							?>
							<option <?php echo $selected; ?> value="<?php echo $key; ?>|<?php echo $value[ 'interval' ]; ?>"><?php echo $value[ 'title' ]; ?></option>
						<?php } ?>
					</select>
				</td>
			<?php }

			if( $info['chart'][ 'filters' ] ){

				$filters = $info['chart'][ 'filters' ];

				$hasFilter = false;

				foreach( $filters as $filter ){

					if( $filter[ 'type' ] == 'cohort' ){

						$cohorts = Crunchbutton_Chart_Cohort::_getAll();

						if( count( $cohorts[ 'cohorts' ] ) > 0 ){

							foreach( $cohorts[ 'cohorts' ] as $cohort ){

								$checked = ( $_GET[ 'id_chart_cohort' ] == $cohort->id_chart_cohort && $_GET[ 'cohort_type' ] == 'cohort' ) ? 'checked="checked"' : '';

								if( $checked != '' ){ $hasFilter = true; }

								?>

								<td nowrap="" class="padded" id="filter-<?php echo $divId; ?>-cohort-<?php echo $cohort->id_chart_cohort; ?>">
									<div>
										<input type="radio" name="filter<?=$chartId?>" class="icheck-<?=$chartId?>" <?php echo $checked; ?> value="cohort&cohort_type=cohort&id_chart_cohort=<?php echo $cohort->id_chart_cohort; ?>" id="cohort-<?php echo $cohort->id_chart_cohort; ?>">
										<label for="cohort-<?php echo $cohort->id_chart_cohort; ?>" style="font-size:10px;"><?php echo $cohort->name; ?></label>
									</div>
								</td>

								<?php
							}
						}

						if( count( $cohorts[ 'giftcards' ] ) > 0 ){
							?>
							<td nowrap="" class="padded" id="filter-cohort-giftcards">
								<div>
									<select id="cohort-giftcards" style="width:100px;font-size:10px;" class="charts-select select-cohort-<?=$chartId?>">
									<option>Gift card group</option>
									<?php foreach( $cohorts[ 'giftcards' ] as $cohort ){
											$selected = ( $_GET[ 'id_chart_cohort' ] == $cohort->id_chart_cohort && $_GET[ 'cohort_type' ] == 'giftcard' ) ? 'selected="selected"' : '';
											if( $selected != '' ){ $hasFilter = true; }
										?>
										<option <?php echo $selected; ?> value="cohort&cohort_type=giftcard&id_chart_cohort=<?php echo $cohort->id_chart_cohort ?>"><?php echo $cohort->name ?></option>
									<?php } ?>
									</select>
								</div>
							</td>

							<?php
						}

						if( count( $cohorts[ 'months' ] ) > 0 ){
							?>
							<td class="padded" nowrap="" id="filter-<?php echo $divId; ?>-cohort-months">
								<div>
									<select id="cohort-months" style="width:100px;font-size:10px;" class="charts-select select-cohort-<?=$chartId?>">
									<option>First order at</option>
									<?php foreach( $cohorts[ 'months' ] as $cohort ){
											$selected = ( $_GET[ 'id_chart_cohort' ] == $cohort->id_chart_cohort && $_GET[ 'cohort_type' ] == 'months' ) ? 'selected="selected"' : '';
											if( $selected != '' ){ $hasFilter = true; }
										?>
										<option <?php echo $selected; ?> value="cohort&cohort_type=months&id_chart_cohort=<?php echo $cohort->id_chart_cohort ?>"><?php echo $cohort->name ?></option>
									<?php } ?>
									</select>
								</div>
							</td>

							<?php
						}

					} else {
						$checked = ( $filter[ 'type' ] == $info[ 'filter' ] ) ? 'checked="checked"' : '';
						if( $checked != '' ){ $hasFilter = true; }
						?>
						<td class="padded" nowrap="" id="filter-<?php echo $divId; ?>-<?php echo $filter[ 'type' ]; ?>">
							<div>
								<input type="radio" name="filter<?=$chartId?>" class="icheck-<?=$chartId?>" <?php echo $checked; ?> value="<?php echo $filter[ 'type' ]; ?>" id="<?php echo $filter[ 'type' ]; ?>">
								<label for="<?php echo $filter[ 'type' ]; ?>" style="font-size:10px;"><?php echo $filter[ 'title' ]; ?></label>
							</div>
						</td>
						<?php
					}
				}
				?>
				<td nowrap="" class="padded" id="filter-no-filter">
					<div>
						<input type="radio" <?php if( !$hasFilter ){ echo 'checked="checked"'; } ?> name="filter<?=$chartId?>" class="icheck-<?=$chartId?>" value="" id="no-filter">
						<label for="no-filter" style="font-size:10px;">No filter</label>
					</div>
				</td>
				<?php
			}
			?>
			</tr>
		</table>

	<div class="row-fluid span11"  style="padding:0 20px; font-size:10px;<?php if( $hideSlider ){ echo 'display:none;'; } ?>">
		<div class="span4" id="week-<?=$chartId?>">
			<?php
			if( $interval == 'week' ){
				$_slider_to = $to;
				$_slider_from = $from;
				?>
					Weeks <?php echo $from; ?> to <?php echo $to; ?> (total <?php echo $totalWeeks; ?>)
				<?php
			} else if( $interval == 'month' ){
					$_slider_to = $to_month;
					$_slider_from = $from_month;
			?>
				Months <?php echo $from_month; ?> to <?php echo $to_month; ?> (total <?php echo $totalMonths; ?>)
			<?php
			} else if( $interval == 'day' ){
					$_slider_to = $to_day;
					$_slider_from = $from_day;
			?>
				Days <?php echo $from_day; ?> to <?php echo $to_day; ?> (total <?php echo $totalDays; ?>)
			<?php
			} ?>
		</div>
		<div class="span6">
			<div id="slider-<?=$divId?>" data-from="<?php echo $_slider_from; ?>" data-to="<?php echo $_slider_to; ?>"></div>
	</div>
	<?php } else {
		echo 'No results for <b>' . $title . '</b>';
	} ?>
</div>
</div>

<?php if( $hasResults ){ ?>
<script type="text/javascript">
$(function () {
	var data = <?=json_encode($jsData, JSON_NUMERIC_CHECK)?>;
	$('#chart-<?=$chartId?>').highcharts({
		chart: {
			type: 'column',
			backgroundColor:'rgba(255, 255, 255, 0.1)'
		},
		title: {
			text: ''
		},
		xAxis: {
			categories: data.xs,
			tickmarkPlacement: 'on',
			title: {
				enabled: false
			},
			labels : {
				rotation: -45,
				align: 'right'
				<?php if( $interval == 'hour' ){ ?>,step:1<?php } ?>
				<?php if( $interval == 'day' ){ ?>,step:10<?php } ?>
				<?php if( $interval == 'week' ){ ?>,step:2<?php } ?>
			}
		},
		yAxis: {
			title: {
				text: '<?=$yName?>'
			},
			labels: {
				formatter: function() {
					return this.value;
				}
			}
		},
		tooltip: {
			formatter: function (tooltip) {
							var items = this.points || splat(this), series = items[0].series, s;

							/* build the header */
							s = [series.tooltipHeaderFormatter(items[0])];

							/* sort the values */
							items.sort(function(a, b){
								return ((a.y < b.y) ? -1 : ((a.y > b.y) ? 1 : 0));
							});
							items.reverse();

							/* build the values */
							$.each(items, function (i, item) {
								if( item.y = 0 ){
									return;
								}
									series = item.series;
									s.push( ( series.tooltipFormatter && series.tooltipFormatter( item ) ) ||
											item.point.tooltipFormatter( series.tooltipOptions.pointFormat ) );
							});

							/* footer */
							s.push(tooltip.options.footerFormat || '');

							return s.join('');
					},
			shared:true,
			crosshairs:true,
			valueSuffix: ' <?=$unit?>'
		},
		plotOptions: {
			column: {
				pointPadding: 0,
				dataLabels: {
					enabled: false,
					color: ( Highcharts.theme && Highcharts.theme.dataLabelsColor ) || 'white'
				}
			}
		},
		series: data.ys
	});
	$( '#slider-<?=$divId?>' ).slider( {
		range: true,
		min: 1,
		<?php
		if( $interval == 'week' ){
			?>
			values: [ <?php echo $from; ?>, <?php echo $to; ?> ],
			max: <?php echo $totalWeeks; ?>,
			<?php
		} else if( $interval == 'month' ){
		?>
			values: [ <?php echo $from_month; ?>, <?php echo $to_month; ?> ],
			max: <?php echo $totalMonths; ?>,
		<?php
		} else if( $interval == 'day' ){
		?>
			values: [ <?php echo $from_day; ?>, <?php echo $to_day; ?> ],
			max: <?php echo $totalDays; ?>,
		<?php
		} ?>
		change: function( event, ui ) {
			$( '#week-<?=$chartId?>' ).html( '<i class="icon-spinner icon-spin"></i>' );
			$( '#slider-<?=$chartId?>' ).slider( 'disable' );
			$( '#slider-<?=$chartId?>' ).css( 'opacity', 0.4 );
			var self = $( '#<?=$divId?>' );
			$( '#slider-<?=$divId?>' ).attr( 'data-from', ui.values[ 0 ] );
			$( '#slider-<?=$divId?>' ).attr( 'data-to', ui.values[ 1 ] );
			loadChart(  { 'divId' : '<?php echo $divId; ?>', 'permalink' : '<?php echo $chartId; ?>', 'interval' : '<?php echo $interval; ?>', 'filter' : '<?php echo $info[ '_filter' ]; ?>'} );
		}
	} );
});
</script>
<?php } ?>
<script type="text/javascript">
	$(function () {
		$( '.icheck-<?=$chartId?>' ).iCheck( { checkboxClass: "icheckbox_flat-aero", radioClass: "iradio_flat-aero" } );

		$( '.icheck-<?=$chartId?>' ).on( 'ifChanged', function( event ){
			var check = $( this );

			var id = check.attr( 'id' );

			$( '#filter-<?php echo $divId; ?>-' + id ).html( '<i class="icon-spinner icon-spin"></i>' );

			if( check.is( ':checked' ) ){
				var filter = check.val();
			} else {
				var filter = '';
			}
			loadChart( { 'divId' : '<?php echo $divId; ?>', 'permalink' : '<?php echo $chartId; ?>', 'filter' : filter, 'interval' : '<?php echo $interval; ?>' } );
		});

		$( '.select-cohort-<?=$chartId?>' ).change( function(){

			var select = $( this );

			var id = select.attr( 'id' );

			$( '#filter-<?php echo $divId; ?>-' + id ).html( '<i class="icon-spinner icon-spin"></i>' );

			loadChart( { 'divId' : '<?php echo $divId; ?>', 'permalink' : '<?php echo $chartId; ?>', 'filter' : select.val() } );
		});

	});
</script>