<?php
class Pro_Ads_API {	

	public function __construct() 
	{
		// API adzone request ---------------------------------------------------
		add_action( 'wp_loaded', array( $this, 'wp_pro_ad_api_load_adzone' ) );
		add_action( 'wp_loaded', array( $this, 'wppas_api_load_adzone' ));	
		
		// API banner request ---------------------------------------------------
		add_action( 'wp_loaded', array( $this, 'wppas_api_load_banner' ) );	
		// API Download banner as image ---------------------------------------------------
		add_action( 'wp_loaded', array( $this, 'wppas_api_download_banner' ) );	
		// REST API data request ------------------------------------------------ 
		//add_action( 'wp_loaded', array( $this, 'wp_pro_ad_rest_api_load_data' ) );	
		
		// Filters --------------------------------------------------------------
		//add_filter( 'template_include', array($this, 'wppas_api_template'), 1 );
		add_filter( 'wpproads_api_display_adzone', array($this, 'wp_pro_ads_api_display_adzone'));
		add_filter( 'wpproads_api_create_adzone', array($this, 'wp_pro_ads_api_create_adzone'));
	}
	
	
	
	
	
	
	
	
	/*
	 * API Allow developers to display/create default Adzones.
	 *
	 * @access public
	 * @return string
	*/
	function wp_pro_ads_api_display_adzone( $args )
	{
		global $wpdb, $pro_ads_multisite, $pro_ads_main;
		
		$defaults = array(
			'name'             => '',
			'description'      => '',
			'size'             => '300x250',
			'center'           => 1,
			'hide_empty'       => 0,
			'rotation'         => 0,
			'rotation_type'    => 'bxslider',
			'rotation_time'    => 3,
			'rotation_effect'  => 'fade',
			'rotation_order'   => 'fixed',
			'fix_size'         => 1,
			'default_url'      => ''
		);
		$adzone = wp_parse_args( $args, $defaults );
		
		if( !empty($adzone['name']))
		{
			// Check if adzone exists.
			$query = $wpdb->get_results("SELECT ID FROM ".$pro_ads_multisite->wpproads_db_prefix()."posts WHERE post_name = '" . sanitize_title($adzone['name']) . "' LIMIT 1");
			
			if( $query ) 
			{
				$adzone_id = $query[0]->ID;
			} 
			else 
			{
				$adzone_id = $this->api_create_adzone($adzone);
			}
			
			return do_shortcode("[pro_ad_display_adzone id=".$adzone_id."]");
		}
	}
	
	
	
	
	/*
	 * API Allow developers to create Adzones.
	 *
	 * @access public
	 * @return ID
	*/
	public function wp_pro_ads_api_create_adzone( $args )
	{
		global $wpdb, $pro_ads_multisite, $pro_ads_main;
		
		$defaults = array(
			'name'             => '',
			'description'      => '',
			'size'             => '300x250',
			'center'           => 1,
			'hide_empty'       => 0,
			'rotation'         => 0,
			'rotation_type'    => 'bxslider',
			'rotation_time'    => 3,
			'rotation_effect'  => 'fade',
			'rotation_order'   => 'fixed',
			'fix_size'         => 1,
			'default_url'      => ''
		);
		$adzone = wp_parse_args( $args, $defaults );
		
		if( !empty($adzone['name']))
		{
			// Check if adzone exists.
			$query = $wpdb->get_results("SELECT ID FROM ".$pro_ads_multisite->wpproads_db_prefix()."posts WHERE post_name = '" . sanitize_title($adzone['name']) . "' LIMIT 1");
			
			if( !$query ) 
			{
				$adzone_id = $this->api_create_adzone($adzone);
			}
			
			return $adzone_id;
		}
	}
	
	
	
	
	public function api_create_adzone( $adzone )
	{
		global $current_user, $pro_ads_main;
		
		$data = array(
			'post_title'       		=> $adzone['name'],
			'post_content'     		=> '',
			'post_status'      		=> 'publish',
			'post_type'        		=> 'adzones',
			'post_date'             => date('Y-m-d H:i:s', $pro_ads_main->time_by_timezone()),
			'post_date_gmt'         => date('Y-m-d H:i:s', time()),
			'post_author'           => $current_user->ID,
			'ping_status'           => get_option('default_ping_status'), 
			'post_parent'           => 0,
			'menu_order'            => 0,
			'to_ping'               => '',
			'pinged'                => '',
			'post_password'         => '',
			'guid'                  => '',
			'post_content_filtered' => '',
			'post_excerpt'          => '',
			'import_id'             => 0,
			'tags_input'            => '',
			'filter' => true	
		);	
		$adzoneID = wp_insert_post( $data );
		
		// Check if custom size
		$sizes = $pro_ads_main->available_banner_sizes(0);
		$custom_size = in_array($adzone['size'], $sizes) ? 0 : 1;
		
		update_post_meta( $adzoneID, '_adzone_description', $adzone['description'] );
		update_post_meta( $adzoneID, '_adzone_custom_size', $custom_size );
		update_post_meta( $adzoneID, '_adzone_size', $adzone['size'] );	
		update_post_meta( $adzoneID, '_adzone_fix_size', $adzone['fix_size'] );
		update_post_meta( $adzoneID, '_adzone_rotation_type', $adzone['rotation_type'] );
		update_post_meta( $adzoneID, '_adzone_rotation', $adzone['rotation'] );
		update_post_meta( $adzoneID, '_adzone_rotation_time', $adzone['rotation_time'] );
		update_post_meta( $adzoneID, '_adzone_rotation_effect', $adzone['rotation_effect'] );
		update_post_meta( $adzoneID, '_adzone_rotation_order', $adzone['rotation_order'] );
		update_post_meta( $adzoneID, '_adzone_center', $adzone['center'] );
		update_post_meta( $adzoneID, '_adzone_hide_empty', $adzone['hide_empty'] );
		update_post_meta( $adzoneID, '_adzone_default_url', $adzone['default_url'] );
		
		return $adzoneID;
	}
	
	
	
