<?php
/*
 * AJAX REQUEST FUNCTIONS
 *
 * http://codex.wordpress.org/AJAX_in_Plugins
 * For not logged-in users use: add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
*/



/* -------------------------------------------------------------
 * Load campaigns from a specific advertiser - when creating a banner
 * ------------------------------------------------------------- */
add_action('wp_ajax_load_advertiser_campaigns', "load_advertiser_campaigns_callback");
function load_advertiser_campaigns_callback() 
{
	global $pro_ads_campaigns;
	
	$campaigns = $pro_ads_campaigns->get_campaigns( array('meta_key' => '_campaign_advertiser_id', 'meta_value' => $_POST['uid']) );
	
	$html = '';
	$campaign_id = '';
	$html.= '<select name="banner_campaign_id" class="chosen-select select_banner_campaign" required="required">';
    	$html.= '<option value="">'.__('Select a campaign', 'wpproads').'</option>';
		foreach( $campaigns as $campaign )
		{
			$select = $campaign_id == $campaign->ID ? 'selected' : '';
			$html.= '<option value="'.$campaign->ID.'" '.$select.'>'.$campaign->post_title.'</option>';
		}
	$html.= '</select>';
	
	echo $html;
	
	exit;
}
/* -------------------------------------------------------------
 * V4.7.6 < For VBC, Load campaigns from a specific advertiser - when creating a banner
 * ------------------------------------------------------------- */
add_action('wp_ajax_load_advertiser_campaigns_2', "load_advertiser_campaigns_2_callback");
function load_advertiser_campaigns_2_callback() 
{
	global $pro_ads_campaigns;
	
	$campaigns = $pro_ads_campaigns->get_campaigns( array('meta_key' => '_campaign_advertiser_id', 'meta_value' => $_POST['uid']) );
	
	$html = '';
	$campaign_id = '';
	//$html.= '<div class="info">'.__('Campaign:','wpproads').'</div> ';
	$html.= '<select id="wppas_banner_campaign" class="chosen-select chosen-select-banner-campaign select_banner_campaign" required="required">';
		$html.= '<option value="">'.__('Select a campaign', 'wpproads').'</option>';
		
		foreach( $campaigns as $campaign )
		{
			$select = $campaign_id == $campaign->ID ? 'selected' : '';
			$html.= '<option value="'.$campaign->ID.'" '.$select.'>'.$campaign->post_title.'</option>';
		}
		
	$html.= '</select>';
	
	echo $html;
	
	exit;
}
/* -------------------------------------------------------------
 * Load campaigns from a specific advertiser - for filtering
 * ------------------------------------------------------------- */
add_action('wp_ajax_filter_advertiser_campaigns', "filter_advertiser_campaigns_callback");
function filter_advertiser_campaigns_callback() 
{
	global $pro_ads_campaigns;
	
	$campaigns = $pro_ads_campaigns->get_campaigns( array('meta_key' => '_campaign_advertiser_id', 'meta_value' => $_POST['uid']) );
	
	$html = '';
	$html.= '<select name="banner_campaign_id" class="chosen-select filter_banner_campaign">';
    	$html.= '<option value="">'.__('Select a Campaign', 'wpproads').'</option>';
		if( $campaigns )
		{
			foreach( $campaigns as $campaign )
			{
				$select = '';
				$html.= '<option value="'.$campaign->ID.'" '.$select.'>'.$campaign->post_title.'</option>';
			}
		}
	$html.= '</select>';
	
	echo $html;
	
	exit;
}





/* -------------------------------------------------------------
 * Link banner to adzone
 * ------------------------------------------------------------- */
add_action('wp_ajax_link_to_adzone', "link_to_adzone_callback");
function link_to_adzone_callback() 
{
	global $pro_ads_adzones;
	
	// link banner to adzone
	//update_post_meta( $_POST['aid'], 'linked_banners', ''  );
	$linked_banners = get_post_meta( $_POST['aid'], '_linked_banners', true );
	$max_banners    = get_post_meta( $_POST['aid'], '_adzone_max_banners', true );
	$banner_status  = get_post_meta( $_POST['bid'], '_banner_status', true );
	
	if( empty( $linked_banners ))
	{
		if( $pro_ads_adzones->check_if_adzone_is_active( $_POST['aid'] ) && $banner_status == 1)
		{
			$linked_banners = array( $_POST['bid'] );
			update_post_meta( $_POST['aid'], '_linked_banners', array_values(array_filter($linked_banners))  );
			
			// link adzone to banner
			$adzone_ids = explode(',', $_POST['result']);
			update_post_meta( $_POST['bid'], '_linked_adzones', $adzone_ids  );
		}
	}
	else
	{
		if( $_POST['action_type'] == 'remove' )
		{
			if (($key = array_search($_POST['bid'], $linked_banners)) !== false) unset($linked_banners[$key]);
			// link adzone to banner
			$adzone_ids = explode(',', $_POST['result']);
			update_post_meta( $_POST['bid'], '_linked_adzones', $adzone_ids  );
		}
		else
		{
			if( $pro_ads_adzones->check_if_adzone_is_active( $_POST['aid'] ) && $banner_status == 1)
			{
				array_push($linked_banners, $_POST['bid']);
				// link adzone to banner
				$adzone_ids = explode(',', $_POST['result']);
				update_post_meta( $_POST['bid'], '_linked_adzones', $adzone_ids  );
			}
		}
		update_post_meta( $_POST['aid'], '_linked_banners', array_values(array_filter($linked_banners)) );
	}
	
	exit;
}






