<?php if (!defined('APS_ADS_VER')) exit('restricted access');
/*
 * @package WordPress
 * @subpackage APS Ads
*/

	function aps_build_ads_manager_page() {
		
		// get ad posts data
		$ads = aps_ads_posts_data();
		$settings = get_aps_ads_settings();
		$ad_conditions = aps_ads_display_conditions();
		$aps_nonce = wp_create_nonce('aps_ads');
		$notice = false;
		
		// process the form
		if (isset($_POST['submit'])) {
			if (wp_verify_nonce($_POST['aps-nonce'], 'aps_ads')) {
				$fields_data = (isset($_POST['aps-ads'])) ? $_POST['aps-ads'] : array();
				update_aps_settings('ads-data', $fields_data);
				$notice = '<div class="notice notice-success is-dismissible"><p>' .esc_html__('Your settings are saved successfully', 'aps-ads') .'.</p></div>';
			} else {
				$notice = '<div class="notice notice-error is-dismissible"><p>' .esc_html__('There is something went wrong, please reload the page and try again', 'aps-ads') .'.</p></div>';
			}
		} ?>
		<div class="wrap aps-wrap">
			<h1><?php esc_html_e('APS Ads Manager', 'aps-ads'); ?></h1>
			<p class="description"><?php esc_html_e('Manage your ad units display placements, you can add multiple ad units in each placement.', 'aps-ads'); ?></p>
			
			<?php // print the notice
			if ($notice) echo wp_specialchars_decode($notice);
			
			$saved_data = get_aps_settings('ads-data', array()); ?>
			
			<form method="post" action="<?php echo esc_url( admin_url('admin.php?page=aps-ads') ); ?>">
				<div class="aps-ads-input-wrap">
					<ul class="aps-ads-slots">
						<?php $count = 1;
						if (aps_is_array($saved_data)) {
							foreach ($saved_data as $saved_ad) { ?>
								<li class="aps-ad-sortable" id="ad-placement-<?php echo esc_attr($count); ?>">
									<div class="aps-ads-item">
										<span class="dashicons dashicons-menu"></span>
										<div class="aps-ads-row">
											<div class="aps-col-2">
												<label for="aps-ad-hook"><?php esc_html_e('Ad Placement', 'aps-ads'); ?></label><br />
												<select class="aps-select aps-select2 aps-select-hook aps-full-width" name="aps-ads[<?php echo esc_attr($count); ?>][hook]">
													<?php foreach ($settings as $group) { ?>
														<optgroup label="<?php echo esc_attr($group['title']); ?>">
															<?php foreach ($group['hooks'] as $hook => $name) { ?>
																<option value="<?php echo esc_attr($hook); ?>"<?php if ($saved_ad['hook'] == $hook) { ?> selected="selected"<?php } ?>><?php echo esc_html($name); ?></option>
															<?php } ?>
														</optgroup>
													<?php } ?>
												</select>
											</div>
											
											<div class="aps-col-2">
												<label for="aps-ad-id"><?php esc_html_e('Select Ad Unit', 'aps-ads'); ?></label><br />
												<select class="aps-select aps-select2 aps-full-width" name="aps-ads[<?php echo esc_attr($count); ?>][id]">
													<?php if ($ads) {
														foreach ($ads as $ad_id => $ad) { ?>
															<option value="<?php echo esc_attr($ad_id); ?>"<?php if ($saved_ad['id'] == $ad_id) { ?> selected="selected"<?php } ?>><?php echo esc_html($ad['title']); ?> - <?php echo esc_html($ad['type']); ?></option>
														<?php }
													} else { ?>
														<option value="0"><?php esc_html_e('You don\'t have any ad to select', 'aps-ads'); ?></option>
													<?php } ?>
												</select>
											</div>
											
											<div class="aps-col-2">
												<label for="aps-ad-display"><?php esc_html_e('Ad Display', 'aps-ads'); ?></label><br />
												<select class="aps-select aps-full-width" name="aps-ads[<?php echo esc_attr($count); ?>][display]">
													<?php foreach ($ad_conditions as $ad_condition_short => $ad_condition) { ?>
														<option value="<?php echo esc_attr($ad_condition_short); ?>"<?php if ($saved_ad['display'] == $ad_condition_short) { ?> selected="selected"<?php } ?>><?php echo esc_html($ad_condition); ?></option>
													<?php } ?>
												</select>
											</div>
										</div>
										<a class="aps-del-item" href="#" title="<?php esc_attr_e('Delete Item', 'aps-ads'); ?>"><i class="aps-icon-trash"></i></a>
									</div>
								</li>
								<?php $count++;
							}
						} ?>
					</ul>
					<a class="aps-add-item aps-btn aps-btn-green" href="" data-count="<?php echo esc_attr($count); ?>" title="<?php esc_attr_e('Add New Item', 'aps-ads'); ?>"><i class="aps-icon-plus"></i> <?php esc_html_e('Add New Item', 'aps-ads'); ?></a>
				</div>
				
				<div class="ads-btn-submit">
					<input type="hidden" name="aps-nonce" value="<?php echo esc_attr($aps_nonce); ?>" />
					<input type="submit" class="button-primary" name="submit" value="<?php esc_attr_e('Save Changes', 'aps-ads'); ?>" />
				</div>
			</form>
		</div>
		<?php // create html variable for fieldset
		$fieldset = '<li class="aps-ad-sortable" id="ad-placement-%count%"><div class="aps-ads-item"><span class="dashicons dashicons-menu"></span>';
		$fieldset .= '<div class="aps-ads-row"><div class="aps-col-2"><label>' .esc_html__('Ad Placement', 'aps-ads') .'</label><br />';
		$fieldset .= '<select class="aps-select aps-select2 aps-select-hook aps-full-width" name="aps-ads[%count%][hook]">';
		foreach ($settings as $group) {
			$fieldset .= '<optgroup label="' .esc_attr($group['title']) .'">';
			foreach ($group['hooks'] as $hook => $name) {
				$fieldset .= '<option value="' .esc_attr($hook) .'">' .esc_html($name) .'</option>';
			}
			$fieldset .= '</optgroup>';
		}
		$fieldset .= '</select></div><div class="aps-col-2">';
		$fieldset .= '<label>' .esc_html__('Select Ad Unit', 'aps-ads') .'</label><br />';
		$fieldset .= '<select class="aps-select aps-select2 aps-full-width" name="aps-ads[%count%][id]">';
		if ($ads) {
			foreach ($ads as $ad_id => $ad) {
				$fieldset .= '<option value="' .esc_attr($ad_id) .'">' .esc_html($ad['title']) .' - ' .esc_html($ad['type']) .'</option>';
			}
		} else {
			$fieldset .= '<option value="0">' .esc_html__('You don\'t have any ad to select', 'aps-ads') .'</option>';
		}
		$fieldset .= '</select></div><div class="aps-col-2">';
		$fieldset .= '<label>' .esc_html__('Ad Display', 'aps-ads') .'</label><br />';
		$fieldset .= '<select class="aps-select aps-full-width" name="aps-ads[%count%][display]">';
		foreach ($ad_conditions as $ad_condition_short => $ad_condition) {
			$fieldset .= '<option value="' .esc_attr($ad_condition_short) .'">' .esc_html($ad_condition) .'</option>';
		}
		$fieldset .= '</select></div></div>';
		$fieldset .= '<a class="aps-del-item" href="#" title="' .esc_html__('Delete Item', 'aps-ads') .'"><i class="aps-icon-trash"></i></a></div></li>'; ?>
		
		<script type="text/javascript">
		jQuery(document).ready(function($) {
			"use strict";
			$("ul.aps-ads-slots").sortable({
				items: "li.aps-ad-sortable",
				opacity: 0.7,
				containment: "parent"
			});
			
			// add new item
			$(document).on("click", ".aps-add-item", function(e) {
				var add_new = $(this),
				count = add_new.data("count"),
				fieldset = '<?php echo addslashes($fieldset); ?>';
				fieldset = fieldset.replace(/%count%/g, count);
				$(".aps-ads-slots").append(fieldset);
				add_new.data("count", (count + 1));
				initializeSelect2($(".aps-select2"));
				e.preventDefault();
			});
			
			// delete item
			$(document).on("click", ".aps-del-item", function(e) {
				var del_it = confirm("<?php esc_html_e('Are you sure you want to delete this item?', 'aps-ads'); ?>");
				
				if (del_it) {
					$(this).parents("li").fadeOut(300, function() {
						$(this).remove();
					});
				}
				e.preventDefault();
			});
			
			function format_options(item) {
				var value = item.id,
				optgroup_label = item.element.parentNode.label;

				if (typeof optgroup_label != "undefined") {
					return optgroup_label +" - "+ item.text;
				} else {
					return item.text;
				}
			}
			
			// initialize select box
			function initializeSelect2(select) {
				select.select2({
					templateSelection: format_options
				}).trigger("change");
			}
			
			$(".aps-select2").each(function() {
				initializeSelect2($(this));
			});
		});
		</script>
		<?php
	}
	
	// admin dashboard widget for displaying top 10 performing ads
	add_action( 'wp_dashboard_setup', 'register_aps_ads_dashboard_widget' );
	
	function register_aps_ads_dashboard_widget() {
		wp_add_dashboard_widget( 'aps_ads_widget', esc_html__('Top 10 Performing APS Ads', 'aps-ads'), 'aps_ads_widget_content' );
		
	}
	
	// widget content
	function aps_ads_widget_content() {
		$control = '<span class="aps-ads-widget-control" data-open="' .esc_attr__('Cancel', 'aps-ads') .'" data-close="' .esc_attr__('Configure', 'aps-ads') .'">' .esc_html__('Configure', 'aps-ads') .'</span>'; ?>
		<div class="aps-ads-widget">
			<form id="ads-stat-form" action="#" method="post">
				<div class="aps-ads-widget-selector">
					<select name="stat-select" class="ads-stat-select">
						<option value="ov"><?php esc_html_e('Overall Stats', 'aps-ads'); ?></option>
						<option value="tm"><?php esc_html_e('This Month Stats', 'aps-ads'); ?></option>
						<option value="pm"><?php esc_html_e('Previous Month Stats', 'aps-ads'); ?></option>
					</select>
					<input type="submit" class="button button-primary" name="update" value="<?php esc_attr_e('Update', 'aps-ads'); ?>" />
					<input type="hidden" name="action" value="aps-ads-stats" />
				</div>
			</form>
			
			<div id="aps-ads-stats">
				<span class="loading-spinner"></span>
			</div>
		</div>
		<script type="text/javascript">
		(function($) {
			"use strict";
			$("#aps_ads_widget h2").after('<?php echo addslashes($control); ?>');
			
			$(".aps-ads-widget-control").on("click", function(e) {
				if ($(this).hasClass("opened")) {
					$(".aps-ads-widget-selector").slideUp();
					$(this).text($(this).data("close")).removeClass("opened");
				} else {
					$(".aps-ads-widget-selector").slideDown();
					$(this).text($(this).data("open")).addClass("opened");
				}
				e.preventDefault();
			});
			
			$(document).on("submit", "#ads-stat-form", function(e) {
				var form_data = $(this).serialize();
				$.ajax({
					url: ajaxurl,
					type: "POST",
					data: form_data,
					beforeSend: function() {
						$("#aps-ads-stats").html('<span class="loading-spinner"></span>');
					}
				})
				.done(function(res) {
					$("#aps-ads-stats").html(res);
					$(".ads-stat-bar").each(function(e) {
						$(this).animate({"width": $(this).data("width")});
					});
				});
				e.preventDefault();
			});
			
			$(window).on("load", function(e) {
				$("#ads-stat-form").submit();
			});
			
			// aps tooltip function
			$(document).on({
				mouseenter: function() {
					var info = $(this).data("result"),
					container = $(".aps-tooltip-display");
					$("body").append('<span class="aps-tooltip-display">' + info + '</span>').show(300);
					$(document).on("mousemove", function(e) {
						var relY = e.pageY + 20,
						relX = e.pageX + 10;
						if ($("html").attr("dir") == "rtl") {
							container.css({"top":relY, "left":relX});
						} else {
							var right_pos = $(window).width() - relX;
							container.css({"top":relY, "right":right_pos});
						}
					});
				},
				mouseleave: function() {
					var container = $(".aps-tooltip-display");
					container.hide(50, function() {
						$(this).remove();
					});
				}
			}, ".ads-stat-bar");
		})(jQuery);
		</script>
		<?php
	}
	
	// hook into admin ajax
	add_action('wp_ajax_aps-ads-stats', 'aps_ads_display_stats_chart');
	
	// get widget stats chart
	function aps_ads_display_stats_chart() {
		$period = (isset($_POST['stat-select'])) ? trim($_POST['stat-select']) : 'ov';
		aps_ads_get_stats_chart($period);
		exit;
	}
	
	// get widget stats chart
	function aps_ads_get_stats_chart($period, $num=10) {
		// ads query args
		$args = array(
			'post_type' => 'aps-ads',
			'posts_per_page' => $num,
			'orderby' => 'meta_value_num',
			'meta_value_num' => 0,
			'meta_compare' => '>'
		);
		
		switch ($period) {
			// Overall
			case 'ov':
				$args['meta_key'] = 'aps-ad-views';
			break;
			
			// This Months
			case 'tm':
				$date = date('m-Y');
				$args['meta_key'] = 'aps-ad-views-' .$date;
			break;
			
			// Previous
			case 'pm':
				$date = date('m-Y', strtotime('first day of previous month'));
				$args['meta_key'] = 'aps-ad-views-' .$date;
			break;
		}
		
		$ads_query = new WP_Query($args);
		
		// start the loop
		if ( $ads_query->have_posts() ) :
			$ads = array();
			$top_views = 0;
			while ( $ads_query->have_posts() ) :
					$ads_query->the_post();
					global $post;
					$pid = $post->ID;
					
					$views = get_post_meta($pid, $args['meta_key'], true);
					$ads[$pid] = array(
						'title' => get_the_title(),
						'views' => $views
					);
					
					if ($views > $top_views) {
						$top_views = $views;
					}
			endwhile;
		endif;
		// reset query data
		wp_reset_postdata();
		
		// start the loop
		if ($ads) {
			if ($top_views <= 100) {
				$multiplier = 100;
				$rules = array('20', '40', '60', '80', '100');
			} elseif ($top_views > 100 && $top_views <= 500) {
				$multiplier = 500;
				$rules = array('100', '200', '300', '400', '500');
			} elseif ($top_views > 500 && $top_views <= 1000) {
				$multiplier = 1000;
				$rules = array('200', '400', '600', '800', '1k');
			} elseif ($top_views > 1000 && $top_views <= 2000) {
				$multiplier = 2000;
				$rules = array('400', '800', '1.2k', '1.6k', '2k');
			} elseif ($top_views > 2000 && $top_views <= 5000) {
				$multiplier = 5000;
				$rules = array('1k', '2k', '3k', '4k', '5k');
			} elseif ($top_views > 5000 && $top_views <= 10000) {
				$multiplier = 10000;
				$rules = array('2k', '4k', '6k', '8k', '10k');
			} elseif ($top_views > 10000 && $top_views <= 20000) {
				$multiplier = 20000;
				$rules = array('4k', '8k', '12k', '16k', '20k');
			} elseif ($top_views > 20000 && $top_views <= 50000) {
				$multiplier = 50000;
				$rules = array('10k', '20k', '30k', '40k', '50k');
			} elseif ($top_views > 50000 && $top_views <= 100000) {
				$multiplier = 100000;
				$rules = array('20k', '40k', '60k', '80k', '.1m');
			} elseif ($top_views > 100000 && $top_views <= 1000000) {
				$multiplier = 1000000;
				$rules = array('.2m', '.4m', '.6m', '.8m', '1m');
			} elseif ($top_views > 1000000 && $top_views <= 10000000) {
				$multiplier = 10000000;
				$rules = array('2m', '4m', '6m', '8m', '10m');
			} elseif ($top_views > 10000000) {
				$multiplier = 1000000000;
				$rules = array('20m', '40m', '60m', '80m', '100m');
			} ?>
			<ul class="ads-stats-list">
				<li>
					<div class="ads-stats-header">
						<span class="ads-stats-rule">0</span>
						<span class="ads-stats-rule"><?php echo esc_html($rules[0]); ?></span>
						<span class="ads-stats-rule"><?php echo esc_html($rules[1]); ?></span>
						<span class="ads-stats-rule"><?php echo esc_html($rules[2]); ?></span>
						<span class="ads-stats-rule"><?php echo esc_html($rules[3]); ?></span>
						<span class="ads-stats-rule"><?php echo esc_html($rules[4]); ?></span>
					</div>
				</li>
				<?php foreach ($ads as $ad) {
					$percentage = ($ad['views'] / $multiplier) * 100;
					echo '<li><div class="ads-stats-result"><span class="ads-stat-title">' .esc_html($ad['title']) .'</span><span class="ads-stat-bar" data-result="' .esc_attr($ad['views']) .' ' .esc_attr__('views', 'aps-ads') .'" data-width="' .esc_attr($percentage) .'%"></span></div></li>';
				} ?>
			</ul>
		<?php } else { ?>
			<p><?php esc_html_e('No ads found for your selected period', 'aps-ads'); ?></p>
		<?php }
	}
	