<?php if (!defined('APS_ADS_VER')) exit('restricted access');
/*
 * @package WordPress
 * @subpackage APS Ads
*/
	// add action register our post type aps-ads
	add_action( 'init', 'register_cpt_aps_ads' );
	
	// Register our Custom Post type as aps-ads
	function register_cpt_aps_ads() {
		// labels text for our post type aps-products
		$labels = array(
			// post type general name
			'name' => __( 'APS Ads', 'aps-ads' ),
			// post type singular name
			'singular_name' => __( 'APS Ad Unit', 'aps-ads' ),
			'name_admin_bar' => __( 'APS Ad Unit', 'aps-ads' ),
			'menu_name' => __( 'Ad Units', 'aps-ads' ),
			'add_new' => __( 'Add New APS Ad Unit', 'aps-ads' ),
			'add_new_item' => __( 'Add New APS Ad Unit', 'aps-ads' ),
			'edit_item' => __( 'Edit APS Ad Unit', 'aps-ads' ),
			'new_item' => __( 'New APS Ad Unit', 'aps-ads' ),
			'view_item' => __( 'View APS Ad Unit', 'aps-ads' ),
			'archives' => __( 'APS Ad Units Archives', 'aps-ads' ),
			'search_items' => __( 'Search APS Ad Units', 'aps-ads' ),
			'insert_into_item' => __( 'Insert into APS Ad Unit', 'aps-ads' ),
			'featured_image' => __( 'APS Ad Unit Image', 'aps-ads' ),
			'set_featured_image' => __( 'Set APS Ad Unit Image', 'aps-ads' ),
			'remove_featured_image' => __( 'Remove APS Ad Unit Image', 'aps-ads' ),
			'use_featured_image' => __( 'Use as APS Ad Unit image', 'aps-ads' ),
			'not_found' =>  __( 'No APS Ad Units found', 'aps-ads' ),
			'not_found_in_trash' => __( 'No APS Ad Units found in Trash', 'aps-ads' )
		);
		
		$args = array(
			'labels' => $labels,
			'public' => false,
			'show_ui' => true,
			'query_var' => true,
			'publicly_queryable' => true,
			'show_in_nav_menus' => false,
			'menu_icon' => 'dashicons-products',
			'capability_type' => 'aps-products',
			'capabilities' => array(
			   'read_post' => 'read_aps_product',
			   'edit_post' => 'edit_aps_product',
			   'edit_posts' => 'edit_aps_products',
			   'delete_posts' => 'delete_aps_products',
			   'create_posts' => 'edit_aps_products',
			   'publish_posts' => 'publish_aps_products',
			   'edit_published_posts' => 'edit_published_aps_products',
			   'delete_published_posts' => 'delete_published_aps_products',
			   'edit_others_posts' => 'edit_others_aps_products',
			   'delete_others_posts' => 'delete_others_aps_products',
			   'read_private_posts' => 'read_private_aps_products',
			   'edit_private_posts' => 'edit_private_aps_products',
			   'delete_private_posts' => 'delete_private_aps_products'
			),
			'map_meta_cap' => true,
			'hierarchical' => false,
			'exclude_from_search' => false,
			'has_archive' => false,
			'show_in_menu' => 'aps-ads',
			'show_in_rest' => false,
			'supports' => array( 'title', 'author' ),
			'register_meta_box_cb' => 'add_aps_ads_metabox',
			'rewrite' => false
		);
		
		register_post_type( 'aps-ads', $args );
	}
	
	// add filter to insure the text APS Ads, is displayed when user updates
	add_filter( 'post_updated_messages', 'aps_ads_updated_messages' );
	
	function aps_ads_updated_messages( $messages ) {
		global $post;
		
		$messages['aps-ads'] = array(
			0 => '', // Unused. Messages start at index 1.
			1 => __( 'Ad Unit updated.', 'aps-ads'),
			2 => __( 'Custom field updated.', 'aps-ads' ),
			3 => __( 'Custom field deleted.', 'aps-ads' ),
			4 => __( 'Ad Unit updated.', 'aps-ads' ),
			// translators: %s: date and time of the revision
			5 => isset( $_GET['revision'] ) ? sprintf( __( 'Ad restored to revision from %s', 'aps-ads' ), wp_post_revision_title( ( int ) $_GET['revision'], false ) ) : false,
			6 => __( 'Ad Unit published.', 'aps-ads' ),
			7 => __( 'Ad Unit saved.', 'aps-ads' ),
			8 => __( 'Ad Unit submitted.', 'aps-ads' ),
			9 => sprintf( __( 'Ad Unit scheduled for: <strong>%1$s</strong>.', 'aps-ads' ), date_i18n( __( 'M j, Y @ G:i' ) )),
			10 => __( 'Ad Unit draft updated.', 'aps-ads' )
		);
		return $messages;
	}
	
	// Add meta boxses
	function add_aps_ads_metabox() {
		add_meta_box( 'aps_ads_meta_box', __( 'APS Ad Unit', 'aps-ads' ), 'aps_ads_metabox', 'aps-ads', 'normal', 'core' );
	}
	
	function aps_ads_metabox($post) {
		$ad_format = ($ad_format = get_post_meta($post->ID, 'aps-ad-format', true)) ? $ad_format : 'image_banner';
		$ad_layout = ($ad_layout = get_post_meta($post->ID, 'aps-ad-layout', true)) ? $ad_layout : 'l';
		$ad_margin = ($ad_margin = get_post_meta($post->ID, 'aps-ad-margin', true)) ? $ad_margin : array('t' => 0, 'r' => 0, 'b' => 0, 'l' => 0);
		$ad_meta = ($ad_meta = get_post_meta($post->ID, 'aps-ad-meta', true)) ? $ad_meta : '';
		
		switch ($ad_format) {
			case 'image_banner':
					$img_id = (isset($ad_meta['img'])) ? $ad_meta['img'] : null;
					$img_link = (isset($ad_meta['link'])) ? $ad_meta['link'] : null;
					$img_tab = (isset($ad_meta['tab'])) ? $ad_meta['tab'] : null;
					$img_url = (isset($img_id)) ? wp_get_attachment_url($img_id) : null;
				break;
				
				case 'adsense_ad':
					$adsense_id = (isset($ad_meta['id'])) ? $ad_meta['id'] : null;
					$adsense_type = (isset($ad_meta['type'])) ? $ad_meta['type'] : null;
				break;
				
				case 'plain_text':
					$plain_text = wp_unslash($ad_meta);
				break;
				
				case 'rich_content':
					$rich_content = $ad_meta;
				break;
				
				case 'custom_ad':
					$custom_ad = esc_textarea($ad_meta);
				break;
		}
		
		// generate HTML for our meta box ?>
		<div class="admin-inside-box clearfix">
			<div class="aps-wrap aps-ads-metabox">
				<input type="hidden" name="aps_ad_meta_nonce" value="<?php echo wp_create_nonce( basename(__FILE__) ); ?>" />
				<h4><?php esc_html_e('Ad Type', 'aps-ads'); ?></h4>
				<ul class="aps-ad-selector">
					<li>
						<label>
							<input type="radio" name="ad_format" value="image_banner"<?php if ($ad_format == 'image_banner') { ?> checked="checked"<?php } ?> autocomplete="off" />
							<span class="ad-type-btn image-banner-btn"><?php esc_html_e('Image Banner', 'aps-ads'); ?></span>
						</label>
					</li>
					<li>
						<label>
							<input type="radio" name="ad_format" value="adsense_ad"<?php if ($ad_format == 'adsense_ad') { ?> checked="checked"<?php } ?> autocomplete="off" />
							<span class="ad-type-btn adsense-ad-btn"><?php esc_html_e('Adsense Ad', 'aps-ads'); ?></span>
						</label>
					</li>
					<li>
						<label>
							<input type="radio" name="ad_format" value="plain_text"<?php if ($ad_format == 'plain_text') { ?> checked="checked"<?php } ?> autocomplete="off" />
							<span class="ad-type-btn plain-text-btn"><?php esc_html_e('Plain Text Ad', 'aps-ads'); ?></span>
						</label>
					</li>
					<li>
						<label>
							<input type="radio" name="ad_format" value="rich_content"<?php if ($ad_format == 'rich_content') { ?> checked="checked"<?php } ?> autocomplete="off" />
							<span class="ad-type-btn rich-content-btn"><?php esc_html_e('Rich Content Ad', 'aps-ads'); ?></span>
						</label>
					</li>
					<li>
						<label>
							<input type="radio" name="ad_format" value="custom_ad"<?php if ($ad_format == 'custom_ad') { ?> checked="checked"<?php } ?> autocomplete="off" />
							<span class="ad-type-btn custom-ad-btn"><?php esc_html_e('Custom Code', 'aps-ads'); ?></span>
						</label>
					</li>
				</ul>
				<div class="clear"></div>
				
				<div class="ad-form-control">
					<h4><?php esc_html_e('Ad Position', 'aps-ads'); ?></h4>
					<span class="ad-layout-input">
						<label>
							<input type="radio" name="ad_layout" value="l"<?php if ($ad_layout == 'l') { ?> checked="checked"<?php } ?> autocomplete="off" />
							<span class="ad-layout-btn ad-layout-l"></span>
						</label>
					</span>
					<span class="ad-layout-input">
						<label>
							<input type="radio" name="ad_layout" value="c"<?php if ($ad_layout == 'c') { ?> checked="checked"<?php } ?> autocomplete="off" />
							<span class="ad-layout-btn ad-layout-c"></span>
						</label>
					</span>
					<span class="ad-layout-input">
						<label>
							<input type="radio" name="ad_layout" value="r"<?php if ($ad_layout == 'r') { ?> checked="checked"<?php } ?> autocomplete="off" />
							<span class="ad-layout-btn ad-layout-r"></span>
						</label>
					</span>
				</div>
				<div class="clear"></div>
				
				<div class="ad-input-wrap">
					<h4><?php esc_html_e('Margin', 'aps-ads'); ?></h4>
					<div class="ad-form-control">
						<?php esc_html_e('Top', 'aps-ads'); ?> 
						<input type="number" name="ad_margin[t]" value="<?php echo esc_attr($ad_margin['t']); ?>" /> px 
					</div>
					<div class="ad-form-control">
						<?php esc_html_e('Right', 'aps-ads'); ?> 
						<input type="number" name="ad_margin[r]" value="<?php echo esc_attr($ad_margin['r']); ?>" /> px
					</div>
					<div class="ad-form-control">
						<?php esc_html_e('Bottom', 'aps-ads'); ?> 
						<input type="number" name="ad_margin[b]" value="<?php echo esc_attr($ad_margin['b']); ?>" /> px
					</div>
					<div class="ad-form-control">
						<?php esc_html_e('Left', 'aps-ads'); ?> 
						<input type="number" name="ad_margin[l]" value="<?php echo esc_attr($ad_margin['l']); ?>" /> px
					</div>
				</div>
				
				<div class="ad-settings-content">
					<div class="ad-tab-content<?php if ($ad_format == 'image_banner') { ?> active-tab<?php } ?>" id="image_banner">
						<h4><?php esc_html_e('Image Banner', 'aps-ads'); ?></h4>
						<div class="ad-input-wrap">
							<button class="button aps-media-upload"><span class="dashicons dashicons-format-image"></span> <?php esc_html_e('Banner Image', 'aps-ads'); ?></button>
							<div class="clear"></div>
							<div id="au-img-thumb" class="<?php if (isset($img_url)) { ?>aps-img-active<?php } ?>">
								<img src="<?php if (isset($img_url)) echo esc_url($img_url); ?>" alt="Image" />
								<span class="aps-img-del" title="<?php esc_attr_e('Remove image', 'aps-ads'); ?>"><span class="dashicons dashicons-dismiss"></span></span>
							</div>
							<input type="hidden" name="image_banner[img]" class="ad-image" value="<?php if (isset($img_id)) echo esc_attr($img_id); ?>" />
						</div>
						
						<div class="ad-input-wrap">
							<div class="ad-form-control">
								<label><?php esc_html_e('Link', 'aps-ads'); ?></label>
								<input type="text" name="image_banner[link]" class="ads-text-input" value="<?php if (isset($img_link)) echo esc_url($img_link); ?>" />
							</div>
							
							<div class="ad-form-control">
								<label>
									<?php esc_html_e('Open Link in New Tab', 'aps-ads'); ?>
									<input type="checkbox" class="aps-cb-input" name="image_banner[tab]" value="new"<?php if (isset($img_tab)) { ?> checked="checked"<?php } ?> />
									<span class="aps-cb-switch"></span>
								</label>
							</div>
						</div>
					</div>
					
					<div class="ad-tab-content<?php if ($ad_format == 'adsense_ad') echo ' active-tab'; ?>" id="adsense_ad">
						<h4><?php esc_html_e('Adsense Ad', 'aps-ads'); ?></h4>
						<div class="ad-input-wrap">
							<div class="ad-form-control">
								<label><?php esc_html_e('Ad Slot ID', 'aps-ads'); ?></label>
								<input type="text" name="adsense_ad[id]" class="ads-text-input" value="<?php if (isset($adsense_id)) echo esc_attr($adsense_id); ?>" />
							</div>
							
							<div class="ad-form-control">
								<label><?php esc_html_e('Unit Type', 'aps-ads'); ?></label>
								<select name="adsense_ad[type]">
									<option value="auto"<?php if (isset($adsense_type) && $adsense_type == 'auto') { ?> selected="selected"<?php } ?>><?php esc_html_e('Auto', 'aps-ads'); ?></option>
									<option value="vertical"<?php if (isset($adsense_type) && $adsense_type == 'vertical') { ?> selected="selected"<?php } ?>><?php esc_html_e('Vertical', 'aps-ads'); ?></option>
									<option value="horizontal"<?php if (isset($adsense_type) && $adsense_type == 'horizontal') { ?> selected="selected"<?php } ?>><?php esc_html_e('Horizontal', 'aps-ads'); ?></option>
									<option value="rectangle"<?php if (isset($adsense_type) && $adsense_type == 'rectangle') { ?> selected="selected"<?php } ?>><?php esc_html_e('Rectangle', 'aps-ads'); ?></option>
								</select>
							</div>
						</div>
					</div>
					
					<div class="ad-tab-content<?php if ($ad_format == 'plain_text') { ?> active-tab<?php } ?>" id="plain_text">
						<h4><?php esc_html_e('Plain Text Ad', 'aps-ads'); ?></h4>
						<p><?php esc_html_e('You may put your plain text ad in the textarea below, no links, no fomatting.', 'aps-ads'); ?></p>
						<div class="ad-input-wrap">
							<textarea name="plain_text" class=""><?php if (isset($plain_text)) echo esc_textarea($plain_text); ?></textarea>
						</div>
					</div>
					
					<div class="ad-tab-content<?php if ($ad_format == 'rich_content') { ?> active-tab<?php } ?>" id="rich_content">
						<h4><?php esc_html_e('Rich Content Ad', 'aps-ads'); ?></h4>
						<p><?php esc_html_e('You may put anything like images, links, text, shortcodes in your ad by using Rich Content editor.', 'aps-ads'); ?></p>
						<div class="ad-input-wrap">
							<?php $ed_content = (isset($rich_content)) ? $rich_content : '';
							wp_editor( $ed_content, 'ad_editor' ); ?>
						</div>
					</div>
					
					<div class="ad-tab-content<?php if ($ad_format == 'custom_ad') { ?> active-tab<?php } ?>" id="custom_ad">
						<h4><?php esc_html_e('Custom Code', 'aps-ads'); ?></h4>
						<p><?php esc_html_e('You may put your custom ad which contains HTML, CSS, JavaScript and PHP code in the editor below, make sure the code is valid and tested for errors.', 'aps-ads'); ?></p>
						<div class="ad-input-wrap">
							<textarea id="custom-code" name="custom_ad" class=""><?php if (isset($custom_ad)) echo aps_esc_output_content($custom_ad); ?></textarea>
						</div>
					</div>
				</div>
			</div>
			<script type="text/javascript">
			(function($) {
				"use strict";
				/* tabs */
				$(document).on("click", ".aps-ad-selector input", function(e) {
					var tab_id = $(this).val();
					$("#" + tab_id).addClass("active-tab").siblings().removeClass("active-tab");
					aps_ads_code_editor();
				});
				
				var code = '<div class="copy-code"><?php esc_html_e('Shortcode', 'aps-ads'); ?>: <span>[aps_ad id=&quot;<?php echo $post->ID; ?>&quot;]</span> <?php _e('Template function', 'aps-ads'); ?>: <span>&lt;?php echo aps_ad(<?php echo $post->ID; ?>); ?&gt;</span></div>';
				$("#post-body-content").after(code);
				
				// media upload
				$(document).on("click", ".aps-media-upload", function(e) {
					var frame = wp.media({
						title : "<?php esc_html_e('Select Banner Image', 'aps-ads'); ?>",
						multiple: false,
						library : { type : "image"},
						button : { text : "<?php esc_html_e('Insert Image', 'aps-ads'); ?>" },
					});
					frame.on("select", function() {
						var selection = frame.state().get("selection");
						selection.each(function(image) {
							var image_id = image.attributes.id;
							$(".ad-image").val(image_id);
							$("#au-img-thumb img").attr("src", image.attributes.url).slideDown();
							$(".aps-img-del").parent().addClass("aps-img-active");
						});
					});
					frame.open();
					e.preventDefault();
				});
				
				$(document).on("click", ".aps-img-del", function(e) {
					$(this).prev("img").slideUp("slow", function() {
						$(this).attr("src", "");
						$(this).parent().removeClass("aps-img-active");
					});
				});
				
				function aps_ads_code_editor() {
					if ($("#custom_ad").hasClass("active-tab") && !$("#custom-code").hasClass("ed-initialized")) {
						/* code editor */
						wp.codeEditor.initialize("custom-code");
						$("#custom-code").addClass("ed-initialized");
					}
				}
				aps_ads_code_editor();
			})(jQuery);
			</script>
		</div>
		<?php
	}
	
	// add action to print aps_product styles in post editing
	add_action( 'admin_print_styles-post-new.php', 'add_aps_ads_styles', 11 );
	add_action( 'admin_print_styles-post.php', 'add_aps_ads_styles', 11 );
	
	// enqueue aps-ads backend styles
	function add_aps_ads_styles() {
		global $post;
		
		if ( $post->post_type == 'aps-ads' ) {
			
			// enqueue APS plugin custom css
			wp_enqueue_style( 'aps-admin-styles' );
			
			// enqueue APS ads css styles
			wp_enqueue_style( 'aps-ads-css' );
			
			// enqueue code editor
			wp_enqueue_code_editor( array( 'type' => 'application/x-httpd-php' ) );
		}
	}
	
	// custom columns
	add_filter( 'manage_edit-aps-ads_columns', 'aps_ads_edit_columns' );
	
	function aps_ads_edit_columns( $columns ) {
		$aps_columns = array(
			'type' => __('Ad Type', 'aps-ads'),
			'shortcode' => __('Shortcode', 'aps-ads'),
			'views' => __('Views', 'aps-ads')
		);
		
		$columns = array_slice($columns, 0, 2, true) + $aps_columns + array_slice($columns, 2, count($columns) - 1, true);
		
		return $columns;
	}
	
	// custom columns display
	add_action( 'manage_aps-ads_posts_custom_column', 'aps_ads_custom_columns' );
	
	function aps_ads_custom_columns( $column ) {
		global $post;
		
		switch ( $column ) {
			// shortcode column
			case 'type' :
				$ad_format = get_post_meta( $post->ID, 'aps-ad-format', true );
				$type = get_readable_aps_ad_format($ad_format);
				echo esc_html($type);
			break;
			
			// shortcode column
			case 'shortcode' :
				echo '[aps_ad id="' .esc_attr($post->ID) .'"]';
			break;
			
			// shortcode column
			case 'views' :
				$views = aps_ads_get_views($post->ID);
				echo format_aps_views_count($views);
			break;
		}
	}
	
	// save ads meta data
	add_action( 'save_post', 'save_aps_ad_metadata' );
	
	function save_aps_ad_metadata( $post_id ) {
		global $post;
		
		$post_type = (isset($_POST['post_type'])) ? $_POST['post_type'] : null;
		
		// check if post type == aps-ads
		if ($post_type == 'aps-ads') {
			
			$post_id = $_POST['post_ID'];
			$nonce = $_POST['aps_ad_meta_nonce'];
			
			// verify nonce
			if ( !current_user_can('edit_aps_product', $post_id) || !wp_verify_nonce($nonce, basename(__FILE__)) ) {
				return $post_id;
			}
			
			// get ad format from input fields
			$ad_format = (isset($_POST['ad_format'])) ? $_POST['ad_format'] : 'image_banner';
			$ad_layout = (isset($_POST['ad_layout'])) ? $_POST['ad_layout'] : array();
			$ad_margin = (isset($_POST['ad_margin'])) ? $_POST['ad_margin'] : array();
			
			
			// save data in post meta fields
			update_post_meta( $post_id, 'aps-ad-format', $ad_format );
			update_post_meta( $post_id, 'aps-ad-layout', $ad_layout );
			update_post_meta( $post_id, 'aps-ad-margin', $ad_margin );
			
			switch ($ad_format) {
				case 'image_banner':
					$image_banner = (isset($_POST['image_banner'])) ? $_POST['image_banner'] : array();
					$ad_meta = array(
						'img' => (isset($image_banner['img'])) ? $image_banner['img'] : '',
						'link' => (isset($image_banner['link'])) ? $image_banner['link'] : '',
						'tab' => (isset($image_banner['tab'])) ? $image_banner['tab'] : ''
					);
				break;
				
				case 'adsense_ad':
					$adsense_ad = (isset($_POST['adsense_ad'])) ? $_POST['adsense_ad'] : array();
					$ad_meta = array(
						'id' => (isset($adsense_ad['id'])) ? $adsense_ad['id'] : '',
						'type' => (isset($adsense_ad['type'])) ? $adsense_ad['type'] : ''
					);
				break;
				
				case 'plain_text':
					$plain_text = (isset($_POST['plain_text'])) ? trim($_POST['plain_text']) : '';
					$ad_meta = $plain_text;
				break;
				
				case 'rich_content':
					$rich_content = (isset($_POST['ad_editor'])) ? trim($_POST['ad_editor']) : '';
					$ad_meta = $rich_content;
				break;
				
				case 'custom_ad':
					global $wp_filesystem;
					WP_Filesystem();
					
					$custom_ad = (isset($_POST['custom_ad'])) ? trim($_POST['custom_ad']) : '';
					$file_name = APS_ADS_DIR .'/inc/code/ad-code-' .$post_id .'.php';
					$file_content = "<?php if (!defined('APS_ADS_VER')) exit('restricted access'); ?> \r\n" .wp_unslash($custom_ad);
					$wp_filesystem->put_contents($file_name, $file_content);
					$ad_meta = $custom_ad;
				break;
			}
			
			update_post_meta( $post_id, 'aps-ad-meta', $ad_meta );
			
			// hook custom callback on save product's meta
			do_action('save_aps_ads_metadata', $post_id);
		}
	}
	
	// human readable ad format
	function get_readable_aps_ad_format($ad_format) {
		$ad_types = array(
			'image_banner' => __('Image Banner', 'aps-ads'),
			'adsense_ad' => __('Adsense Ad', 'aps-ads'),
			'plain_text' => __('Plain Text Ad', 'aps-ads'),
			'rich_content' => __('Rich Content Ad', 'aps-ads'),
			'custom_ad' => __('Custom Ad', 'aps-ads')
		);
		
		return $ad_types[$ad_format];
	}
	
	// get ad views by id
	function aps_ads_get_views($id) {
		$views = ($data = get_post_meta($id, 'aps-ad-views', true)) ? (int) $data : 0;
		return $views;
	}
	
	// update ad views by id
	function aps_ads_update_views($id) {
		$old_views = aps_ads_get_views($id);
		$views = $old_views + 1;
		update_post_meta($id, 'aps-ad-views', $views);
		
		// update views history
		aps_ads_update_views_history($id);
	}
	
	// get ad views history by id
	function aps_ads_get_views_history($id, $month) {
		$views_history = ($data = get_post_meta($id, 'aps-ad-views-' .$month, true)) ? $data : 0;
		return $views_history;
	}
	
	// update ad views history by id
	function aps_ads_update_views_history($id) {
		$month = date('m-Y');
		$views_history = aps_ads_get_views_history($id, $month);
		$views = $views_history + 1;
		update_post_meta($id, 'aps-ad-views-' .$month, $views);
	}
	