<?php

class Sales extends Controller{

	//! HTTP route pre-processor
	/**
	 * @param $f3 \Base
	 */
	function beforeroute($f3) {
		parent::beforeroute($f3);

		// Only admins/super admins can use this class
		if ($f3->get('USER')->role < 8){
			$f3->error(403);
		}
	}

	/**
	 * @param $f3 \Base
	 */
	public function getIndex($f3){

		// Template settings
		$f3->set('active','sales');
		$f3->set('inc','sales.html');
		$f3->set('inc_bottom', 'sales-bottom.html');
		$f3->set('title',$f3->get('lang_sales_spots'));

		// Load available ads for listing
		$res_sales = new \Models\Sale();
		$sales = $res_sales->find();

		// Get ad stats
		$statsData = new Statsdata();
		$salesStats = $statsData->DashboardTopSales(7, 9999);

		$price_types = $this->pricingTypes($f3);
		$res_sales = array();
		if ($sales){
			$count = 0;
			foreach ($sales as $sale) {
				$res_sale = array();
				$res_sale['id'] = $sale->_id;
				$res_sale['title'] = '<a href="index.php?sales&edit&'.$sale->_id.'">'.$sale->title.'</a>';
				$res_sale['status'] = $sale->status;
				$res_sale['last_updated'] = date('Y/m/d H:i:s', $sale->last_updated);
				$res_sale['site_name'] = $sale->site_name ? $sale->site_name : '-';
				$res_sale['pricing_cost'] = number_format($sale->pricing_cost, 2);
				$res_sale['pricing_type'] = $price_types[$sale->pricing_type]["name"];
				$res_sale['fill_group'] = $sale->fill_group  ? '<a href="index.php?groups&edit&'.$sale->fill_group->_id.'">'.$sale->fill_group->title.'</a>' : '-';
				$res_sale['clicks'] = array_key_exists($sale->_id, $salesStats)  ? $salesStats[$sale->_id]['clicks'] : 0;
				$res_sale['sales'] = array_key_exists($sale->_id, $salesStats)  ? $salesStats[$sale->_id]['sales'] : 0;
				switch ($sale->type){
					case 'banner':
						$res_sale['type'] = 'fa-picture-o';
						break;
					case 'textlink':
						$res_sale['type'] = 'fa-external-link';
						break;
					case 'video':
						$res_sale['type'] = 'fa-video-camera';
						break;
					case 'freeform':
						$res_sale['type'] = 'fa-square-o';
						break;
				}
				$res_sale['count'] = $count;
				$res_sales[] = $res_sale;
				$count++;
			}
		}
		$f3->set('res_sales',$res_sales);

		echo Template::instance()->render('layout.html');

	}