/* -------------------------------------------------------------
 * Order banners in Adzone
 * ------------------------------------------------------------- */
add_action('wp_ajax_order_banners_in_adzone', "order_banners_in_adzone_callback");
function order_banners_in_adzone_callback() 
{
	//foreach ($_POST['order-item'] as $i => $value) {}
	
	$id_order = explode(',', $_POST['id_order']);
	$linked_banners_order = array();
	
	foreach($id_order as $i => $order) 
	{
		$linked_banners_order[] = $order;
	}
	
	update_post_meta( $_POST['aid'], '_linked_banners', array_values(array_filter($linked_banners_order)) );
	//print_r($linked_banners_order);
	exit;
}







/* -------------------------------------------------------------
 * Load Stats
 * ------------------------------------------------------------- */
add_action('wp_ajax_load_stats', "load_stats_callback");
function load_stats_callback() 
{
	global $pro_ads_statistics, $wppas_stats, $wppas_stats_tpl;
	
	echo $wppas_stats_tpl->stats_tpl(
		array(
			's_type'   => !empty($_POST['s_type']) ? $_POST['s_type'] : 'day', 
			'year'     => !empty($_POST['year']) ? $_POST['year'] : '', 
			'month'    => !empty($_POST['month']) ? $_POST['month'] : '', 
			'day'      => !empty($_POST['day']) ? $_POST['day'] : $wppas_stats->day,
			'unique'   => !empty($_POST['unique']) ? $_POST['unique'] : 0,
			'select'   => !empty($_POST['select']) ? $_POST['select'] : array()
		)
	);
	
	exit;
}

add_action('wp_ajax_load_stats_from_day', "load_stats_from_day_callback");
function load_stats_from_day_callback() 
{
	global $pro_ads_statistics;
	
	echo $pro_ads_statistics->pro_ad_show_statistics(
			array(
				'type'     => array('slug' => $_POST['type'], 'name' => $pro_ads_statistics->stat_types($_POST['type'])), 
				'range'    => 'day', 
				'rid'      => 4,
				'color'    => $_POST['color'],
				'year'     => $_POST['year'], 
				'month'    => $_POST['month'], 
				'day'      => $_POST['day'],
				'group'    => !empty($_POST['group']) ? $_POST['group'] : '',
				'group_id' => !empty($_POST['group_id']) ? $_POST['group_id'] : ''
			)
		);
	
	// stats table
	/*$pro_ads_statistics->get_stats_table( 
		array(
			'type'     => array('slug' => $_POST['type'], 'name' => $pro_ads_statistics->stat_types($_POST['type'])), 
			'range'    => 'day', 
			'rid'      => 4,
			'color'    => $_POST['color'],
			'year'     => $_POST['year'], 
			'month'    => $_POST['month'], 
			'day'      => $_POST['day'],
			'group'    => !empty($_POST['group']) ? $_POST['group'] : '',
			'group_id' => !empty($_POST['group_id']) ? $_POST['group_id'] : ''
		) 
	);*/
	
	exit;
}






/* -------------------------------------------------------------
 * Shotcode Editor
 * ------------------------------------------------------------- */
add_action('wp_ajax_load_wpproads_shortcodes', 'load_wpproads_shortcodes_callback');
function load_wpproads_shortcodes_callback() 
{
	global $pro_ads_templates;
	
	$pro_ads_templates->get_shortcode_editor_form();
	
	exit();
}






/* -------------------------------------------------------------
 * Manual update Campaigns/Banners
 * ------------------------------------------------------------- */
add_action('wp_ajax_manual_update_campaigns_banners', 'manual_update_campaigns_banners_callback');
function manual_update_campaigns_banners_callback() 
{
	global $pro_ads_main;
	
	$pro_ads_main->daily_updates(1, 1);
	
	echo __('Campaign and Banner statuses are updated.','wpproads');
	
	exit();
}







/* -------------------------------------------------------------
 * LOAD RESPONSIVE ADZONES
 * ------------------------------------------------------------- */
add_action('wp_ajax_pas_responsive', 'pas_responsive_callback');
add_action('wp_ajax_nopriv_pas_responsive', 'pas_responsive_callback');
function pas_responsive_callback() 
{	
	$screen = empty($_POST['screen']) || $_POST['screen'] == 'desktop' ? '' : '_'.$_POST['screen'];
	echo do_shortcode('[pro_ad_display_adzone id="'.$_POST['adzone_id'].'" screen="'.$screen.'"]');
	
	exit();
}






/* -------------------------------------------------------------
 * Asynchronous JS Tag - Load Adzones
 * ------------------------------------------------------------- */
add_action('wp_ajax_pas_async_load_adzone', 'pas_async_load_adzone');
add_action('wp_ajax_nopriv_pas_async_load_adzone', 'pas_async_load_adzone');
function pas_async_load_adzone() 
{	
	$screen = empty($_POST['screen']) || $_POST['screen'] == 'desktop' ? '' : '_'.$_POST['screen'];
	$is_popup = !empty($_POST['is_popup']) ? ' popup=1' : '';
	$is_flyin = !empty($_POST['is_flyin']) ? ' flyin=1' : '';
	$is_corner_curl = !empty($_POST['is_corner_curl']) ? ' corner_curl=1' : '';
	
	echo do_shortcode('[pro_ad_display_adzone id="'.$_POST['adzone_id'].'" screen="'.$screen.'"'.$is_popup.$is_flyin.$is_corner_curl.']');
	
	exit();
}





