<?php
class WPPAS_BuySell {	
	
	public function __construct() 
	{
		
	}
	
	
	/** 
	 * BUY SELL MAIN DATA
	 *
	 */
	public static function get_buysell_data()
	{
		$args = get_option( 'wpproads_buysell_settings', array());
		
		$defaults = array(
			'provider' => 'paypal',
			'cur' => 'USD',
			'order_page' => '',
			'paypal_email' => '',
			'paypal_debug' => 0,
			'paypal_sandbox' => 0,
			'vbc_image_uploads' => 1,
			'vbc_text' => 1,
			'vbc_shapes' => 1,
			'vbc_icons' => 1,
			'vbc_svg' => 1,
			'vbc_btn' => 1,
			'vbc_html' => 1,
			'html' => 0
		);
		$args = wp_parse_args( $args, $defaults );
		
		return $args;
	}
	
	
	
	/**
	 * Load Order
	 */
	public static function load_order($args = array())
	{
		global $wpdb;
		
		$defaults = array(
			'query' => ''
		);
		$args = wp_parse_args( $args, $defaults );
		
		$orders = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "wppas_buysell ".$args['query']);	
		
		return $orders;
	}
	
	/**
	 * UPDATE ORDER
	 */
	public static function update_order($args = array())
	{
		global $wpdb;
		
		$defaults = array(
			'id' => 0,
			'banner_id' => 0,
			'query' => ''
		);
		$args = wp_parse_args( $args, $defaults );
		$bs_order = '';
		
		// Check if the order exists.
		if(!empty($args['id']))
		{
			// by order id
			$bs_order = self::load_order(array('query' => "WHERE id = ".$args['id']." LIMIT 1"));
		}
		elseif( !empty($args['banner_id']))
		{
			// by banner id
			$bs_order = self::load_order(array('query' => "WHERE banner_id = ".$args['banner_id']." LIMIT 1"));
		}
		
		
		// If order exists
		if( !empty($bs_order) && !empty($args['query']))
		{
			$wpdb->query("UPDATE ".$wpdb->prefix."wppas_buysell SET ".$args['query']." WHERE id = ".$bs_order[0]->id." ");
		}
	}
	
	
	
	/** 
	 * SETTINGS FORM
	 *
	 */
	public static function settings_form()
	{
		$data = self::get_buysell_data();
		
		$html = '';
		$html.= '<form action="" method="post" enctype="multipart/form-data">
            <div class="tuna_meta metabox-holder">

                <div class="postbox nobg">
                    <div class="inside">
                        <table class="form-table">
                            <tbody>
                                
                                <tr>
                                    <th scope="row">
                                        '.__('Payment Option', 'wpproads').'
                                        <span class="description">'.__('Select which provider you want tp use to receive payments.','wpproads').'</span>
                                    </th>
                                    <td>';
											$html.= WPPAS_TPL::select_cont(array(
												'id' => 'buysell_provider',
												'name' => 'buysell_provider',
												'value' => $data['provider'],
												'select_opts' => array(
													'paypal' => array('text' => __('Paypal','wpproads'))
												)
											));
                                    $html.= '</td>
                                </tr>
									<tr>
                                    <th scope="row">
											'.__('Currency', 'wpproads').'
                                        <span class="description">'.__('Select your prefered currency.','wpproads').'</span>
                                    </th>';
										$html.= '<td>';
											$html.= WPPAS_TPL::select_cont(array(
												'id' => 'buysell_cur',
												'name' => 'buysell_cur',
												'value' => $data['cur'],
												'select_opts' => WPPAS_BuySell::currencies()
											));
										$html.= '</td>';
									$html.= '</tr>
									<tr>
                                    <th scope="row">
                                        '.__('Order Page', 'wpproads').'
                                        <span class="description">'.__('Provide the URL to the order page.','wpproads').'</span>
                                    </th>
                                    <td>';
                                    	$html.= WPPAS_TPL::inpt_cont(array(
												'desc' => __('Create a new page and add the following shortcode to add the order page. <strong>[wpproads_buysell_form]</strong>','wpproads'),
												'id' => 'buysell_order_page', 
												'name' => 'buysell_order_page', 
												'placeholder' => 'http://',
												'value' => $data['order_page'],
												'icon' => 'url'
											));
                                    $html.= '</td>
                                </tr>';
									$html.= '<tr>';
										$html.= '<th scope="row">
                                        '.__('Banner Creator', 'wpproads').'
                                        <span class="description">'.__('Visual Banner creator options.','wpproads').'</span>
                                    </th>';
										$html.= '<td class="wppas">';
											$html.= WPPAS_TPL::checkbox_cont(array(
												'desc' => __('Allow Image Uploads','wpproads'),
												'name' => 'buysell_vbc_image_uploads',
												'value' => $data['vbc_image_uploads'],
												'trigger_switch_button' => 1,
												'size' => 'one_forth'
											));
											$html.= WPPAS_TPL::checkbox_cont(array(
												'desc' => __('Allow Text','wpproads'),
												'name' => 'buysell_vbc_text',
												'value' => $data['vbc_text'],
												'size' => 'one_forth'
											));
											$html.= WPPAS_TPL::checkbox_cont(array(
												'desc' => __('Allow Shapes','wpproads'),
												'name' => 'buysell_vbc_shapes',
												'value' => $data['vbc_shapes'],
												'size' => 'one_forth'
											));
											$html.= WPPAS_TPL::checkbox_cont(array(
												'desc' => __('Allow Icons','wpproads'),
												'name' => 'buysell_vbc_icons',
												'value' => $data['vbc_icons'],
												'size' => 'one_forth'
											));
											$html.= WPPAS_TPL::checkbox_cont(array(
												'desc' => __('Allow SVG','wpproads'),
												'name' => 'buysell_vbc_svg',
												'value' => $data['vbc_svg'],
												'size' => 'one_forth'
											));
											$html.= WPPAS_TPL::checkbox_cont(array(
												'desc' => __('Allow Buttons','wpproads'),
												'name' => 'buysell_vbc_btn',
												'value' => $data['vbc_btn'],
												'size' => 'one_forth'
											));
											$html.= WPPAS_TPL::checkbox_cont(array(
												'desc' => __('Allow HTML','wpproads'),
												'name' => 'buysell_vbc_html',
												'value' => $data['vbc_html'],
												'size' => 'one_forth'
											));
										$html.= '</td>';
									$html.= '</tr>';
									
								$html.= '</tbody>
							</table>
						</div>
					</div>';
					// end postbox
					
					
					$html.= '<h3>'.__('Paypal Settings','wpproads').'</h3>';
					$html.= '<div class="postbox nobg">';
						$html.= '<div class="inside">';
							$html.= '<table class="form-table">';
								$html.= '<tbody>';
									$html.= '<tr>';
										$html.= '<th scope="row">';
											$html.= __('Paypal Email', 'wpproads');
											$html.= '<span class="description">'.__('Add your Paypal email to receive payments.','wpproads').'</span>';
										$html.= '</th>';
										$html.= '<td>';
											$html.= WPPAS_TPL::inpt_cont(array(
												'id' => 'buysell_paypal_email', 
												'name' => 'buysell_paypal_email', 
												'placeholder' => __('Email', 'wpproads'),
												'value' => $data['paypal_email'],
												'icon' => ''
											));
										$html.= '</td>';
									$html.= '</tr>';
									$html.= '<tr>';
										$html.= '<th scope="row">';
											$html.= __('Paypal Debug', 'wpproads');
											$html.= '<span class="description">'.__('Add errors to the log file.','wpproads').'</span>';
										$html.= '</th>';
										$html.= '<td>';
											$html.= WPPAS_TPL::select_cont(array(
												'desc' => __('NOTE: if turned on make sure the log.txt file located in the plugin folder is writable.','wpproads'),
												'id' => 'buysell_paypal_debug',
												'name' => 'buysell_paypal_debug',
												'value' => $data['paypal_debug'],
												'select_opts' => array(
													0 => array('text' => __('No','wpproads')),
													1 => array('text' => __('Yes','wpproads'))
												)
											));
										$html.= '</td>';
									$html.= '</tr>';
									$html.= '<tr>';
										$html.= '<th scope="row">';
											$html.= __('Paypal Sandbox', 'wpproads');
											$html.= '<span class="description">'.__('Use paypal sandbox for testing.','wpproads').'</span>';
										$html.= '</th>';
										$html.= '<td>';
											$html.= WPPAS_TPL::select_cont(array(
												'id' => 'buysell_paypal_sandbox',
												'name' => 'buysell_paypal_sandbox',
												'value' => $data['paypal_sandbox'],
												'select_opts' => array(
													0 => array('text' => __('No','wpproads')),
													1 => array('text' => __('Yes','wpproads'))
												)
											));
										$html.= '</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div>';
					// end .postbox
					
					
				$html.= '</div>';
				// end tuna-meta
				
				$html.= '<div class="btn_container_with_menu" style="margin-top:40px;">';
              		$html.= '<input type="submit" value="'.__('Save General Settings', 'wpproads').'" class="main_button button-secondary green" name="buysell_settings" />';
            	$html.= '</div>';
				
			$html.= '</form>';
		
		return $html;
	}
	
	
	
	
	/**
	 * PAYPAL ACCEPTED CURRENCIES
	 * https://developer.paypal.com/docs/classic/api/currency_codes/#paypal
	 */
	public static function currencies()
	{
		$cur = array(
			'EUR' => array('value' => 'EUR', 'text' => 'Euro - EUR'),
			'USD' => array('value' => 'USD', 'text' => 'United States Dollars - USD'),
			'GBP' => array('value' => 'GBP', 'text' => 'United Kingdom Pounds - GBP'),
			'CAD' => array('value' => 'CAD', 'text' => 'Canada Dollars - CAD'),
			'AUD' => array('value' => 'AUD', 'text' => 'Australia Dollars - AUD'),
			'NZD' => array('value' => 'NZD', 'text' => 'New Zealand Dollars - NZD'),
			'JPY' => array('value' => 'JPY', 'text' => 'Japan Yen - JPY'),
			'INR' => array('value' => 'INR', 'text' => 'India Rupees - INR'),
			'CHF' => array('value' => 'CHF', 'text' => 'Switzerland Francs - CHF'),
			'ZAR' => array('value' => 'ZAR', 'text' => 'South Africa Rand - ZAR'),
			'DKK' => array('value' => 'DKK', 'text' => 'Denmark Kroner - DKK'),
			'CZK' => array('value' => 'CZK', 'text' => 'Czech Republic Koruny - CZK'),
			'HKD' => array('value' => 'HKD', 'text' => 'Hong Kong Dollars - HKD'),
			'HUF' => array('value' => 'HUF', 'text' => 'Hungary Forint - HUF'),
			'ILS' => array('value' => 'ILS', 'text' => 'Israel New Shekels - ILS'),
			'MXN' => array('value' => 'MXN', 'text' => 'Mexico Pesos - MXN'),
			'NOK' => array('value' => 'NOK', 'text' => 'Norway Kroner - NOK'),
			'PLN' => array('value' => 'PLN', 'text' => 'Poland Zlotych - PLN'),
			'SEK' => array('value' => 'SEK', 'text' => 'Swedish Krona - SEK'),
			'SGD' => array('value' => 'SGD', 'text' => 'Singapore Dollars - SGD'),
			'BRL' => array('value' => 'BRL', 'text' => 'Brazilian Real - BRL'),
			'PHP' => array('value' => 'PHP', 'text' => 'Philippine Peso - PHP'),
			'TWD' => array('value' => 'TWD', 'text' => 'Taiwan New Dollar - TWD'),
			'THB' => array('value' => 'THB', 'text' => 'Thai Baht - THB')
		);
		
		return $cur;
	}
	
	
	
	
	/**
	 * RECEIVE PAYMENT - PAYPAL
	 *
	 * @args: $paypal_data (array), $provider (string)
	 * @access public
	 * @return array
	 */
	public static function receive_payment( $paypal_data, $provider = 'paypal' )
	{
		global $wpdb, $wppas_paypal_ipn, $pro_ads_advertisers, $wppas_adzone_creator;
		
		$wppas_paypal_ipn->log_add('received : ' . print_r($paypal_data, true));
		
		if( !empty($paypal_data))
		{
			$data = json_decode(json_encode(json_decode(stripslashes(urldecode($paypal_data['custom'])))), true);
			
			$order_id = $data['order_id'];
			$adzone_id = $data['adzone_id'];
			$price = $data['price'];
			$email = $data['email'];
			$username = $data['username'];
			
			// Fully paid
			if( $paypal_data['payment_amount'] >= $price )
			{
				$adzone_data = $wppas_adzone_creator->load_adzone_data($adzone_id);
				$order = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "wppas_buysell WHERE id = ".$order_id." LIMIT 1");
				
				$user = get_user_by( 'email', $email );
				$wpuser_id = $user ? $user->ID : 0;
				
				// Banner Data
				$banner = $order[0]->banner;
				$b_data = json_decode(json_encode(json_decode(stripslashes(urldecode($banner)))), true);
				$banner_data = array(
					'user_data'   => json_decode($b_data['user_data'],true),
					'adzone_data' => json_decode($b_data['adzone_data'],true),
					'banner_data' => json_decode($b_data['banner_data'],true),
					'banner_html' => json_decode($b_data['banner_html'],true)
				);
				
				// Check if there is already an advertiser for this user
				$advertiser = $pro_ads_advertisers->get_advertisers( 
					array(
						'meta_key'       => '_proad_advertiser_email',
						'meta_value'     => $email
					)
				);
				if( !empty($advertiser) )
				{ 
					$advertiser_id = $advertiser[0]->ID;
				}
				else
				{
					$advertiser_id = wp_insert_post( array('post_status' => 'publish', 'post_type' => 'advertisers', 'post_title' => $banner_data['user_data']['name'], ) );
					update_post_meta( $advertiser_id, '_proad_advertiser_email', $email );
	  				update_post_meta( $advertiser_id, '_proad_advertiser_wpuser', $wpuser_id );
				}
				$banner_data['banner_data']['advertiser'] = $advertiser_id;
				
				$b_name = !empty($banner_data['banner_data']['name']) ? $banner_data['banner_data']['name'] : __('Banner created on: '.date('D j F Y, H:s', current_time( 'timestamp' )) );
				
				// Banner Status
				$bs_approve = $adzone_data['adzone_data'][0]['bs_approve'];
				$order_status = $bs_approve ? 'draft' : 'active';
				// If banner needs to be approved set status to draft.
				$banner_data['banner_data']['status'] = $order_status;
				
				// Create Banner
				$defaults = array(
					'post_status'           => 'publish', 
					'post_type'             => 'wppas_banners',
					'post_author'           => $wpuser_id,
					'post_title'            => $b_name,
					'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))
				);
				$banner_id = wp_insert_post( $defaults );
				
				// CREATE  BANNER
				$barr = array();
				if(!empty($banner_data['banner_html']) )
				{
					foreach($banner_data['banner_html'] as $banner )
					{
						$barr[$banner['screen_size']] = array(
							'html' => $banner['html']
						);
					}
				}
				
				update_post_meta($banner_id, '_wpproads_banner_data', $banner_data['banner_data']);
				update_post_meta($banner_id, '_wpproads_html_banners', $barr);
				update_post_meta($banner_id, '_wpproads_banner_type', 'vbc');
				
				// Link to adzone
				$linked_banners = WPPAS_TPL::vbc_data(array('id' => $adzone_id, 'type' => 'banners', 'default' => array()));
				array_push($linked_banners, $banner_id);
				$linked_banners = $wppas_adzone_creator->order_linked_banners(array('linked_banners' => $linked_banners));
				$adzone_data['adzone_data'][0]['banners'] = $linked_banners;
				update_post_meta($adzone_id, '_wpproads_adzone_data', $adzone_data['adzone_data'][0]);
				
				// Update order
				$wpdb->query("UPDATE " . $wpdb->prefix . "wppas_buysell 
					SET 
						advertiser_id = ".$advertiser_id.",
						banner_id = ".$banner_id.",
						status = '".$order_status."',
						transaction = '".$paypal_data['txn_id']."',
						trans_date = '".current_time('timestamp')."',
						am_paid = '".$paypal_data['payment_amount']."'
					WHERE id = '".$order_id."' 
				");	
			}
		}
	}
	
	
	
	/**
	 * RECEIVE PAYMENT RENEWAL - PAYPAL
	 *
	 * @args: $data (array), $provider (string)
	 * @access public
	 * @return array
	 */
	public static function receive_payment_renewal($pp_data, $provider = 'paypal')
	{
		global $wpdb, $wppas_paypal_ipn, $wppas_adzone_creator, $wppas_banner_creator;
		
		$wppas_paypal_ipn->log_add('received : ' . print_r($pp_data, true));
		
		if( !empty($pp_data))
		{
			$data = json_decode(json_encode(json_decode(stripslashes(urldecode($pp_data['custom'])))), true);
			$order_id = $data['order_id'];
			
			// Fully paid
			if( $pp_data['payment_amount'] >= $price )
			{
				$order = self::load_order(array('query' => 'WHERE id = '.$order_id.' LIMIT 1'));
				self::update_order(array('id' => $order_id, 'query' => 'status = "renewed"'));
				$adzone_data = $wppas_adzone_creator->load_adzone_data($order[0]->adzone_id);
				
				// Add new order to database.
				$wpdb->query("INSERT INTO " . $wpdb->prefix . "wppas_buysell 
					SET 
						time = '".current_time('timestamp')."',
						user_id = '".$order[0]->user_id."',
						email = '".$order[0]->email."',
						ip_address = '".$ip_adress."',
						advertiser_id = '".$order[0]->advertiser_id."',
						adzone_id = '".$order[0]->adzone_id."',
						banner_id = '".$order[0]->banner_id."',
						alphaID = '".$order[0]->alphaID."',
						banner = '".$order[0]->banner."',
						status = 'active',
						price = '".$order[0]->price."',
						transaction = '".$pp_data['txn_id']."',
						trans_date = '".current_time('timestamp')."',
						am_paid = '".$pp_data['payment_amount']."'
						provider = 'paypal'
				");
				
				$wppas_banner_creator->reset_banner_stats(array('ID' => $order[0]->banner_id, 'date' => 1));
				
				// Link to adzone
				$linked_banners = WPPAS_TPL::vbc_data(array('id' => $order[0]->adzone_id, 'type' => 'banners', 'default' => array()));
				if( !in_array($order[0]->banner_id, $linked_banners))
				{
					array_push($linked_banners, $order[0]->banner_id);
					$adzone_data['adzone_data'][0]['banners'] = $linked_banners;
					update_post_meta($order[0]->adzone_id, '_wpproads_adzone_data', $adzone_data['adzone_data'][0]);
				}
			}
		}
	}
	
	
	
	
	/**
	 * BUY SELL - Banner placeholder (link to order form)
	 *
	 */
	public static function show_bs_banner($args = array())
	{
		$defaults = array(
			'aid'           => 0,
			'rotation_time' => 5000,
			'slide_num'     => 0
		);
		
		$args = wp_parse_args( $args, $defaults );
		$slide_num = $args['slide_num'] > 0 ? $args['slide_num']+1 : $args['slide_num'];
		$html = '';
		
		$buyandsell = WPPAS_TPL::vbc_data(array(
			'id' => $args['aid'], 
			'type' => 'buyandsell', 
			'default' => 0, 
			'request' => 'adzone'
		));
		if( $buyandsell )
		{
			$bs_banner_id = WPPAS_TPL::vbc_data(array(
				'id' => $args['aid'], 'type' => 'bs_banner_id', 'default' => '', 'request' => 'adzone'
			));	
			$html.= '<div class="slide_'.$slide_num.' wpslide" idle="'.$args['rotation_time'].'" style="width:inherit; height:inherit;">';
				$html.= do_shortcode('[wpproads_banner id="'.$bs_banner_id.'" adzone='.$args['aid'].' buysell=1]');
			$html.= '</div>';
		}
		
		return $html;
	}
	
	
	
	/**
	 * BUY SELL - LOAD TOP POSITION BANNERS
	 * return: array()
	 */
	public static function top_position_banners($args = array())
	{
		global $wpdb;
		
		$defaults = array(
			'adzone_id'      => 0,
			'linked_banners' => array()
		);
		$args = wp_parse_args( $args, $defaults );
		$positions = array();
		
		if(empty($args['linked_banners']))
		{
			$adzone_info = self::adzone_info($args['adzone_id']);
			$linked_banners = $adzone_info['linked_banners'];
		}
		else
		{
			$linked_banners = $args['linked_banners'];
		}
		
		
		if(!empty($linked_banners))
		{
			foreach($linked_banners as $banner)
			{
				$order = self::load_order(array('query' => "WHERE banner_id = ".$banner." ORDER BY id DESC LIMIT 1"));
				if(!empty($order) && !empty($order[0]->pos))
				{
					array_push($positions, array('id' => $banner, 'pos' => $order[0]->pos));
				}
				else
				{
					array_push($positions, array('id' => $banner, 'pos' => 0));	
				}
			}
		}
		
		usort($positions, array('WPPAS_BuySell', 'pos_sort'));
		
		return $positions;
	}
	
	/** 
	 * Sort function
	 */
	private static function pos_sort($a, $b)
	{
		return $a['pos'] < $b['pos'];
	}
	
	
	
	/**
	 * BUY SELL - ORDER FORM
	 *
	 */
	public static function order_form($args = array())
	{
		global $wppas_banner_creator, $wppas_adzone_creator;
		
		wp_enqueue_script('wp-color-picker-alpha');
		
		$adzone_id = isset($_GET['adzone']) ? $_GET['adzone'] : 0;
		$html = '';
		$html.= '<div class="wppas">';
		
		if( $adzone_id )
		{
			$data = self::get_buysell_data();
			$adzone_data = $wppas_adzone_creator->load_adzone_data($adzone_id);
			$adzone_info = self::adzone_info($adzone_id);
			
			// Order Header
			$html.= '<div class="bs_order_header">';
				// adzone title
				$html.= '<h1 class="title">'.sprintf(__('Advertise in the %s adzone %s','wpproads'), '<strong>'.$adzone_info['name'].'</strong>', $adzone_info['rotation_icon']).'</h1>';
				
				// adzone rotation info
				$html.= $adzone_info['rotation'] ? '<div style="font-size:12px;color: #c3c3c3;"><strong>'.__('Rotation','wpproads').'</strong> - '.$adzone_info['rotate_info'].'</div>' : '';
				// adzone size info
				$html.= '<div style="font-size:12px;color: #c3c3c3;"><strong>'.__('Size','wpproads').'</strong> - '.$adzone_info['size'].'</div>';
				
				if( $adzone_info['spots'] <= 0 )
				{
					// soldout
					$html.= '<div class="status soldout" style="text-transform:uppercase;margin:20px 0;">'.__('Currently sold out','wpproads').'</div>';
				}
				else
				{
					// available
					$html.= '<div class="status available" style="text-transform:uppercase;margin:20px 0;">'.sprintf(__('%s Spots Available','wpproads'), $adzone_info['spots_available']).'</div>';
				}
			$html.= '</div>';
			// end .bs_order_header
			
			// Banner preview popup.
			$html.= '<div class="vbc_loader_bg"></div>';
			$html.= WPPAS_TPL::full_page_modal(array(
			 	'id' => 'vbc_preview_container'
			 ));
			/*$html.= '<div class="vbc_preview_container">';
				$html.= '<div class="preview_cont"></div>';
			$html.= '</div>';*/
			// Loader
			$html.= '<div class="wppas_bs_loading_vbc" style="display:none;z-index:999999;position:fixed;top:20%;left:40%;">';
				$html.= $wppas_banner_creator->vbc_loader();
			$html.= '</div>';
			
			// Order form
			$html.= '<div id="wppas_visual_bc_container" class="bs_order_form">';
				
				if( $adzone_info['spots'] > 0 )
				{
					$html.= '<input type="hidden" id="wppas_banner_size" value="'.$adzone_info['size'].'" />';
					$html.= '<input type="hidden" id="wppas_adzone_id" value="'.$adzone_id.'" />';
					$html.= '<input type="hidden" id="wppas_bs_price" value="'.$adzone_info['price'].'" />';
					$html.= '<input type="hidden" id="wppas_bs_pos" value="0" />';
					$html.= '<input type="hidden" id="wppas_bs_contract" value="'.$adzone_info['contract'].'" />';
					$html.= '<input type="hidden" id="wppas_bs_duration" value="'.$adzone_info['duration'].'" />';
				
					// 1. USER INFO
					$html.= '<div class="bs_userinfo">';
						
						// Check if user is loggedin
						$email = '';
						$name = '';
						if( is_user_logged_in() )
						{
							$user = wp_get_current_user();
							$email = $user->user_email; 
							$name = !empty($user->user_firstname) && !empty($user->user_lastname) ? $user->user_firstname.' '.$user->user_lastname : '';
						}
						
						$html.= '<h2>'.__('1. Your Details','wpproads').'</h2>';
						// Personal details
						$html.= WPPAS_TPL::inpt_cont(array(
							'title' => __('Full Name','wpproads'),
							'desc' => __('Provide your full name to create your advertiser account on our website.','wpproads'),
							'id' => 'bs_name', 
							'name' => 'bs_name', 
							'placeholder' => __('John Doe','wpproads'),
							'value' => $name,
							'size' => 'one_second'
						));
						$html.= WPPAS_TPL::inpt_cont(array(
							'title' => __('Email Address','wpproads'),
							'desc' => __('Provide a valid email address to activate your account and receive status updates about your banners.','wpproads'),
							'id' => 'bs_email', 
							'name' => 'bs_email', 
							'placeholder' => __('email','wpproads'),
							'value' => $email,
							'size' => 'one_second'
						));
					$html.= '</div>';
					
					
					// 2. CONFIRMATION
					$html.= '<div class="bs_confirmation">';
						$html.= '<h2 style="margin:30px 0 0;">'.__('Confirmation','wpproads').'</h2>';
						$html.= '<p>'.sprintf(__('Add Banner to %s adzone <small>(ID: %s)</small>','wpproads'), '<strong>'.$adzone_info['name'].'</strong>', $adzone_id).'</p>';
						$html.= '<ul>';
							$html.= '<li>'.__('Price:','wpproads').' <strong><span id="bs_conf_price">'.$adzone_info['price'].'</span> '.$data['cur'].'</strong></li>';
							$html.= '<li>'.__('Contract:','wpproads').' <strong>'.self::contract_line(array('contract' => $adzone_info['contract'], 'duration' => $adzone_info['duration'])).'</strong></li>';
							// Positions
							if( $adzone_info['bidding'] )
							{
								$up_bid = $adzone_info['pos_bid'];
								$banners_pos = self::top_position_banners(array('adzone_id' => $adzone_id));
								$your_pos = ($adzone_info['linked_banners_num']+1);
								$html.= '<li>';
									$html.= __('Position:','wpproads').' <strong>#<span id="bs_conf_pos">'.$your_pos.'</span></strong>';
									$html.= $your_pos > 1 ? '<span class="improve_note open_pos_modal">'.sprintf(__('Get <strong>#1</strong> position for only %s extra!','wpproads'), ($banners_pos[0]['pos']+$up_bid).' '.$data['cur']).'</span>' : '';
									
									$html.= WPPAS_TPL::full_page_modal(array(
										'id' => 'improve_pos_modal',
										'content' => self::banner_pos_tpl(array('adzone_id' => $adzone_id)),
										'script' => '$(".open_pos_modal").on("click", function(){ $("#improve_pos_modal").show();$("html").css({"overflow":"hidden"});$("body").css({"overflow":"hidden"});});'
									));
								$html.= '</li>';
							}
							
						$html.= '</ul>';
						$html.= '<div class="bs_confirmation_notice" style="margin-top: 20px;"></div>';
						$html.= '<a id="bs_confirm_user_details" class="button-secondary green">'.__('Confirm & proceed to Banner Creator','wpproads').'</a>';
					$html.= '</div>';
				}
				
			$html.= '</div>';
			// end #wppas_visual_bc_container
			
			// 3. Banner Editor - Content gets added by Javascript - jquery.wppas.buyandsell.js
			// 4. PAYMENT - Content gets added by Javascript - jquery.wppas.buyandsell.js
			$html.= '<div class="bs_payment_container wppas">';
				
				$html.= '<div class="bs_payment"></div>';
				
			$html.= '</div>';
			// end .bs_payment_container
			
			// FOOTER FAQ  INFO
			$html.= '<div style="margin:50px 0 0 0; border-top: solid 1px #EFEFEF;">';
				$html.= self::faq_info_footer();
			$html.= '</div>';
			
			// More available adzones
			$html.= '<div style="margin:50px 0 0 0;">';
				$html.= self::all_available_adzones(array('title' => __('More Advertising Options','wpproads'), 'exclude' => array($adzone_id)));
			$html.= '</div>';
			
			
			
			// JS
			$sizes = $wppas_banner_creator->screen_sizes(); 
			$screen_sizes = json_encode($sizes);
			$html.= '<script type="text/javascript">';
				$html.= 'var _VBC = jQuery("#wppas_visual_bc_container");';
				$html.= 'var screen_sizes = '.$screen_sizes.';';
				
				$html.= 'jQuery(document).ready(function($){';
					$html.= '_VBC.wppas.buysell({screen_sizes: screen_sizes});';
				$html.= '});';
			$html.= '</script>';
		}
		else
		{
			//$html.= __('Sorry, the adzone you are looking for cannot be found.','wpproads');	
			$html.= self::all_available_adzones();
			$html.= self::faq_info_footer();
		}
		
		$html.= '</div>';
		// end .wppas
		
		return $html;
	}
	
	
	/**
	 * FOOTER FAQ INFO
	 */
	public static function faq_info_footer()
	{
		$html = '';
		$html.= '<div class="bs_fq_inf rotation one_third">';
			$html.= '<span class="title">'.__('Ad will rotate with other ads','wpproads').'</span>';
			$html.= '<span class="desc">'.__('When you see this icon, it means your ad will rotate with other ads in the adzone.','wpproads').'</span>';
		$html.= '</div>';
		
		$html.= '<div class="bs_fq_inf adblockers one_third">';
			$html.= '<span class="title">'.__('What about ad blockers?','wpproads').'</span>';
			$html.= '<span class="desc">'.__('No worries! We have them under control, If however your ad would be detected by an adblocker impressions will not be counted.','wpproads').'</span>';
		$html.= '</div>';	
		
		return $html;
	}
	
	
	
	
	/**
	 * BANNER POSITION INFO template
	 */
	public static function banner_pos_tpl($args = array())
	{
		$defaults = array(
			'adzone_id'     => 0
		);
		$args = wp_parse_args( $args, $defaults );
		$bs_data = self::get_buysell_data();
		$adzone_info = self::adzone_info($args['adzone_id']);
		$banners_pos = self::top_position_banners(array('adzone_id' => $args['adzone_id']));
		$rotation_time = ($adzone_info['rotation_time']/1000);
		$html = '';
		
		$html.= '<div style="width:60%; margin:auto;">';
		
			$html.= '<h2 class="improve_pos_title">'.sprintf(__('Improve your position in %s adzone','wpproads'), '<strong>'.$adzone_info['name'].'</strong>').'</h2>';
			$html.= sprintf(__('The %s adzone rotates banners every %s seconds.','wpproads'), $adzone_info['name'], $rotation_time);
			$html.= sprintf(__('<strong>Your current possition in rotation will be #%s</strong>. However you do have the option to improve your position and potentially get more views and click trues for your website/link. Every advertiser has the option to drop a higher bid and improve the position for his ad in the adzone.','wpproads'), ($adzone_info['linked_banners_num']+1));
			
			// Top banners for this adzone
			$html.= '<h3 style="margin-top:40px;">'.__('Your Options','wpproads').'</h3>';
			$html.= '<ul class="pos_offers">';
			if(!empty($banners_pos))
			{
				foreach($banners_pos as $i => $banner)
				{
					$class = $i == 0 ? ' gold' : '';
					$class = $i == 1 ? ' silver' : $class;
					$class = $i == 2 ? ' bronze' : $class;
					$html.= '<li class="offer"><a class="get_pos_offer" data-pos="'.($i+1).'" data-pos-price="'.($banner['pos']+$adzone_info['pos_bid']).'"><span class="pos_offer'.$class.'">'.sprintf(__('Get #%s Position','wpproads'),($i+1)).'</span> '.($banner['pos']+$adzone_info['pos_bid']).' '.$bs_data['cur'].'</a></li>';
				}
			}
			$html.= '</ul>';
			
		$html.= '</div>';
		
		$html.= '<script type="text/javascript">';
			$html.= 'jQuery(document).ready(function($){';
				$html.= '$(".get_pos_offer").on("click", function(){';
					$html.= 'var pos_price = $(this).data("pos-price"),';
					$html.= 'pos = $(this).data("pos"),';
					$html.= 'price = $("#wppas_bs_price").val(),';
					$html.= 'new_price = Number(price)+Number(pos_price);';
					
					$html.= '$("#wppas_bs_pos").val(pos_price);';
					$html.= '$("#wppas_bs_price").val(new_price);';
					$html.= '$("#bs_conf_price").html(new_price);';
					$html.= '$("#bs_conf_pos").html(pos);';
					
					$html.= '$("#improve_pos_modal").hide();$("html").css({"overflow":"auto"});$("body").css({"overflow":"auto"});';
				$html.= '});';
			$html.= '});';
		$html.= '</script>';
		
		return $html;
	}
	
	
	
	
	/**
	 * Returns a readable contract line with type + duration
	 *
	 */
	public static function contract($args = array())
	{
		if($args['contract'] == 'ppv')
		{
			$contract = array(
				'multi'  => __('Views'),
				'single' => __('View'),
			);
		}
		else if($args['contract'] == 'ppd')
		{
			$contract = array(
				'multi'  => __('Days'),
				'single' => __('Day'),
			);
		}
		else
		{
			$contract = array(
				'multi'  => __('Clicks'),
				'single' => __('Click'),
			);
		}
		
		return $contract;
	}
	
	
	
	/**
	 * Returns a readable contract line with type + duration
	 *
	 */
	public static function contract_line($args = array())
	{
		$html = '';
		$contract = self::contract(array('contract' => $args['contract']));
		
		if($args['duration'] > 1)
		{
			$html.= $args['duration'].' '.$contract['multi'];
		}	
		else
		{
			$html.= $args['duration'].' '.$contract['single'];
		}
		
		return $html;
	}
	
	
	
	
	/**
	 * Banner Editor
	 */
	public static function banner_editor($args = array(), $inf = array())
	{
		global $wppas_banner_creator;
		
		$data = self::get_buysell_data();
		
		$html = '';
		// Banner Editor
		$html.= '<div class="bs_banner_creator '.$inf['banner_data']['banner_data'][0]['timeline_arr']['main']['alphaID'].'">';
			// Banner size - based on adzone
			$html.= '<input type="hidden" id="wppas_data" value="'.urlencode(json_encode($args)).'" />';
			$html.= '<input type="hidden" id="wppas_inf" value="'.urlencode(json_encode($inf)).'" />';
			
			$html.= '<h2>'.__('2. Design Banner','wpproads').'</h2>';
			
			// Banner details
			$html.= '<div class="bs_userinfo">';
				$html.= WPPAS_TPL::inpt_cont(array(
					'title' => __('Banner Name','wpproads'),
					'desc' => __('Provide an appropriate name for your banner.','wpproads'),
					'id' => 'bs_banner_title', 
					'name' => 'bs_banner_title', 
					'placeholder' => __('Banner Title','wpproads')
				));
				$html.= WPPAS_TPL::inpt_cont(array(
					'title' => __('Banner Link (URL)','wpproads'),
					'desc' => __('The URL your banner should link to.','wpproads'),
					'id' => 'bs_link', 
					'name' => 'bs_link', 
					'placeholder' => __('http://your-link.com','wpproads')
				));
			$html.= '</div>';
			
			
			// MENU
			$html.= '<div>';
				$html.= '<ul id="vbc_menu" class="vbc_menu_toggle vbc_main_menu_toggle" style="display:inline-block;">';
					$html.= '<li class="preview_banner preview right" data-option="vbc-preview">
							<i class="fa fa-search" aria-hidden="true" style="margin-right: 5px;"></i>
						</li>';
				$html.= '</ul>';
			$html.= '</div>';
			
			// Upload progress
			$html.= '<div id="wppas-vbc-upload-imagelist">';
				$html.= '<ul id="wppas-vbc-ul-list" class="wppas-vbc-upload-list"></ul>';
			$html.= '</div>';
			
			$html.= $wppas_banner_creator->editor_template(array(
				'editor_opts' => array(
					'frontend'    => 1,
					'html_editor' => 0,
					'add_images' => $data['vbc_image_uploads'],
					'add_text' => $data['vbc_text'],
					'add_shapes' => $data['vbc_shapes'],
					'add_icons' => $data['vbc_icons'],
					'add_svg' => $data['vbc_svg'],
					'add_button' => $data['vbc_btn'],
					'add_html' => $data['vbc_html'],
					'add_zip' => 0
				),
				'create_folder' => 1,
				'banner' => $inf['banner_data']
			));
			
			$html.= '<div style="margin-top:20px;">';
				$html.= '<div class="bs_confirmation_notice"></div>';
				$html.= '<a id="bs_confirm_banner" class="button-secondary green">'.__('Confirm & proceed to Payment','wpproads').'</a>';
			$html.= '</div>';
		$html.= '</div>';	
		
		return $html;
	}
	
	
	
	/**
	 * PAYPAL PAYMENT FORM
	 *
	 */
	public static function paypal_form($args = array())
	{
		global $wppas_paypal_ipn, $wppas_banner_creator;
		
		$data = self::get_buysell_data();
		$paypal_url = $wppas_paypal_ipn->wp_tuna_get_paypal_redirect( $data['paypal_sandbox'] );
		$rand = substr(uniqid('', true), -5);
		
		$html = '';
		$html.= '<h2>'.__('Payment','wpproads').'</h2>';
		
		// Banner Example
		$html.= '<div class="bs_example">';
			$html.= '<p>'.__('Great! This is what your banner will look like.','wpproads').'</p>';
			$html.= $wppas_banner_creator->show_banner_by_code($args);
		$html.= '</div>';
		
		$html.= '<form id="'.$rand.'_'.$args['adzone_id'].'" action="'.$paypal_url.'" method="post">';
			$html.= '<input type="hidden" name="cmd" value="_xclick">';
			$html.= '<input type="hidden" name="business" value="'.$data['paypal_email'].'">';
			$html.= '<input type="hidden" name="item_name" value="'.sprintf(__('Payment for Banner on %s'), get_bloginfo('name')).'">';
			$html.= '<input type="hidden" name="currency_code" value="'.$data['cur'].'">';
			$html.= '<input type="hidden" name="amount" class="amount" value="'.$args['adzone_data']['price'].'">';
			$html.= '<input type="hidden" name="notify_url" value="'.trailingslashit( home_url( 'index.php' ) ).'?wppas-pp-ipn=IPN" />';
			$html.= '<input type="hidden" name="return" value="'.trailingslashit( home_url( 'index.php' ) ).'?wppas_purchase='.$args['adzone_data']['ID'].'">';
			$html.= '<input type="hidden" name="custom" value="'.urlencode(json_encode($args['ipn_data'])).'">';
			$html.= '<input type="submit" class="button-secondary green" value="'.__('Buy Now','wpproads').'">';
		$html.= '</form>';
		
		return $html;
	}
	
	
	
	
	public static function paypal($args = array())
	{
		global $wppas_paypal_ipn, $wppas_banner_creator;
		
		$defaults = array(
			'id'           => 0, //adzone_id
			'price'        => 10,
			'form_style'   => '',
			'ipn_data'     => '',
			'submit_btn'   => __('Buy Now','wpproads'),
			'button_class' => 'button-secondary green',
			'notify'       => 'IPN',
			'return'       => 'wppas_purchase'
		);
		$args = wp_parse_args( $args, $defaults );
		
		$data = self::get_buysell_data();
		$paypal_url = $wppas_paypal_ipn->wp_tuna_get_paypal_redirect( $data['paypal_sandbox'] );
		$rand = substr(uniqid('', true), -5);
		$form_style = !empty($args['form_style']) ? ' style="'.$args['form_style'].'"' : '';
		$html = '';
		
		$html.= '<form id="'.$rand.'_'.$args['id'].'" action="'.$paypal_url.'" method="post"'.$form_style.'>';
			$html.= '<input type="hidden" name="cmd" value="_xclick">';
			$html.= '<input type="hidden" name="business" value="'.$data['paypal_email'].'">';
			$html.= '<input type="hidden" name="item_name" value="'.sprintf(__('Payment for Banner on %s'), get_bloginfo('name')).'">';
			$html.= '<input type="hidden" name="currency_code" value="'.$data['cur'].'">';
			$html.= '<input type="hidden" name="amount" class="amount" value="'.$args['price'].'">';
			$html.= '<input type="hidden" name="notify_url" value="'.trailingslashit( home_url( 'index.php' ) ).'?wppas-pp-ipn='.$args['notify'].'" />';
			$html.= '<input type="hidden" name="return" value="'.trailingslashit( home_url( 'index.php' ) ).'?'.$args['return'].'='.$args['id'].'">';
			$html.= '<input type="hidden" name="custom" value="'.urlencode(json_encode($args['ipn_data'])).'">';
			$html.= '<input type="submit" class="'.$args['button_class'].'" value="'.$args['submit_btn'].'">';
		$html.= '</form>';	
		
		return $html;
	}
	
	
	
	/**
	 * Remove Order
	 */
	public static function remove_order($args = array())
	{
		global $wpdb, $wppas_banner_creator;
		
		$defaults = array(
			'id'           => 0,
			'banner_id'    => 0,
			'alphaID'      => 0
		);
		$args = wp_parse_args( $args, $defaults );
		
		if(!empty($args['alphaID']))
		{
			$wppas_banner_creator->deleteDir($args['alphaID']);
		}
		
		if( !empty($args['id']))
		{
			// By Order ID
			$wpdb->query( "DELETE FROM " . $wpdb->prefix . "wppas_buysell WHERE id = ".$args['id'].";" );
		}
		elseif( !empty($args['banner_id']))
		{
			// By Banner ID
			$wpdb->query( "DELETE FROM " . $wpdb->prefix . "wppas_buysell WHERE banner_id = ".$args['banner_id'].";" );
		}
		
	}
	
	
	
	
	
	
	
	/**
	 * All Purchases
	 * 
	 *
	 */
	public static function all_purchases($args = array())
	{
		global $wpdb, $pro_ads_main;
		
		wp_enqueue_script('WPPAS_VBC_BS');
		
		$defaults = array(
			'id' => 0,
			'query' => ''
		);
		$args = wp_parse_args( $args, $defaults );
		$html = '';
		
		$orders = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "wppas_buysell ".$args['query']);
		
		$html.= '<ul class="wppas_purchases">';
			foreach($orders as $order)
			{
				$status = self::order_status($order);
				$post_status = !empty($order->banner_id) ? get_post_status($order->banner_id) : '';
				$payment_status = !empty($order->am_paid) ? 'paid' : 'unpaid';
				
				$banner = !empty($order->banner) ? json_decode(json_encode(json_decode(stripslashes(urldecode($order->banner)))), true) : '';
				$banner_data = !empty($banner) ? array_key_exists('banner_data', $banner) ? json_decode($banner['banner_data'], true) : '' : '';
				$alphaID = array_key_exists('alphaID', $order) ? $order->alphaID : '';
				if(empty($alphaID) && !empty($banner_data))
				{
					 if( !empty($banner_data['timeline_arr']['main']))
					 {
						$alphaID = array_key_exists('alphaID', $banner_data['timeline_arr']['main']) ? $banner_data['timeline_arr']['main']['alphaID'] : $alphaID;
					 }
				}
				
				// fix to remove old entries from database
				if( !empty($order->banner_id) && empty($post_status))
				{
					self::remove_order(array('id' => $order->id));
				}
				
				$html.= '<li class="order order_'.$order->id.'">';
					$html.= '<div style="color:#c3c3c3; font-size:11px;">'.sprintf(__('%s ago','wpproads'), $pro_ads_main->time_ago($order->time)).'</div>';
					$html.= '<span class="status '.$status['value'].'">'.$status['name'].'</span>';
					$html.= $post_status == 'trash' ? '<span class="status trash">'.__('Trashed','wpproads').'</span>' : '';
					$html.= '<span>'.$order->email.' <span style="color:#c3c3c3; font-size:11px;">(ID: '.$order->advertiser_id.')</span></span>';
					$html.= '<div>';
						if( !empty($order->banner_id))
						{
							$html.= 'Banner: <a href="admin.php?page=wppas-banner-creator&view=editor&bid='.$order->banner_id.'">'.$order->banner_id.'</a>';
						}
						else
						{
							$html.= 'Banner: /';	
						}
						$html.= '<span>, Adzone: <a href="admin.php?page=wppas-banner-creator&view=adzone_editor&aid='.$order->adzone_id.'">'.$order->adzone_id.'</a></span>';
						$html.= ' <span style="color:#c3c3c3; font-size:11px;">('.$alphaID.')</span>'; 
					$html.= '</div>';
					$html.= '<div>';
						$html.= 'Price:'.$order->price;
						$html.= !empty($order->am_paid) ? ' <span class="'.$payment_status.'">Paid:'.$order->am_paid.'</span>' : '';
					$html.= '</div>';
					if( $status['value'] == 'abandoned')
					{
						$html.= '<a class="remove" data-order-id="'.$order->id.'">'.__('Remove','wpproads').'</a>';
					}
				$html.= '</li>';
			}
		$html.= '</ul>';
		
		$html.= '<script type="text/javascript">';
			$html.= 'var _VBC = jQuery(".wppas_purchases");';
			
			$html.= 'jQuery(document).ready(function($){';
				$html.= '_VBC.wppas.purchases({});';
			$html.= '});';
		$html.= '</script>';
		
		return $html;
	}
	
	
	
	
	/**
	 * Order Status
	 * 
	 *
	 */
	public static function order_status($order = array())
	{
		$status = $order->status == 1 ? 'active' : $order->status;
		$status = empty($status) ? 'abandoned' : $status;
		if( $status == 'abandoned' )
		{
			$status = current_time('timestamp') - $order->time < 3600 ? 'in-progress' : $status;
		}
		$status = self::status(array('key' => $status));
		
		return $status;
	}
	
	/**
	 * Status Array
	 * 
	 *
	 */
	public static function status($args = array())
	{
		$defaults = array(
			'key' => ''
		);
		$args = wp_parse_args( $args, $defaults );
		
		$array = array(
			'draft' => array('value' => 'draft', 'name' => __('Pending Review','wpproads')),
			'abandoned' => array('value' => 'abandoned', 'name' => __('Not Finished','wpproads')),
			'in-progress' => array('value' => 'in-progress', 'name' => __('In Progress','wpproads')),
			'active' => array('value' => 'active', 'name' => __('Active','wpproads')),
			'expired' => array('value' => 'expired', 'name' => __('Expired','wpproads')),
			'trash' => array('value' => 'trash', 'name' => __('Trashed','wpproads')),
			'renewed' => array('value' => 'renewed', 'name' => __('Renewed','wpproads')),
		);
		
		return !empty($args['key']) ? $array[$args['key']] : $array;
	}
	
	/**
	 * Adzone Info
	 *
	 */
	public static function adzone_info($ID)
	{
		global $wppas_adzone_creator;
		
		$data = $wppas_adzone_creator->load_adzone_data($ID);
		$size = WPPAS_TPL::vbc_data(array('id' => $ID, 'type' => 'size', 'default'  => '300x250'));
		$price = WPPAS_TPL::vbc_data(array('id' => $ID, 'type' => 'bs_price', 'default'  => 100));
		$pos_bid = WPPAS_TPL::vbc_data(array('id' => $ID, 'type' => 'bs_pos_bid', 'default'  => 5));
		$contract = WPPAS_TPL::vbc_data(array('id' => $ID, 'type' => 'bs_contract', 'default'  => 'ppc'));
		$duration = WPPAS_TPL::vbc_data(array('id' => $ID, 'type' => 'bs_duration', 'default'  => 100));
		$linked_banners = $data['adzone_data'][0]['banners'];
		$linked_banners_num = !empty($linked_banners) ? count($linked_banners) : 0;
		$max_banners = WPPAS_TPL::vbc_data(array('id' => $ID, 'type' => 'bs_max_banners', 'default' => ''));
		$rotation = WPPAS_TPL::vbc_data(array('id' => $ID, 'type' => 'rotation', 'default' => 1));
		$rotation_shuffle = WPPAS_TPL::vbc_data(array('id' => $ID, 'type' => 'rotation_shuffle', 'default' => 0));
		$bidding = $rotation && empty($rotation_shuffle) ? 1 : 0;
		$rotation_time = WPPAS_TPL::vbc_data(array('id' => $ID, 'type' => 'rotation_time', 'default' => 5000));
		$rotation_icon = empty($max_banners) || $max_banners > 1 ? __('<i class="fa fa-refresh" style="color:#dedede;"></i>','wpproads') : '';
		$rotate_info = !empty($max_banners) ? sprintf(__('Ad will rotate with max. %s other ads','wpproads'), ($max_banners-1)) : __('Ad will rotate with other ads','wpproads');
		$spots = !empty($max_banners) ? $max_banners-$linked_banners_num : 1;
		$spots_available = !empty($max_banners) ? $max_banners-$linked_banners_num : __('Unlimited','wpproads');
		$contract_line = self::contract_line(array('contract' => $contract, 'duration' => $duration));
		
		$adzone_info = array(
			'name' => get_the_title($ID),
			'size' => $size,
			'price' => $price,
			'pos_bid' => $pos_bid,
			'contract' => $contract,
			'duration' => $duration,
			'linked_banners' => $linked_banners,
			'linked_banners_num' => $linked_banners_num,
			'max_banners' => $max_banners,
			'bidding' => $bidding,
			'rotation' => $rotation,
			'rotation_time' => $rotation_time,
			'rotation_icon' => $rotation_icon,
			'rotate_info' => $rotate_info,
			'spots' => $spots,
			'spots_available' => $spots_available,
			'contract_line' => $contract_line
		);
		
		return $adzone_info;
	}
	
	
	
	
	/**
	 * All available adzones
	 */
	public static function all_available_adzones($args = array())
	{
		global $wppas_adzone_creator;
		
		$defaults = array(
			'title' => __('Advertising Spots','wpproads'),
			'exclude' => array()
		);
		$args = wp_parse_args( $args, $defaults );
		$html = '';
		$bs_data = self::get_buysell_data();
		
		$html.= '<div class="bs_available_zones">';
			$html.= '<h1 class="title">'.$args['title'].'</h1>';
			$html.= '<ul class="bs">';
				$adzones = $wppas_adzone_creator->all_adzones_query(array('exclude' => $args['exclude']));
				if(!empty($adzones))
				{
					foreach($adzones as $adzone)
					{
						$data = $wppas_adzone_creator->load_adzone_data($adzone->ID);
						$size = WPPAS_TPL::vbc_data(array('id' => $adzone->ID, 'type' => 'size', 'default'  => '300x250'));
						$price = WPPAS_TPL::vbc_data(array('id' => $adzone->ID, 'type' => 'bs_price', 'default'  => 100));
						$contract = WPPAS_TPL::vbc_data(array('id' => $adzone->ID, 'type' => 'bs_contract', 'default'  => 'ppc'));
						$duration = WPPAS_TPL::vbc_data(array('id' => $adzone->ID, 'type' => 'bs_duration', 'default'  => 100));
						$linked_banners = $data['adzone_data'][0]['banners'];
						$linked_banners_num = !empty($linked_banners) ? count($linked_banners) : 0;
						$max_banners = WPPAS_TPL::vbc_data(array('id' => $adzone->ID, 'type' => 'bs_max_banners', 'default' => ''));
						$rotation = empty($max_banners) || $max_banners > 1 ? 1 : 0;
						$rotation_icon = empty($max_banners) || $max_banners > 1 ? __('<i class="fa fa-refresh" style="color:#dedede;"></i>','wpproads') : '';
						$rotate_info = !empty($max_banners) ? sprintf(__('Ad will rotate with max. %s other ads','wpproads'), ($max_banners-1)) : __('Ad will rotate with other ads','wpproads');
						$spots = !empty($max_banners) ? $max_banners-$linked_banners_num : 1;
						$spots_available = !empty($max_banners) ? $max_banners-$linked_banners_num : __('Unlimited','wpproads');
						$contract_line = self::contract_line(array('contract' => $contract, 'duration' => $duration));
				
						if( $data['adzone_data'][0]['buyandsell'] )
						{
							//$html.= print_r($data['adzone_data'],true);
							$html.= '<li class="order">';
								$html.= '<a href="?adzone='.$adzone->ID.'" class="box">';
								$html.= '<div class="one_second v_middle">';
									$html.= '<span style="color:#6b6b6b;"><strong>'.$adzone->post_title.'</strong> '.__('adzone','wpproads').' '.$rotation_icon.'</span>';
									if( $spots <= 0 )
									{
										// soldout
										$html.= '<div class="status soldout" style="text-transform:uppercase;margin: 0 0 0 10px;">'.__('Currently sold out','wpproads').'</div>';
									}
									else
									{
										// available
										$html.= '<div class="status available" style="text-transform:uppercase;margin: 0 0 0 10px;">'.sprintf(__('%s Spots Available','wpproads'), $spots_available).'</div>';
									}
									// adzone rotation info
									$html.= $rotation ? '<div style="font-size:12px;color:#c3c3c3;"><strong>'.__('Rotation','wpproads').'</strong> - '.$rotate_info.'</div>' : '';
									// adzone size info
									$html.= '<div style="font-size:12px;color:#c3c3c3;"><strong>'.__('Size','wpproads').'</strong> - '.$size.'</div>';
								$html.= '</div>';
								$html.= '<div class="one_second v_middle" style="color: #c3c3c3; text-align:center;">';
									$html.= '<span>'.$price.' '.$bs_data['cur'].'</span>';
									$html.= '<div><small>'.sprintf(__('Per %s','wpproads'),$contract_line).'</small></div>';
								$html.= '</div>';
								
								$html.= '</a>';
							$html.= '</li>';
						}
					}
				}
			$html.= '</ul>';
		$html.= '</div>';
		// end .bs_available_zones
		
		return $html;
	}
	
	
	
	
	
	
	/**
	 * USER DASHBOARD - Frontent
	 */
	public static function user_dashboard($args = array())
	{
		global $wppas_adzone_creator, $wppas_banner_creator, $pro_ads_main;
		
		$defaults = array(
			'title' => __('Your Banners','wpproads')
		);
		$args = wp_parse_args( $args, $defaults );
		$html = '';
		$bs_data = self::get_buysell_data();
		
		if( is_user_logged_in() )
		{
			$user = wp_get_current_user();
			$email = $user->user_email;
			
			$orders = self::load_order(array('query' => "WHERE email = '".$email."' ORDER BY id DESC"));
			
			$html.= '<div class="wppas bs_available_zones">';
				$html.= '<h1 class="title">'.$args['title'].'</h1>';
				$html.= '<ul class="bs">';
					if( !empty($orders))
					{
						foreach( $orders as $order)
						{
							$status = self::order_status($order);
							if( $status['value'] != 'renewed')
							{
								$post_status = !empty($order->banner_id) ? get_post_status($order->banner_id) : '';
								//$alphaID = $wppas_banner_creator->get_alphaID(array('id' => $order->banner_id));
								
								$html.= '<li class="order" style="padding:10px;" data-order-id="'.$order->id.'">';
									// Banner info
									$html.= '<div class="one_third v_middle">';
										$html.= !empty($order->banner_id) ? '<span>'.get_the_title($order->banner_id).'</span>' : '';
										$html.= '<span style="color:#c3c3c3;font-size:11px;margin-left:5px;">'.sprintf(__('Created: %s ago','wpproads'), $pro_ads_main->time_ago($order->time)).'</span>';
										$html.= '<div>';
											$html.= '<span class="status '.$status['value'].'" style="color:#FFF;">'.$status['name'].'</span>';
											$html.= $post_status == 'trash' ? '<span class="status trash">'.__('Trashed','wpproads').'</span>' : '';
										$html.= '</div>';
									$html.= '</div>';
									
									// Adzone info
									$adzone_info = !empty($order->adzone_id) ? self::adzone_info($order->adzone_id) : array();
									$html.= '<div class="one_third v_middle">';
										$html.= '<span style="color:#c3c3c3;font-size:11px;">'.__('Linked to:','wpproads').'</span>';
										$html.= !empty($order->adzone_id) ? ' <strong>'.get_the_title($order->adzone_id).'</strong>' : '';
										$html.= !empty($order->adzone_id) ? ' <span>'.__('adzone','wpproads').'</span>' : '';
										$html.= !empty($order->adzone_id) ? ' '.$adzone_info['rotation_icon'] : '';
										$html.= $adzone_info['rotation'] ? '<div style="font-size:12px;color:#c3c3c3;"><strong>'.__('Rotation','wpproads').'</strong> - '.$adzone_info['rotate_info'].'</div>' : '';
										$html.= '<div style="font-size:12px;color:#c3c3c3;"><strong>'.__('Size','wpproads').'</strong> - '.$adzone_info['size'].'</div>';
									$html.= '</div>';
									
									// Edit banner
									if( !empty($order->banner_id))
									{
										$html.= '<div class="one_third v_middle" style="text-align:right;">';
											$html.= $status['value'] == 'expired' ? self::paypal(array(
												'id'           => $order->adzone_id,
												'price'        => $adzone_info['price'],
												'form_style'   => 'display:inline-block;margin-right:5px;',
												'ipn_data'     => array('order_id' => $order->id),
												'submit_btn'   => __('Re-Activate','wpproads'),
												'button_class' => 'reactivate_banner',
												'notify'       => 'RENEW',
												'return'       => 'wppas_purchase'
											)) : '';
											//$html.= $status['value'] == 'expired' ? '<a class="reactivate_banner" style="margin-right:5px;" href="?adzone='.$order->adzone_id.'&amp;banner_id='.$order->banner_id.'&amp;order_id='.$order->id.'">'.__('Re-Activate','wpproads').'</a>' : '';
											$html.= '<a class="edit_banner edit_banner_'.$order->banner_id.'" data-banner="'.$order->banner_id.'">'.__('Edit Banner','wpproads').'</a>';
										$html.= '</div>';
									}
								$html.= '</li>';
							}
						}
						
						// Edit Popup
						$pop = '';
						$pop.= '<div class="vbc_loader_duration" style="display:none;z-index:999999;position:fixed;top:20%;">';
							$pop.= $wppas_banner_creator->vbc_loader();
						$pop.= '</div>';
						$pop.= '<div class="vbc_edit_modal_content"></div>';
						
						$html.= WPPAS_TPL::full_page_modal(array(
							'id' => 'vbc_edit_modal',
							'content' => $pop,
							'script' => '$(".edit_banner").on("click", function(){ console.log("open"); $(".vbc_edit_modal_content").html(""); $(this).wppas.load_vbc({banner_id:$(this).data("banner")}); });'
						));
					}
				$html.= '</ul>';
			$html.= '</div>';
		}
		else
		{
			$html.= '<div>'.__('You need to be loggedin to access this content.', 'wpproads').'</div>';
		}
			
		
		return $html;
	}
	
}
?>