	/*
	 * Api load banner / adzone
	 *
	 * Not longer used since v5.2.6 - problems loading in some themes (for some unknown reason) 
	 *
	 * @access public
	 * @return html
	*/
	public function wppas_api_template($single)
	{
		if( isset( $_GET['wppasbid'] ) && !empty( $_GET['wppasbid'] ) || isset( $_GET['wppasaid'] ) && !empty( $_GET['wppasaid'] ))
		{
			return WP_ADS_TPL_DIR. '/API/banner.php';
		}
		
		return $single;
	}
	
	
	
	
	
	
	
	
	public function wppas_api_load_banner()
	{
		global $pro_ads_multisite;
		
		if( isset( $_GET['wppasbid'] ) && !empty( $_GET['wppasbid'] ))
		{
			
			$html = '';
			$id = !empty( $_GET['wppasbid'] ) ? $_GET['wppasbid'] : 0;
			$custom_css = get_option('wpproads_custom_css', '');
			$wppas_dev_mode = get_option('wppas_dev_mode', 0);
			$script = !$wppas_dev_mode ? 'jquery.wppas.vbc.min.js' : '__dv/jquery.wppas.vbc.js';
			
			$html.= '<!DOCTYPE>';
			$html.= '<html>';
				$html.= '<head>';
					$html.= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
					
					/*$html.= '<script type="text/javascript" src="'.get_bloginfo('wpurl').'/wp-admin/load-scripts.php?load=jquery-core"></script>';*/
					$html.= '<script type="text/javascript" src="'.$pro_ads_multisite->wpproads_get_site_url().'/wp-includes/js/jquery/jquery.js?ver=1.12.4"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/vbc/postscribe.min.js"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/vbc/'.$script.'"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/vbc/jquery-ui-effects.min.js"></script>';
					
					
					$html.= '<link rel="stylesheet" href="'.WP_ADS_URL.'public/assets/css/vbc/wppas_vbc_bnr.css" type="text/css" media="all" />';
					$html.= '<link rel="stylesheet" href="'.WP_ADS_INC_URL.'/font-awesome/css/font-awesome.min.css" type="text/css" media="all" />';
					$html.= apply_filters('wppas_api_head', '');
					$html.= '<style type="text/css">body{ margin:0; padding:0; '.$custom_css.' }</style>';
					
					$html.= '<title>WP PRO ADVERTISING SYSTEM - All In One Ad Manager for Wordpress</title>';
				$html.= '</head>';
				$html.= '<body>';
					
					$html.= do_shortcode('[wpproads id="'.$id.'"]');
					
				$html.= '</body>';
			$html.= '</html>';
			// Fix for some themes
			$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/vbc/'.$script.'"></script>';
			
			echo $html;
			
			exit();
		}
	}
	
	
	
	
	/*
	 * Api load adzone
	 * @since v5.1.4
	 *
	 * @access public
	 * @return html
	*/
	public function wppas_api_load_adzone()
	{
		global $pro_ads_multisite;
		
		if( isset( $_GET['wppasaid'] ) && !empty( $_GET['wppasaid'] ))
		{	
			$html = '';
			$id = !empty( $_GET['wppasaid'] ) ? $_GET['wppasaid'] : 0;
			$wppas_dev_mode = get_option('wppas_dev_mode', 0);
			$script = !$wppas_dev_mode ? 'jquery.wppas.vbc.min.js' : '__dv/jquery.wppas.vbc.js';
			$custom_css = get_option('wpproads_custom_css', '');
			
			$html.= '<!DOCTYPE>';
			$html.= '<html>';
				$html.= '<head>';
					$html.= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
					$html.= '<script type="text/javascript" src="'.$pro_ads_multisite->wpproads_get_site_url().'/wp-includes/js/jquery/jquery.js?ver=1.12.4"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/vbc/postscribe.min.js"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/vbc/'.$script.'"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/vbc/jquery-ui-effects.min.js"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/slide/jssor.slider.min.js"></script>';
					
					$html.= '<link rel="stylesheet" href="'.WP_ADS_URL.'public/assets/css/vbc/wppas_vbc_bnr.css" type="text/css" media="all" />';
					$html.= '<link rel="stylesheet" href="'.WP_ADS_INC_URL.'/font-awesome/css/font-awesome.min.css" type="text/css" media="all" />';
					$html.= apply_filters('wppas_api_head', '');
					$html.= '<style type="text/css">body{ margin:0; padding:0; '.$custom_css.' }</style>';
					
					$html.= '<title>WP PRO ADVERTISING SYSTEM - All In One Ad Manager for Wordpress</title>';
				$html.= '</head>';
				$html.= '<body>';
					
					$html.= do_shortcode('[wpproads id="'.$id.'"]');
					
				$html.= '</body>';
			$html.= '</html>';
			// fix for some themes
			$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/vbc/'.$script.'"></script>';
			
			echo $html;
			
			exit();
		}
	}
	
	
	
	
	/*
	 * Api load adzone
	 *
	 * @access public
	 * @return int
	*/
	public function wp_pro_ad_api_load_adzone( $id = 0, $full_html = 1)
	{
		global $pro_ads_adzones, $pro_ads_main, $pro_ads_codex;
		
		$adzone_id = isset( $_GET['wpproadszoneid'] ) && !empty( $_GET['wpproadszoneid'] ) ? $_GET['wpproadszoneid'] : '';
		$adzone_id = empty($adzone_id) && isset( $_GET['wppaszoneid'] ) && !empty( $_GET['wppaszoneid'] ) ? $_GET['wppaszoneid'] : $adzone_id;
		$adzone_id = $id ? $id : $adzone_id;
		
		if( !empty($adzone_id) )
		{
			if( method_exists( $pro_ads_adzones, 'display_adzone' ) )
			{
				//$adzone_id = $_GET['wppaszoneid'] ? $_GET['wppaszoneid'] : $id;
				$custom_css = get_option('wpproads_custom_css', '');
				$pro_ads_main->daily_updates();
				$ref_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
				
				if( $full_html )
				{
					?>
					<!DOCTYPE>
					<html>
					<head>
					<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
                    <?php
				}
				?>
                <!-- Ads on this site are served by WP PRO Advertising System - All In One Ad Manager <?php echo WP_ADS_VERSION; ?> - wordpress-advertising.com -->
                <script type='text/javascript' src='<?php bloginfo('wpurl'); ?>/wp-admin/load-scripts.php?load=jquery-core'></script>
				  <script type="text/javascript" src="<?php echo WP_ADS_TPL_URL.'/js/jquery.jshowoff.min.js'; ?>"></script>
                <script type="text/javascript" src="<?php echo WP_ADS_TPL_URL.'/js/jquery.bxslider.min.pas.js'; ?>"></script>
                <?php
				wp_enqueue_style( 'wp_pro_add_style' );
				wp_enqueue_script( 'wp_pro_add_js_functions' );
                
				// Buy and sell
				if( $pro_ads_main->buyandsell_is_active() )
				{
					?>
                    <script type="text/javascript" src="<?php echo WP_ADS_BS_TPL_URL.'/js/buyandsell.js'; ?>"></script>
                	<link rel="stylesheet" id="wp_pro_add_style-css" href="<?php echo WP_ADS_BS_TPL_URL; ?>/css/buyandsell.css" type="text/css" media="all">
                    <?php
				}
				?>
				<style type="text/css">
					body { margin:0; padding:0; }
					<?php echo $custom_css; ?>
				</style>
                <?php
				if( $full_html )
				{
					?>
                    <title>WP PRO ADVERTISING SYSTEM - All In One Ad Manager for Wordpress</title>
                    </head>
                    <body>
                    <?php
				}
                    $arr = $pro_ads_adzones->get_adzone_data($adzone_id, array('id' => $adzone_id));
                    
                    if( $pro_ads_codex->wpproads_adzone_is_grid( $adzone_id )  )
                    {
                        echo $pro_ads_adzones->display_adzone_grid( $adzone_id, $arr['atts'] );
                    }
                    else
                    {
                        $adzone = $pro_ads_adzones->display_adzone( $adzone_id, $arr['atts'], $ref_url );
						echo $adzone['html'];
                    }
				if( $full_html )
				{
                    ?>
                    </body>
                    </html>
                	<?php
				}
			}
			else
			{
				_e('WP Pro Ad System Error: function "pro_ad_display_adzone" does not exists.','wpproads');	
			}
			exit();
		}
	}
	
	
	
	
	
	
	