/* -------------------------------------------------------------
 * AD BLOCKER DETECTION
 * ------------------------------------------------------------- */
add_action('wp_ajax_adblocker_detected', 'adblocker_detected_callback');
add_action('wp_ajax_nopriv_adblocker_detected', 'adblocker_detected_callback');
function adblocker_detected_callback()
{
	$adblock_action = array( 
		'alert' => ''
	);
	$adblock_action = apply_filters( 'wp_pro_ads_adblock_detected', $adblock_action );
	echo json_encode( $adblock_action );
	
	exit();
}





/* -------------------------------------------------------------
 * SHORTCODE EDITOR TEMPLATE
 * ------------------------------------------------------------- */
add_action('wp_ajax_load_shortcode_editor', 'load_shortcode_editor_callback');
function load_shortcode_editor_callback()
{
	global $pro_ads_templates;
	
	echo $pro_ads_templates->pro_ad_adzone_popup_screen( $_GET['adzone_id'] );
	
	exit();
}



/* -------------------------------------------------------------
 * AJAX ROTATION LOAD BANNER
 * ------------------------------------------------------------- */
add_action('wp_ajax_rotation_load_banner', 'rotation_load_banner_callback');
add_action('wp_ajax_nopriv_rotation_load_banner', 'rotation_load_banner_callback');
function rotation_load_banner_callback()
{
	global $wppas_stats;
	
	//$pro_ads_statistics->save_impression( $_POST['id'], $_POST['aid'] );
	$wppas_stats->save_stats(array(
		'type'      > 'impressions',
		'banner_id' => $_POST['id'],
		'adzone_id' => $_POST['aid']
	));
	echo do_shortcode('[pro_ad_display_banner id="'.$_POST['id'].'" aid="'.$_POST['aid'].'" container=0]');
	
	exit();
}




/* -------------------------------------------------------------
 * Load Customizable CSS - @since v4.6.20
 * ------------------------------------------------------------- */
add_action('wp_ajax_wppas_php_style', 'wppas_php_style');
add_action('wp_ajax_nopriv_wppas_php_style', 'wppas_php_style');
function wppas_php_style() 
{
	require(WP_ADS_TPL_DIR . '/css/wppas_php.php');
  	exit;
}



/* -------------------------------------------------------------
 * Load Asyncjs - @since v4.6.21
 * Removed @since v5.3.0
 * ------------------------------------------------------------- */
/*add_action('wp_ajax_wppas_asyncjs', 'wppas_asyncjs');
add_action('wp_ajax_nopriv_wppas_asyncjs', 'wppas_asyncjs');
function wppas_asyncjs() 
{
	require(WP_ADS_TPL_DIR . '/js/asyncjs.php');
  	exit;
}
*/



/* -------------------------------------------------------------
 * Save old Stats
 * ------------------------------------------------------------- */
add_action('wp_ajax_wppas_calculate_stats_import', 'wppas_calculate_stats_import');
add_action('wp_ajax_nopriv_wppas_calculate_stats_import', 'wppas_calculate_stats_import');
function wppas_calculate_stats_import() 
{
	global $wpdb;
	
	$bnum = 5;
								
	$sdate = mktime(0,0,0,$_POST['month'], $_POST['sday'], $_POST['year']);
	$edate = mktime(23,59,59,$_POST['month'], $_POST['eday'], $_POST['year']);
	$where = ' WHERE date >= '.$sdate.' AND date <= '.$edate;
	
	$query = $wpdb->get_results('SELECT COUNT(*) as num FROM '.$wpdb->prefix.'wpproads_user_stats'.$where);
	$itemcount = $query[0]->num;
	$batches = $itemcount / $bnum;
	
	echo json_encode( array( 'itemcount' => $itemcount, 'batches' => $batches, 'bnum' => $bnum, 'sdate' => $sdate, 'edate' => $edate) );
	exit;
}



/* -------------------------------------------------------------
 * Save old Stats
 * ------------------------------------------------------------- */
add_action('wp_ajax_wppas_save_old_stats', 'wppas_save_old_stats');
add_action('wp_ajax_nopriv_wppas_save_old_stats', 'wppas_save_old_stats');
function wppas_save_old_stats() 
{
	global $wppas_stats, $pro_ads_multisite, $wpdb;
	
	$where = ' WHERE date >= '.$_POST['sdate'].' AND date <= '.$_POST['edate'];
	$offset = $_POST['num'] * $_POST['bnum'];
	
	$query = $wpdb->get_results('SELECT * FROM '.$wpdb->prefix.'wpproads_user_stats'.$where.' LIMIT '.$_POST['bnum'].' OFFSET '.$offset);
	foreach($query as $old)
	{
		$data = array(
			'banner_id'      => $old->banner_id, 
			'adzone_id'      => $old->adzone_id,
			'advertiser_id'  =>  $old->advertiser_id,
			'campaign_id'    =>  $old->campaign_id,
			'ip_address'     => $old->ip_address,
			'userdata'       => array(
				'city'          => $old->city,
				'country'       => $old->country,
				'country_cd'    => $old->country_cd,
				'browser'       => $old->browser,
				'platform'      => $old->platform,
				'device'        => $old->device
			),
			'type'           => $old->type.'s',
			'year'           => date('Y', $old->time),
			'month'          => date('n', $old->time),
			'day'            => date('j', $old->time),
			'hour'           => date('G', $old->time),
			'time'           => $old->time,
			'hits'           => $old->hits
		);
		
		global $wpdb;
		
		$stime = mktime(0,0,0, $data['month'], $data['day'], $data['year']);
		$wppas_stats->update_stats_db($data, array('type' => $data['type'], 'time' => $stime, 'hits' => $data['hits']));
	}
		
	echo round(($_POST['num'] * 100) / $_POST['batches']);
			
	
	
  	exit;
}