	/**
	 * @param $f3 \Base
	 */
	public function getCreate($f3){

		// Template settings
		$f3->set('active','sales');
		$f3->set('inc','sales-edit.html');
		$f3->set('inc_bottom', 'sales-edit-bottom.html');
		$f3->set('title',$f3->get('lang_sales_spots'));

		// Create a blank ad model
		$sale = new \Models\Sale();
		$f3->set('res_sale',$sale);

		// Load available groups for listing
		$res_groups = new \Models\Group();
		$groups = $res_groups->find();
		$f3->set('res_groups',$groups);

		$f3->set('types', $this->adTypes($f3));
		$f3->set('price_types', $this->pricingTypes($f3));
		$f3->set('currencies', $this->currencies($f3));

		echo Template::instance()->render('layout.html');

	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function postCreate($f3, $params){

		// Check for DEMO settings
		if ($f3->get('DEMO') == 1) $f3->reroute('/index.php?sales&list');

		if ($f3->get('POST.fill_group') == '') $f3->set('POST.fill_group', null);

		$result = false;
		try {
			$sale = new \Models\Sale();
			$result = $sale->post($f3, $params, false);

			if (!$f3->exists('POST.test')){
				$result ? $f3->reroute('/index.php?sales&list') : $f3->reroute('/index.php?sales&create');
			}
		} catch (Exception $e){
			Utils::Logger('postCreate:Error posting sale - '.$e);
		}

	}


	/**
	 * @param $f3 \Base
	 */
	public function getEdit($f3){

		$id = $f3->get('PARAMS.id');
		$sale = new \Models\Sale();
		$sale->load(array('_id = ?', $id));
		if ($sale->dry()) $f3->reroute('/index.php?sales&list');
		$f3->set('res_sale', $sale);

		// Template settings
		$f3->set('active','sales');
		$f3->set('inc','sales-edit.html');
		$f3->set('inc_bottom', 'sales-edit-bottom.html');
		$f3->set('title',$f3->get('lang_sales_spots'));

		$f3->set('time_last_updated', date('Y/m/d H:i:s', $sale->last_updated));

		// Load available groups for listing
		$res_groups = new \Models\Group();
		$groups = $res_groups->find();
		$f3->set('res_groups',$groups);

		$f3->set('types', $this->adTypes($f3));
		$f3->set('price_types', $this->pricingTypes($f3));
		$f3->set('currencies', $this->currencies($f3));

		echo Template::instance()->render('layout.html');

	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function postEdit($f3, $params){

		// Check for DEMO settings
		if ($f3->get('DEMO') == 1) $f3->reroute('/index.php?sales&list');

		if ($f3->get('POST.fill_group') == '') $f3->set('POST.fill_group', null);

		// Keep ads data
		$id = $f3->get('PARAMS.id');
		$sale = new \Models\Sale();
		$sale->load(array('_id = ?', $id));
		if ($sale->dry()) $f3->reroute('/index.php?sales&list');

		//$saleAds = $sale->ads;
		//if (!empty($saleAds)) $f3->set('POST.ads', $sale->ads);

		try {

			$sale = new \Models\Sale();
			$result = $sale->post($f3, $params, true, array('ads','site_key'));

			$result ? $f3->reroute('/index.php?sales&list') : $f3->reroute('/index.php?sales&edit&'.$f3->get('PARAMS.id'));
		} catch (Exception $e){
			Utils::Logger('postEdit:Error posting sale - '.$e);
		}

	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function postDelete($f3, $params){

		// Check for DEMO settings
		if ($f3->get('DEMO') == 1) $f3->reroute('/index.php?sales&list');

		try {
			$sale = new \Models\Sale();
			$result = $sale->delete($f3, $params);
			echo $result;
		} catch (Exception $e){
			Utils::Logger('postDelete:Error deleting sale - '.$e);
		}
		$msg = \FlashMessage::instance();
		$arr = $msg->getMessages();

	}


	/**
	 * @param $f3 \Base
	 */
	public function getCodes($f3){

		$id = $f3->get('PARAMS.id');
		$sale = new \Models\Sale();
		$sale->load(array('_id = ?', $id));
		if ($sale->dry()) $f3->reroute('/index.php?sales&list');
		$f3->set('sale', $sale);

		// Template settings
		$f3->set('active','sales');
		$f3->set('inc','sales-code.html');
		$f3->set('inc_bottom', 'sales-code-bottom.html');
		$f3->set('title',$f3->get('lang_sales_code'));

		$salesUrl = $f3->get('SCHEME').'://'.$f3->get('HOST').$f3->get('BASE').'/index.php?spots&'.$sale->site_key;
		$f3->set('sales_url', $salesUrl);

		// Check if any of the ads requires php only
		$f3->set('php_only', false);
		if (!empty($sale->fill_group)){
			$ads = $sale->fill_group->ads;
			if (count($ads) > 0){
				foreach ($ads as $ad) {
					if ($ad->type == 'freeform') {
						if ((stristr($ad->type_freeform->text, '<script>') !== false) ||
								(stristr($ad->type_freeform->text, '<?php') !== false)
						) {
							$f3->set('php_only', true);
							break;
						}
					}
				}
			}
		}


		echo Template::instance()->render('layout.html');

	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function getCode($f3, $params){

		$code = '';

		$id = $f3->get('PARAMS.id');
		$type = $f3->get('PARAMS.type');
		if ((empty($id)) || (empty($type))) return;

		$url = str_replace('admin', 'api',$f3->get('HOST').$f3->get('BASE'));

		$sale = new \Models\Sale();
		$sale->load(array('_id=?', $id));
		if ($sale->dry()) return;

		$keywordsOrIdData = 'data-id="'.$id.'"';
		$jsUrl = $url.'/index.php?js&s&';
		$phpUrl = $f3->get('SCHEME').'://'.$url.'/index.php?in&s&i='.$id.'&';

		$class = 'mgsv1_';
		$varCheck = 'mysa_'.$class;

		$html_sale_title = htmlentities('<!--'.$sale->title.'-->');

		switch ($type){
			case 1: // JS Standard HTML
				$code = $html_sale_title.htmlentities('<span '.$keywordsOrIdData.' class="'.$class.'1"><script>(window.jQuery || document.write("<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js\"><\/script>"))</script><script type="text/javascript">(function(){if('.$varCheck.'1) return; var ma = document.createElement("script"); ma.type = "text/javascript"; ma.async = true; ma.src = "http" + ("https:"==document.location.protocol?"s":"") + "://'.$jsUrl.'1&v=2"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ma, s) })();var '.$varCheck.'1=true;</script></span>');
				break;
			case 2: // JS Floating top
				$code = $html_sale_title.htmlentities('<span '.$keywordsOrIdData.' data-l="top" class="'.$class.'3"><script>(window.jQuery || document.write("<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js\"><\/script>"))</script><script type="text/javascript">(function(){if('.$varCheck.'3) return; var ma = document.createElement("script"); ma.type = "text/javascript"; ma.async = true; ma.src = "http" + ("https:"==document.location.protocol?"s":"") + "://'.$jsUrl.'3&v=2"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ma, s) })();var '.$varCheck.'3=true;</script></span>');
				break;
			case 3: // JS Floating bottom
				$code = $html_sale_title.htmlentities('<span '.$keywordsOrIdData.' data-l="bottom" class="'.$class.'3"><script>(window.jQuery || document.write("<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js\"><\/script>"))</script><script type="text/javascript">(function(){if('.$varCheck.'3) return; var ma = document.createElement("script"); ma.type = "text/javascript"; ma.async = true; ma.src = "http" + ("https:"==document.location.protocol?"s":"") + "://'.$jsUrl.'3&v=2"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ma, s) })();var '.$varCheck.'3=true;</script></span>');
				break;
			case 4: // JS Rotating
				$code = $html_sale_title.htmlentities('<span '.$keywordsOrIdData.' data-i="5000" class="'.$class.'2"><script>(window.jQuery || document.write("<script src=\"//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js\"><\/script>"))</script><script type="text/javascript">(function(){if('.$varCheck.'2) return; var ma = document.createElement("script"); ma.type = "text/javascript"; ma.async = true; ma.src = "http" + ("https:"==document.location.protocol?"s":"") + "://'.$jsUrl.'2&v=2"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ma, s) })();var '.$varCheck.'2=true;</script></span>');
				break;
			case 5: // PHP Standard HTML
				$code = '&lt;?php'.htmlentities(' /* '.$sale->title.' */ '.'@readfile(\''.$phpUrl.'c=1&at=p&r=\'.$_SERVER[\'REMOTE_ADDR\'].\'&h=\'.urlencode($_SERVER[\'HTTP_HOST\']).\'&rf=\'.urlencode($_SERVER[\'HTTP_REFERER\']).\'&ua=\'.urlencode($_SERVER[\'HTTP_USER_AGENT\']));'.' ?>');
				break;
			case 6: // PHP Floating top
				$code = '&lt;?php'.htmlentities(' /* '.$sale->title.' */ '.'@readfile(\''.$phpUrl.'c=3&at=p&loc=top&r=\'.$_SERVER[\'REMOTE_ADDR\'].\'&h=\'.urlencode($_SERVER[\'HTTP_HOST\']).\'&rf=\'.urlencode($_SERVER[\'HTTP_REFERER\']).\'&ua=\'.urlencode($_SERVER[\'HTTP_USER_AGENT\']));'.' ?>');
				break;
			case 7: // PHP Floating bottom
				$code = '&lt;?php'.htmlentities(' /* '.$sale->title.' */ '.'@readfile(\''.$phpUrl.'c=3&at=p&loc=bottom&r=\'.$_SERVER[\'REMOTE_ADDR\'].\'&h=\'.urlencode($_SERVER[\'HTTP_HOST\']).\'&rf=\'.urlencode($_SERVER[\'HTTP_REFERER\']).\'&ua=\'.urlencode($_SERVER[\'HTTP_USER_AGENT\']));'.' ?>');
				break;
		}

		echo json_encode($code);
	}


	/**
	 * @param $f3 \Base
	 */
	public static function adTypes($f3){
		$adTypes = array(
				'banner' => array('name' => $f3->get('lang_image_banner'), 'type' => 'banner'),
				'textlink' => array('name' => $f3->get('lang_text_link'), 'type' => 'textlink'),
				'video' => array('name' => $f3->get('lang_video'), 'type' => 'video'),
				'freeform' => array('name' => $f3->get('lang_free_form'), 'type' => 'freeform')
		);
		return ($adTypes);
	}

	/**
	 * @param $f3 \Base
	 */
	public static function pricingTypes($f3){

		$pricingTypes = array(
				'cpm' => array('name' => $f3->get('lang_1_000_impressions__cpm_'), 'type' => 'cpm'),
				'cpc' => array('name' => $f3->get('lang_1_click__cpc_'), 'type' => 'cpc'),
				'month' => array('name' => $f3->get('lang_1_month'), 'type' => 'month'),
				'3month' => array('name' => $f3->get('lang_3_month'), 'type' => '3month'),
				'6month' => array('name' => $f3->get('lang_6_month'), 'type' => '6month'),
				'week' => array('name' => $f3->get('lang_1_week'), 'type' => 'week'),
				'year' => array('name' => $f3->get('lang_1_year'), 'type' => 'year'),
				'day' => array('name' => $f3->get('lang_1_day'), 'type' => 'day')
		);
		return ($pricingTypes);
	}

	/**
	 * @param $f3 \Base
	 */
	public static function currencies($f3){

		$currencies = array(
				'USD' => array('name' => $f3->get('lang_u_s__dollar____'), 'type' => 'USD'),
				'AUD' => array('name' => $f3->get('lang_austrailian_dollar__a___'), 'type' => 'AUD'),
				'CAD' => array('name' => $f3->get('lang_canadian_dollar__c___'), 'type' => 'CAD'),
				'GBP' => array('name' => $f3->get('lang_british_pound____'), 'type' => 'GBP'),
				'EUR' => array('name' => $f3->get('lang_euro____'), 'type' => 'EUR'),
				'CHF' => array('name' => $f3->get('lang_swiss_franc__chf_'), 'type' => 'CHF')
		);
		return ($currencies);
	}


	/**
	 * @param $f3 \Base
	 */
	public function postUpload($f3){
		$web = \Web::instance();

		$overwrite = true; // set to true, to overwrite an existing file; Default: false
		$slug = true; // rename file to filesystem-friendly version
		$uploadUrl = $f3->get('SCHEME').'://'.$f3->get('HOST').$f3->get('BASE').'/';

		$file = $web->receive(function($file){
					if ($file['error'] != 0) return false;

					if (($file["type"] == 'image/png') ||
							($file["type"] == 'image/jpg') ||
							($file["type"] == 'image/jpeg') ||
							($file["type"] == 'image/gif')){

						if($file['size'] > (2 * 1024 * 1024)) // if bigger than 2 MB
							return false; // this file is not valid, return false will skip moving it

						return true; // allows the file to be moved from php tmp dir to your defined upload dir
					}

					return false;

				},
				$overwrite,
				$slug
		);
		if ($file){
			echo '{"result":'.json_encode(array('url'=>$uploadUrl.key($file))).'}';
		} else {
			echo '{"result":'.json_encode(array('error'=>'Error uploading file.')).'}';
		}
	}
}