	/*
	 * REST API
	 *
	 * @access public
	 * @return 
	*/
	public function wp_pro_ad_rest_api_load_data()
	{
		if( isset( $_GET['wppasapi'] )) // && !empty( $_GET['wpproadsapi'] ) 
		{
			if( !empty($_SERVER['HTTP_REFERER']))
			{
				$data = RestAPI::processRequest(); 
				
				if( $data->getMethod() == 'get' || $data->getMethod() == 'post' )
				{	
					$status = 200;
					//$data_list = json_encode($data->getRequestVars());
					$data_list = $data->getRequestVars();
					$content_type = 'application/json';
					
					RestAPI::sendResponse($status, $data_list, $content_type);
				}
				else
				{
					RestAPI::sendResponse(404);
				}
			}
			else
			{
				RestAPI::sendResponse(401);
			}
		}
	}
	
	
	
	
	/*
	 * DOWNLOAD BANNER AS IMAGE
	 *
	 * @access public
	 * @return 
	*/
	public function wppas_api_download_banner()
	{
		global $pro_ads_multisite, $wppas_banner_creator;
		
		if( isset( $_GET['wppas_download'] ) && !empty( $_GET['wppas_download']) )
		{
			$html = '';
			$id = $_GET['wppas_download'] ? $_GET['wppas_download'] : 0;
			$custom_css = get_option('wpproads_custom_css', '');
			$wppas_dev_mode = get_option('wppas_dev_mode', 0);
			$script = !$wppas_dev_mode ? 'jquery.wppas.vbc.min.js' : '__dv/jquery.wppas.vbc.js';
			$script_editor = !$wppas_dev_mode ? 'jquery.wppas.vbc.editor.min' : '__dv/jquery.wppas.vbc.editor.js';
			
			$html.= '<!DOCTYPE>';
			$html.= '<html>';
				$html.= '<head>';
					$html.= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
					
					$html.= '<script type="text/javascript" src="'.$pro_ads_multisite->wpproads_get_site_url().'/wp-includes/js/jquery/jquery.js?ver=1.12.4"></script>';
					$html.= '<script type="text/javascript">/* <![CDATA[ */var itm_editor_cont ={"form":""};var predefined = {"buttons":"{}"};var itm_editor_save_confirms ={"array":"[]"}; var ajaxurl = "'.admin_url( 'admin-ajax.php' ).'";/* ]]> */</script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/vbc/postscribe.min.js"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/dom-to-image.js"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/vbc/'.$script.'"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/vbc/'.$script_editor.'"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_URL.'public/assets/js/vbc/jquery-ui-effects.min.js"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_TPL_URL.'/js/ace/ace.js"></script>';
					$html.= '<script type="text/javascript" src="'.WP_ADS_INC_URL . '/chosen/chosen.jquery.min.js"></script>';
					
					
					
					
					$html.= '<link rel="stylesheet" href="'.WP_ADS_URL.'public/assets/css/vbc/wppas_vbc_bnr.css" type="text/css" media="all" />';
					$html.= '<link rel="stylesheet" href="'.WP_ADS_INC_URL.'/font-awesome/css/font-awesome.min.css" type="text/css" media="all" />';
					$html.= apply_filters('wppas_api_head', '');
					$html.= '<style type="text/css">body{margin:0;padding:0;} .banner_cover{cursor:pointer;border:solid 1px;display: inline-block;padding:5px;margin:5px 5px 0 0;} .banner_cover:hover{background-color:#e2e2e2;color:#FFF;border-color:#d0d0d0;} .download_btns_cont{margin: 20px 10px;}</style>'; //'.$custom_css.'
					
					$html.= '<title>WP PRO ADVERTISING SYSTEM - All In One Ad Manager for Wordpress</title>';
				$html.= '</head>';
				$html.= '<body>';
					
					$html.= do_shortcode('[wpproads id="'.$id.'"]');
					
					$html.= '<div id="wppas_banner_html_editor_undefined" style="display:none;"></div>';
					
					$html.= '<div class="download_btns_cont">';
						$html.= '<div style="font-weight: bold;">'.__('Download as:','wpproads').'</div>';
						// Buttons
						$html.= '<div class="banner_cover cover png" data-type="toPng">';
							$html.= __('PNG','wpproads');
						$html.= '</div>';
						$html.= '<div class="banner_cover cover jpg" data-type="toJpeg">';
							$html.= __('JPG','wpproads');
						$html.= '</div>';
						$html.= '<div class="banner_cover cover svg" data-type="toSvg">';
							$html.= __('SVG','wpproads');
						$html.= '</div>';
						
					$html.= '</div>';
					
					$html.= '<div class="vbc_loader_bg" style="position:fixed;top:0;height:100%;width:100%;z-index:1000;background-color:rgba(255, 255, 255, 0.83);display:none;"></div>';
            		$html.= '<div class="vbc_loader_duration" style="position:absolute;z-index:1001;margin:0 45%;top:20%;display:none;">';
						$html.= '<div class="vbc_loader">';
							$html.= $wppas_banner_creator->vbc_loader();
						$html.= '</div>';
					$html.= '</div>';
							
				$html.= '</body>';
			$html.= '</html>';
			
			$html.= '<script>';
				$html.= 'jQuery(document).ready(function($){';
					$html.= '$(".b_container").wppas.editor({ajaxurl: "'.admin_url( 'admin-ajax.php' ).'"});';
				$html.= '});';
			$html.= '</script>';
			
			echo $html;
			
			exit();
		}
	}
	
	
	
}
?>