/* -------------------------------------------------------------
 * Builder/Manager - load popup
 * ------------------------------------------------------------- */
add_action('wp_ajax_wppas_load_popup', "wppas_load_popup_callback");
add_action('wp_ajax_nopriv_wppas_load_popup', "wppas_load_popup_callback");
function wppas_load_popup_callback() 
{
	global $pro_ads_templates;
	
	if( $_POST['type'] == 'flyin' )
	{
		$data = array('post_id' => $_POST['post_id']);
		
		echo method_exists($pro_ads_templates, $_POST['content']) ? $pro_ads_templates->{$_POST['content']}($data) : __('Woops, nothings here.','snipr');
	}
	
	exit;
}

/* -------------------------------------------------------------
 * Builder/Manager - load popup
 * ------------------------------------------------------------- */
add_action('wp_ajax_load_kickstart_content', "load_kickstart_content_callback");
add_action('wp_ajax_nopriv_load_kickstart_content', "load_kickstart_content_callback");
function load_kickstart_content_callback() 
{
	global $pro_ads_templates;
	
	if( !empty($_POST['aid']) )
	{
		$aid = $_POST['aid'];
		echo method_exists($pro_ads_templates, $_POST['content']) ? $pro_ads_templates->{$_POST['content']}($aid) : __('Woops, nothings here.','snipr');
	}
	
	exit;
}



/* -------------------------------------------------------------
 * VBC LOAD BANNER EDITOR
 * ------------------------------------------------------------- */
add_action('wp_ajax_vbc_load_banner_editor', 'load_banner_editor_callback');
add_action('wp_ajax_nopriv_vbc_load_banner_editor', 'load_banner_editor_callback');
function load_banner_editor_callback() 
{
	global $wppas_banner_creator;
	
	$option = $_POST['option'];
	
	if( $option == 'startscreen')
	{
		echo $wppas_banner_creator->start_screen_tpl();
	}
	elseif( $option == 'editor')
	{
		$bsize_str = $_POST['bsize'];
		$bsize = explode('x', $bsize_str);
		
		$arr = array(
			'bsize_str' => $bsize_str,
			'bsize' => $bsize
		);
		
		echo $wppas_banner_creator->editor_template($arr);
	}
	
	exit;
}



/* -------------------------------------------------------------
 * VBC SAVE BANNER 
 * ------------------------------------------------------------- */
add_action('wp_ajax_save_vbc_banner', 'save_vbc_banner_callback');
add_action('wp_ajax_nopriv_save_vbc_banner', 'save_vbc_banner_callback');
function save_vbc_banner_callback() 
{
	global $current_user, $wppas_banner_creator;
	
	$banners = json_decode(json_encode(json_decode(stripslashes($_POST['banners']))), true);
	$data = json_decode(json_encode(json_decode(stripslashes($_POST['data']))), true);
	/*echo $_POST['data'];
	echo '--------------';
	echo print_r($data, true);*/
	$bid = $_POST['bid'];
	$return = $_POST['return'];
	
	$barr = array();
	if(!empty($banners) )
	{
		foreach($banners as $banner )
		{
			$barr[$banner['screen_size']] = array(
				'html' => $banner['html']
			);
		}
	}
	
	$b_name = !empty($data['name']) ? $data['name'] : __('Banner created on: '.date('D j F Y, H:s', current_time( 'timestamp' )) );
	
	/*echo 'AJAX::';
	//echo print_r($banners, true);
	echo print_r($data, true);*/
	
	if( !$bid )
	{
		// Insert new banner
		$b_data = array(
			'post_title'       		=> $b_name,
			'post_content'     		=> '',
			'post_category'   		=> array(),
			'post_status'      		=> 'publish',
			'post_type'        		=> 'wppas_banners',
			'post_date'             => date('Y-m-d H:i:s', current_time('timestamp')),
			'post_date_gmt'         => date('Y-m-d H:i:s', current_time('timestamp', 1)),
			'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	
		);
		
		// Filter to do something with the post data
		$b_data = apply_filters( 'wppas_insert_banner_data', $b_data );		
		$bannerID = wp_insert_post( $b_data );
	}
	else
	{
		// Update existing banner
		$bannerID = $bid;
		$b = $wppas_banner_creator->load_banner_data($bannerID);
		// Merge banner data
		$def = $b['banner_data'][0];
		$data = wp_parse_args( $data, $def );
		
		$b_data = array(
			'ID'         => $bannerID,
			'post_title' => !empty($data['name']) ? $data['name'] : $b['banner']->post_title,
		);
		wp_update_post( $b_data );
		
		// Check for Buy Sell order
		WPPAS_BuySell::update_order(array('banner_id' => $bannerID, 'query' => "status = '".$data['status']."'"));
	}
	
	// Set ID again in case it would be different after importing from other sites.
	$data['ID'] = $bannerID;
	
	update_post_meta($bannerID, '_wpproads_banner_data', $data);
	update_post_meta($bannerID, '_wpproads_html_banners', $barr);
	update_post_meta($bannerID, '_wpproads_banner_type', 'vbc');
	
	// Create banner folder
	WPPAS_Core::create_folder(array(
		'folder' => '/wppas/banners/'.$data['alphaID']
	));
	
	//echo $data['name'];
	//echo print_r($banners, true);
	//echo print_r($barr, true);
	if( $return == 'bitm' )
	{
		$banner = get_post($bannerID);
		echo $wppas_banner_creator->all_banners_item($banner);
	}
	else
	{
		echo $bannerID;
	}
	
	exit;
}




