<?php

class Groups 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','groups');
		$f3->set('inc','groups.html');
		$f3->set('inc_bottom', 'groups-bottom.html');
		$f3->set('title',$f3->get('lang_ad_groups'));

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

		// Get group stats
		$statsData = new Statsdata();
		$groupStats = $statsData->DashboardTopGroups(7, 9999);

		$res_groups = array();
		if ($groups){
			$count = 1;
			foreach ($groups as $group) {
				$res_group = array();

				// Get selected ad ids
				$selected_ads = array();

				$ads = $group->ads;
				if (!empty($ads)) {
					$ad_ids = array();
					if (!empty($group->ad_order)) {
						$ad_ids = explode(',', $group->ad_order);

						foreach ($ad_ids as $ad_id) {
							foreach ($ads as $a) {
								if ($a->_id == $ad_id) {
									$selected_ads[] = $a;
									continue;
								}
							}
						}

						foreach ($ads as $ad) {
							if (!in_array($ad->_id, $ad_ids)) {
								$unselected_ads[] = $ad;
							}
						}

					} else {
						if ($group->ads) {
							foreach ($group->ads as $ad) {
								$ad_ids[] = $ad->_id;
							}
						}

						if (count($ad_ids) > 0) {
							foreach ($ads as $ad) {
								if (in_array($ad->_id, $ad_ids)) {
									$selected_ads[] = $ad;
								}
							}
						}
					}
				}
				$res_group['ads'] = $selected_ads;

				$res_group['id'] = $group->_id;
				$res_group['title'] = '<a href="index.php?groups&edit&'.$group->_id.'">'.$group->title.'</a>';
				$res_group['last_updated'] = date('Y/m/d H:i:s', $group->last_updated);
				//$res_group['ads'] = $group->ads;
				$res_group['impressions'] = array_key_exists($group->_id, $groupStats)  ? $groupStats[$group->_id]['impressions'] : 0;
				$res_group['count'] = $count;
				$res_groups[] = $res_group;
				$count++;
			}
		}
		$f3->set('res_groups',$res_groups);
		
		echo Template::instance()->render('layout.html');

	}

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

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

		// Create a blank group model
		$res_group = new \Models\Group();
		$f3->set('res_group',$res_group);

			// Load available ads for listing
		$res_ads = new \Models\Ad();
		$ads = $res_ads->find(null, array('order'=>'title'));
		$f3->set('unselected_ads',$ads);
		$f3->set('selected_ads',null);
		$f3->set('ad_ids',array());

		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?groups&list');

		$ad_ordering = $f3->get('POST.ad_order_type');
		if ($ad_ordering == '2'){
			$f3->set('POST.ad_order', implode(',',$f3->get('POST.ads')));
		} else {
			$f3->set('POST.ad_order', null);
		}

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

			if (!$f3->exists('POST.test')){
				$result ? $f3->reroute('/index.php?groups&list') : $f3->reroute('/index.php?groups&create');
			}

		} catch (Exception $e){
			Utils::Logger('postCreate:Error posting group - '.$e);
		}

	}


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

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

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

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

		// Load available ads for listing
		$res_ads = new \Models\Ad();
		$ads = $res_ads->find(null, array('order'=>'title'));

		// Get selected ad ids
		$selected_ads = array();
		$unselected_ads = array();

		$ad_ids = array();
		if (!empty($res_group->ad_order)){
			$ad_ids = explode(',', $res_group->ad_order);

			foreach ($ad_ids as $ad_id) {
				foreach ($ads as $a) {
					if ($a->_id == $ad_id){
						$selected_ads[] = $a;
						continue;
					}
				}
			}

			foreach ($ads as $ad) {
				if (!in_array($ad->_id, $ad_ids)){
					$unselected_ads[] = $ad;
				}
			}

		} else {

			if ($res_group->ads){
				foreach ($res_group->ads as $ad){
					$ad_ids[] = $ad->_id;
				}
			}
			if (!empty($ads)){
				foreach ($ads as $ad) {
					if (in_array($ad->_id, $ad_ids)){
						$selected_ads[] = $ad;
					} else {
						$unselected_ads[] = $ad;
					}
				}
			}

		}

		$f3->set('selected_ads',$selected_ads);
		$f3->set('unselected_ads',$unselected_ads);

		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?groups&list');

		$ad_ordering = $f3->get('POST.ad_order_type');
		if ($ad_ordering == '2'){
			if ($f3->get('POST.ads') != null){
				$f3->set('POST.ad_order', implode(',',$f3->get('POST.ads')));
			} else {
				$f3->set('POST.ad_order', null);
			}
		} else {
			$f3->set('POST.ad_order', null);
		}

		try {
			$res_group = new \Models\Group();
			$result = $res_group->post($f3, $params);

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

	}


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

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

		try {

			$groupId = $params['id'];
			$group = new \Models\Group();
			$group->load(array('_id = ?', $groupId));
			if ($group->dry()) return;

			$ads = $group->ads;

			if (!empty($ads)){
				foreach ($ads as $ad) {

					// remove group from any ads
					$a = new \Models\Ad();
					$a->load(array('_id = ?', $ad->_id));

					$ad_groups = $ad->groups;
					$adGroupsArray = array();
					foreach ($ad_groups as $ad_group) {
						if ($ad_group->_id == $group->_id) continue;
						$adGroupsArray[] = $ad_group->_id;
					}

					$a->groups = $adGroupsArray;
					$a->save();

				}
			}

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

	}


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

		$id = $f3->get('PARAMS.id');
		$group = new \Models\Group();
		$group->load(array('_id = ?', $id));
		if ($group->dry()) $f3->reroute('/index.php?groups&list');
		$ads = $group->ads;

		$f3->set('group', $group);

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

		$f3->set('php_only', false);
		$f3->set('vast', false);
		if (!empty($ads)){

			// Check if any of the ads requires php only
			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;
					}
				}
			}

			// Check if all the ads support VAST
			$f3->set('vast', true);
			foreach ($ads as $ad) {
				if ($ad->type == 'video'){
					$videoSrc = $ad->type_video->src;
					$extension = strtolower(pathinfo($videoSrc, PATHINFO_EXTENSION));
					if ($extension == 'swf') {
						$f3->set('vast', false);
						break;
					}
				} else {
					$f3->set('vast', false);
					break;
				}
			}

		}

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


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

		// Only admins/super admins can do this function
		if ($f3->get('USER')->role < 8){
			$f3->error(403);
		}
		$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'));

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

		$keywords = $f3->get('GET.k') ? html_entity_decode(str_replace(', ',',',$f3->get('GET.k'))) : '';
		if (!empty($keywords)){
			$keywordsOrIdData = 'data-k="'.urlencode($keywords).'"';
			$jsUrl = $url.'/index.php?js&kg&';
			$phpUrl = $f3->get('SCHEME').'://'.$url.'/index.php?in&kg&k='.urlencode($keywords).'&';
			$class = 'mgkv1_';
			$varCheck = 'mysa_'.$class;
		} else {
			$keywordsOrIdData = 'data-id="'.$id.'"';
			$jsUrl = $url.'/index.php?js&g&';
			$phpUrl = $f3->get('SCHEME').'://'.$url.'/index.php?in&g&i='.$id.'&';
			$class = 'mgv1_';
			$varCheck = 'mysa_'.$class;
		}

		$html_group_title = htmlentities('<!--'.$group->title.'-->');

		switch ($type){
			case 1: // JS Standard HTML
				$code = $html_group_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_group_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_group_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_group_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(' /* '.$group->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(' /* '.$group->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(' /* '.$group->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;
			case 10: // VAST
				$outUrl = $f3->get('SCHEME').'://'.$url.'/index.php?in&v&g&'.$id;
				$code = htmlentities($outUrl);
		}

		echo json_encode($code);
	}


}