/* -------------------------------------------------------------
 * VBC SAVE ADZONE
 * ------------------------------------------------------------- */
add_action('wp_ajax_save_vbc_adzone', 'save_vbc_adzone_callback');
add_action('wp_ajax_nopriv_save_vbc_adzone', 'save_vbc_adzone_callback');
function save_vbc_adzone_callback() 
{
	global $current_user, $wppas_adzone_creator;
	
	$data = json_decode(json_encode(json_decode(stripslashes($_POST['data']))), true);
	//echo print_r($data);
	
	$aid = $_POST['aid'];
	$return = $_POST['return'];
	
	$a_name = !empty($data['name']) ? $data['name'] : __('Adzone created on: '.date('D j F Y, H:s', current_time( 'timestamp' )) );
	
	if( !$aid )
	{
		// Insert new banner
		$a_data = array(
			'post_title'       		=> $a_name,
			'post_content'     		=> '',
			'post_category'   		    => array(),
			'post_status'      		=> 'publish',
			'post_type'        		=> 'wppas_adzones',
			'post_date'             => date('Y-m-d H:i:s', current_time('timestamp')),
			'post_date_gmt'         => date('Y-m-d H:i:s', current_time('timestamp', 1)),
			'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	
		);
		
		// Filter to do something with the post data
		$a_data = apply_filters( 'wppas_insert_banner_data', $a_data );		
		$adzoneID = wp_insert_post( $a_data );
	}
	else
	{
		// Update existing adzone
		$adzoneID = $aid;
		$a = $wppas_adzone_creator->load_adzone_data($adzoneID);
		$a_data = array(
			'ID'         => $adzoneID,
			'post_title' => !empty($data['name']) ? $data['name'] : $a['adzone']->post_title,
		);
		wp_update_post( $a_data );
		
		$data['banners'] = $a['adzone_data'][0]['banners'];
	}
	
	// Set ID again in case it would be different after importing from other sites.
	$data['ID'] = $adzoneID;
	
	update_post_meta($adzoneID, '_wpproads_adzone_data', $data);
	
	echo $adzoneID;
	
	exit;
}


/* -------------------------------------------------------------
 * UPDATE ADZONE BANNERS
 * ------------------------------------------------------------- */
add_action('wp_ajax_update_vbc_adzone_banners', 'update_vbc_adzone_banners_callback');
add_action('wp_ajax_nopriv_update_vbc_adzone_banners', 'update_vbc_adzone_banners_callback');
function update_vbc_adzone_banners_callback() 
{
	global $wppas_adzone_creator;
	
	$adzoneID = $_POST['aid'];
	$banners = json_decode(json_encode(json_decode(stripslashes($_POST['banners']))), true);
	
	$adzone_data = $wppas_adzone_creator->load_adzone_data($adzoneID);
	$adzone_data['adzone_data'][0]['banners'] = $banners;
	
	update_post_meta($adzoneID, '_wpproads_adzone_data', $adzone_data['adzone_data'][0]);
	
	exit;
}



/* -------------------------------------------------------------
 * VBC TRASH BANNER 
 * ------------------------------------------------------------- */
add_action('wp_ajax_trash_vbc_banner', 'trash_vbc_banner_callback');
add_action('wp_ajax_nopriv_trash_vbc_banner', 'trash_vbc_banner_callback');
function trash_vbc_banner_callback() 
{
	global $wppas_banner_creator;
	
	if( !empty($_POST['ID']))
	{
		wp_trash_post( $_POST['ID']  );	
		
		echo $wppas_banner_creator->banner_remove_confirmation($_POST['ID']);
	}
	
	exit;
}

/* -------------------------------------------------------------
 * VBC TRASH ADZONE
 * ------------------------------------------------------------- */
add_action('wp_ajax_trash_vbc_adzone', 'trash_vbc_adzone_callback');
add_action('wp_ajax_nopriv_trash_vbc_adzone', 'trash_vbc_adzone_callback');
function trash_vbc_adzone_callback() 
{
	global $wppas_adzone_creator;
	
	if( !empty($_POST['ID']))
	{
		wp_trash_post( $_POST['ID']  );	
		
		echo $wppas_adzone_creator->adzone_remove_confirmation($_POST['ID']);
	}
	
	exit;
}


/* -------------------------------------------------------------
 * VBC UNDO TRASH BANNER 
 * ------------------------------------------------------------- */
add_action('wp_ajax_undo_trash_vbc_banner', 'undo_trash_vbc_banner_callback');
add_action('wp_ajax_nopriv_undo_trash_vbc_banner', 'undo_trash_vbc_banner_callback');
function undo_trash_vbc_banner_callback() 
{
	if( !empty($_POST['ID']))
	{
		$arr = array( 'ID' => $_POST['ID'], 'post_status' => 'publish');
	  	$postID = wp_update_post( $arr );
		
		echo $postID;
	}
	
	exit;
}


/* -------------------------------------------------------------
 * VBC UNDO TRASH ADZONE
 * ------------------------------------------------------------- */
add_action('wp_ajax_undo_trash_vbc_adzone', 'undo_trash_vbc_adzone_callback');
add_action('wp_ajax_nopriv_undo_trash_vbc_adzone', 'undo_trash_vbc_adzone_callback');
function undo_trash_vbc_adzone_callback() 
{
	if( !empty($_POST['ID']))
	{
		$arr = array( 'ID' => $_POST['ID'], 'post_status' => 'publish');
	  	$postID = wp_update_post( $arr );
		
		echo $postID;
	}
	
	exit;
}



/* -------------------------------------------------------------
 * EXPORT FILES to ZIP (under construction)
 * ------------------------------------------------------------- */
add_action('wp_ajax_export_files', 'export_files_callback');
add_action('wp_ajax_nopriv_export_files', 'export_files_callback');
function export_files_callback() 
{
	global $wppas_banner_creator;
	
	if(!empty($_POST['ID']))
	{
		echo print_r(json_decode(stripslashes($_POST['json'])));
		/*
		$folder = 'wppas/'.$_POST['ID'];
		$upload = wp_upload_dir();
    	$upload_dir = $upload['basedir'];
		$banner_dir = $upload_dir . '/'.$folder;
    	$image_dir = $banner_dir.'/images';
		
		if ( wp_mkdir_p( $image_dir ))
		{
			$banner = $wppas_banner_creator->load_banner_data($_POST['ID']);
			//echo print_r($banner['banner_data'][0]['timeline_arr'],true);
			// Get Images
			if(!empty($banner['banner_data'][0]['timeline_arr']))
			{
				// Create JSON
				$file = fopen($banner_dir.'/banner.json','w+');
				//fwrite($file, stripslashes($_POST['json']));
				fwrite($file, json_encode($banner));
				fclose($file);
				
				// Save images
				foreach( $banner['banner_data'][0]['timeline_arr'] as $screen_size)
				{
					foreach( $screen_size as $item)
					{
						if($item['data']['type'] == 'image')
						{
							$src = $item['data']['src'];
							$imagename = basename($src);
							copy($src, $image_dir.'/'.$imagename);
						}
					}	
				}
			}
			echo 'Folder '.$folder.' successfully created';
		}
		else
		{
			$wp_error = new WP_Error( 'error', __( 'Folder "'.$folder.'" could not be created (wrong permissions). Please create the folder manually under '.$banner_dir.'.', 'wpproads' ) );
			echo $wp_error->get_error_message();
			//Just tell where the user has to make a new folder with the name $folder
   			// or if you're kool, you use _doing_it_wrong(); ... ;-)
		}*/
	}
	else
	{
		$wp_error = new WP_Error( 'error', __( 'Folder could not be created (No banner ID provided).', 'wpproads' ) );
		echo $wp_error->get_error_message();
	}
	
	//echo stripslashes($_POST['json']);
	
	exit();
}




/* -------------------------------------------------------------
 * BUY SELL - LOAD VISUAL BANNER CREATOR AJAX FORM
 * ------------------------------------------------------------- */
add_action('wp_ajax_load_bs_vbc_form', 'load_bs_vbc_form_callback');
add_action('wp_ajax_nopriv_load_bs_vbc_form', 'load_bs_vbc_form_callback');
function load_bs_vbc_form_callback() 
{	
	global $wpdb, $pro_ads_advertisers, $wppas_banner_creator;
	
	$data = json_decode(json_encode(json_decode(stripslashes($_POST['data']))), true);
	
	$array = array(
		'user_data'   => json_decode($data['user_data'],true),
		'adzone_data' => json_decode($data['adzone_data'],true),
		'json'        => urlencode($_POST['data'])
	);
	
	// Check if user is WP user
	$user = get_user_by( 'email', $array['user_data']['email'] );
	$wpuser_id = $user ? $user->ID : 0;
	
	// Check if user already is a advertiser
	$advertiser = $pro_ads_advertisers->get_advertisers( 
		array(
			'meta_key'       => '_proad_advertiser_email',
			'meta_value'     => $array['user_data']['email']
		)
	);
	$advertiser_id = !empty($advertiser) ? $advertiser[0]->ID : 0;
	$username = $user ? $user->user_login : preg_replace('/\s+/', '', strtolower($array['user_data']['name']));
	$ip_adress = $_SERVER['REMOTE_ADDR'];
	
	// Create new timeline arr for this banner.
	$banner_data = $wppas_banner_creator->load_banner_data();
	
	// Add order to database.
	$wpdb->query("INSERT INTO " . $wpdb->prefix . "wppas_buysell 
		SET 
			time = '".current_time('timestamp')."',
			user_id = '".$wpuser_id."',
			email = '".$array['user_data']['email']."',
			ip_address = '".$ip_adress."',
			advertiser_id = '".$advertiser_id."',
			adzone_id = '".$array['adzone_data']['ID']."',
			alphaID = '".$banner_data['banner_data'][0]['timeline_arr']['main']['alphaID']."',
			banner = '".$array['json']."',
			status = 0,
			price = '".$array['adzone_data']['price']."',
			pos = '".$array['adzone_data']['pos']."',
			provider = 'paypal'
	");
	
	$inf = array();
	$inf['order_id'] = $wpdb->insert_id;
	$inf['banner_data'] = $banner_data;
	
	echo WPPAS_BuySell::banner_editor($array, $inf);
		
	exit;
}



/* -------------------------------------------------------------
 * BUY SELL - LOAD PAYPAL AJAX FORM
 * ------------------------------------------------------------- */
add_action('wp_ajax_load_bs_paypal_form', 'load_bs_paypal_form_callback');
add_action('wp_ajax_nopriv_load_bs_paypal_form', 'load_bs_paypal_form_callback');
function load_bs_paypal_form_callback() 
{
	global $wpdb, $pro_ads_advertisers;
	
	$data = json_decode(json_encode(json_decode(stripslashes($_POST['data']))), true);
	
	$array = array(
		'user_data'   => json_decode($data['user_data'],true),
		'adzone_data' => json_decode($data['adzone_data'],true),
		'banner_data' => json_decode($data['banner_data'],true),
		'banner_html' => json_decode($data['banner_html'],true),
		'json'        => urlencode($_POST['data'])
	);
	
	
	$wpdb->query("UPDATE " . $wpdb->prefix . "wppas_buysell 
		SET 
			banner = '".$array['json']."'
		WHERE id = ".$array['banner_data']['order_id']."
	");
	//
	
	
	$array['ipn_data'] = array(
		'order_id' => $array['banner_data']['order_id'],
		'adzone_id' => $array['adzone_data']['ID'],
		'price' => $array['adzone_data']['price'],
		'email' => $array['user_data']['email'],
		'username' => $username
	);
	
	echo WPPAS_BuySell::paypal_form($array);
		
	exit;
}


/* -------------------------------------------------------------
 * BUY SELL - LOAD VBC
 * ------------------------------------------------------------- */
add_action('wp_ajax_load_vbc', 'load_vbc_callback');
add_action('wp_ajax_nopriv_load_vbc', 'load_vbc_callback');
function load_vbc_callback() 
{
	global $wppas_banner_creator;
	
	$banner_id = $_POST['banner_id'];
	
	$bs_data = WPPAS_BuySell::get_buysell_data();
	$alphaID = $wppas_banner_creator->get_alphaID(array('id' => $banner_id));
	//$order = WPPAS_BuySell::load_order(array('query' => "WHERE id = '".$_POST['id']."'"));
	$bsize = WPPAS_TPL::vbc_data(array('id' => $banner_id, 'type' => 'size', 'default'  => '300x250'));
	$bstatus = WPPAS_TPL::vbc_data(array('id' => $banner_id, 'type' => 'status', 'default'  => 'draft'));
									
	// Popup content
	$content = '';
	// Loader
	$content.= '<div class="vbc_loader_bg"></div>';
	$content.= '<div class="vbc_loader_duration" style="display:none;z-index:999999;position:fixed;top:20%;">';
		$content.= $wppas_banner_creator->vbc_loader();
	$content.= '</div>';
	
	
	$content.= '<div class="'.$alphaID.'" style="width:80%; margin:auto;">';
		$content.= '<input type="hidden" id="wppas_banner_size" value="'.$bsize.'" />';
		$content.= '<input type="hidden" id="banner_ID" value="'.$banner_id.'" />';
		$content.= '<input type="hidden" id="wppas_banner_status" value="'.$bstatus.'" />';
		$content.= '<ul class="vbc_menu_toggle" style="margin: 10px 0;">';
			$content.= '<li class="save_banner big left save" data-option="vbc-save"><i class="fa fa-save" style="margin-right: 5px;"></i></li>';
		$content.= '</ul>';
		$content.= $wppas_banner_creator->editor_template(array(
			'bid' => $banner_id,
			'editor_opts' => array(
				'frontend'    => 1,
				'html_editor' => 0,
				'add_images' => $bs_data['vbc_image_uploads'],
				'add_text' => $bs_data['vbc_text'],
				'add_shapes' => $bs_data['vbc_shapes'],
				'add_icons' => $bs_data['vbc_icons'],
				'add_svg' => $bs_data['vbc_svg'],
				'add_button' => $bs_data['vbc_btn'],
				'add_html' => $bs_data['vbc_html'],
				'add_zip' => 0
			),
			'create_folder' => 1
		));
	$content.= '</div>';
	
	echo $content;
	
	exit;
}


/* -------------------------------------------------------------
 * BUY SELL - REMOVE ORDER
 * ------------------------------------------------------------- */
add_action('wp_ajax_bs_remove_order', 'bs_remove_order_callback');
add_action('wp_ajax_nopriv_bs_remove_order', 'bs_remove_order_callback');
function bs_remove_order_callback() 
{
	$order = WPPAS_BuySell::load_order(array('query' => "WHERE id = ".$_POST['id']." LIMIT 1"));
	
	if( !empty($order))
	{
		WPPAS_BuySell::remove_order(array(
			'id' => $_POST['id'],
			'alphaID' => $order[0]->alphaID
		));
	}
	
	exit;
}



/* -------------------------------------------------------------
 * UPLOAD ZIP FILE
 * ------------------------------------------------------------- */
add_action('wp_ajax_upload_zip_files', 'upload_zip_files_callback');
add_action('wp_ajax_nopriv_upload_zip_files', 'upload_zip_files_callback');
function upload_zip_files_callback() 
{
	global $wppas_banner_creator;
	
	/*$fileName = $_FILES['file']['name'];
	$fileSource = $_FILES["file"]["tmp_name"];
	$fileType = $_FILES['file']['type'];
	$fileError = $_FILES['file']['error'];
	$fileContent = file_get_contents($_FILES['file']['tmp_name']);*/
	echo 'oioi';
	//print_r($_FILES);
	/*echo $wppas_banner_creator->upload_and_unzip(array(
		'filename' => $_FILES["file"]["name"],
		'source' => $_FILES["file"]["tmp_name"],
		'type' => $_FILES["file"]["type"]
	));*/
	
	exit();
}


/* -------------------------------------------------------------
 * load_banner_filter_options
 * ------------------------------------------------------------- */
add_action('wp_ajax_load_banner_filter_options', 'load_banner_filter_options_callback');
add_action('wp_ajax_nopriv_load_banner_filter_options', 'load_banner_filter_options_callback');
function load_banner_filter_options_callback() 
{
	global $pro_ads_advertisers;
	
	$filter_by = $_POST['filter_by'];
	$html = '';
	
	if( !empty($filter_by))
	{
		if( $filter_by == 'advertiser')
		{
			$advertisers = $pro_ads_advertisers->get_advertisers();
			
			$options = array();
			$options['empty'] = array('value' => '', 'text' => __('Select', 'wpproads'));
			foreach( $advertisers as $option)
			{
				$title = !empty($option->post_title) ? $option->post_title : $option->ID;
				$options[$option->ID] = array('value' => $option->ID, 'text' => $title);
			}
		}
		
		$html = WPPAS_TPL::select_cont(array(
			'title' => __('Filter option','wpproads'),
			'id' => 'wppas_filter_by_option',
			'value' => '',
			'select_opts' => $options,
			'size' => 'one_forth'
		));
	}
				
	echo $html;
	
	exit();
}

/* -------------------------------------------------------------
 * select_filter_option
 * ------------------------------------------------------------- */
add_action('wp_ajax_select_banner_filter_option', 'select_banner_filter_option_callback');
add_action('wp_ajax_nopriv_select_banner_filter_option', 'select_banner_filter_option_callback');
function select_banner_filter_option_callback() 
{
	$filter = $_POST['filter'];
	$filter_id = $_POST['filter_id'];
	$url = urldecode($_POST['url']);
	
	echo $url.'&filter='.$filter.'&filter_id='.$filter_id;
	
	exit();
}


/* -------------------------------------------------------------
 * Save banner cover
 * ------------------------------------------------------------- */
add_action('wp_ajax_save_banner_cover', 'save_banner_cover_callback');
add_action('wp_ajax_nopriv_save_banner_cover', 'save_banner_cover_callback');
function save_banner_cover_callback() 
{
	if( !empty($_POST['data']))
	{
		$data = $_POST['data'];
		$alphaID = $_POST['alphaID'];
		//$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
		$base64Image = trim($data);
		$base64Image = str_replace('data:image/png;base64,', '', $base64Image);
		$base64Image = str_replace('data:image/jpg;base64,', '', $base64Image);
		$base64Image = str_replace('data:image/jpeg;base64,', '', $base64Image);
		$base64Image = str_replace('data:image/gif;base64,', '', $base64Image);
		$base64Image = str_replace(' ', '+', $base64Image);
	
		$data = base64_decode($base64Image);
		//file_put_contents('/tmp/image.png', $data);
		
		$upload = wp_upload_dir();
		$upload_dir = $upload['basedir'];
		$upload_folder = '/wppas/banners/'.$alphaID;
		$banner_dir = $upload_dir . $upload_folder;
		wp_mkdir_p( $banner_dir );
		
		//if(move_uploaded_file($data, $banner_dir.'/cover.png')) 
		if( file_put_contents($banner_dir.'/cover.png', $data) )
		{
			$response = array(
				'success' => true,
				'html' => '',
				'attach_id' => '',
				'url' => $upload['baseurl'].$upload_folder.'/cover.png',
				'type' => 'image'
			);
			echo json_encode($response);
		}
		else{
			echo json_encode(array('success' => false, 'html' => 'ERROR uploading file.', 'url' => $banner_dir.'/cover.png'));
		}
	}
	
	exit();
}



/* -------------------------------------------------------------
 * SET SCREEN SIZE COOKIE
 * ------------------------------------------------------------- */
/*
add_action('wp_ajax_pas_set_screensize', 'pas_set_screensize_callback');
add_action('wp_ajax_nopriv_pas_set_screensize', 'pas_set_screensize_callback');
function pas_set_screensize_callback() 
{
	global $pro_ads_responsive;
	
	if(isset($_POST['width']))
	{
		$type = $pro_ads_responsive->get_screen_type($_POST['width']);
		$cookie = !empty($type['prefix']) ? $type['prefix'] : 0;
		setcookie("wpproads_screentype", $cookie, 0, COOKIEPATH, COOKIE_DOMAIN);
	}
	
	exit();
}
*/
?>