<?php
/*
	DevSaver Web Framework
	Copyright (c) 2013-2014 DevSaver. 
	All rights reserved.
		web:  www.devsaver.com
		mail: support@devsaver.com		
*/

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CPopups extends CPlugin{
	
	var $tplvars; 
	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $position = array(
		"1" => "popup-left",
		"2" => "popup-right",
		"3" => "popup-top",
		"4" => "popup-bottom",
		"5" => "popup-center",
		"6" => "popup-full",
		"7" => "popup-bottom-left",
		"8" => "popup-bottom-right",		
		"9" => "popup-top-left",
		"10" => "popup-top-right",		
	);
	

	var $align = array(
		"0" => "widget-left",
		"1" => "widget-center",
		"2" => "widget-right",
	);


	function __construct() {
		//$this->CPlugin($db, $tables , $templates);
	}

	function DoEvents(){
		global $base, $_CONF, $_TSM , $_VARS , $_USER , $_BASE , $_SESS;	
		
		parent::DoEvents();

		if ($_GET["mod"] == "popups") {

			$this->__init();

			switch ($_GET["sub"]) {
				case "ajax.popup":
					return $this->AjaxPopup();
				break;

				case "ajax.close":
					return $this->AjaxClose();
				break;
			}
		}
	
	}

	function __init() {
		global $_CONF;

		if ($this->__inited) {
			return "";
		}

		$this->__inited = true;
		
		$path = $this->tpl_path;

		$templates = array(
			"init"	=> "init.htm",
			"popup"	=> "popup.htm"
		);

		foreach ($templates as $key => $val) {
			$this->private->templates[$key] = new CTemplateDynamic(
				$path . $val
			);
		}

		$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("popups");

	}



	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function onGlobalHooksExecute($module) {
		global $_LANG_ID , $_TSM , $base , $_SESS;



		//shortcodes
		$this->plugins["shortcodes"]->dynamic[] = array(
			"code"	=> 'popup',
			"method"	=> array(&$this, "shortcode")
		);

		//shortcodes
		$this->plugins["shortcodes"]->dynamic[] = array(
			"code"	=> 'clickpopup',
			"method"	=> array(&$this, "shortcode")
		);

		$cond = $this->SqlBaseCond();
		
		if ($module["mod_id"]) {
			$popup = $this->db->QFetchArray(
				"SELECT * FROM 
					{$this->tables['plugin:popups']}
				WHERE 
					( (find_in_set({$module[mod_id]} , popup_modules) AND 	popup_default = 0 ) OR popup_default=1) 
					{$cond}
					
				ORDER BY popup_default ASC, rand() limit 1"
			);

		} elseif ($module["module_id"]) {
			$popup = $this->db->QFetchArray(
				"SELECT * FROM 
					{$this->tables['plugin:popups']} 
				WHERE 
					((find_in_set({$module[module_id]} , popup_modules_global) AND popup_default = 0) OR popup_default = 1 )
					{$cond}
					
				ORDER BY popup_default ASC, rand() limit 1"
			);
		}

		if (is_array($popup)) {
			//add it as a shortcode
			$this->plugins["seo"]->AppendToBody(
				$this->Render($popup)
			);	
		}
		
	}

	function ShortCode($matches) {
		switch ($matches["shortcode"]) {
			case "popup":
				return $this->Render($matches["vars"]["attr"]);
			break;

			case "clickpopup":
				return $this->Render($matches["vars"]["attr"] , true);
			break;
		}
		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function SqlBaseCond() {
		global $_SESS , $base;


		if (is_array($_SESS["minibase"]["raw"])) {
			$cond = " AND popup_status in (1,2) ";
		} else {
			$cond = " AND popup_status = 1 ";
		}


		//device detection
		if ($base->isTablet) {
				$cond .= " AND find_in_set(2,popup_device) ";
		} elseif ($base->isMobile) {
				//phone
				$cond .= " AND find_in_set(3,popup_device) ";
			} else {
				//desktop
				$cond .= " AND find_in_set(1,popup_device) ";
			}
	

		//permission detection
		if (is_array($_SESS["client"])) {

			if (is_array($_SESS["client"]["groups"])) {
				foreach ($_SESS["client"]["groups"] as $k => $v) {
					$tmp[] = " find_in_set({$v} , popup_perm_groups) ";
				}
				
				$cond .= " AND ( popup_perm in (0,1) OR  (popup_perm = 3 AND (popup_perm_groups='' OR ( " . implode(" OR "  , $tmp ) . " )))) ";
			} else {
				$cond .= " AND popup_perm in (0,1,3) ";
			}
			
		} else {
			$cond .= " AND popup_perm in (0,1,2) ";
		}
		
		return $cond;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Render($popup , $force = false) {
		global $base , $_SESS;

		if (!is_array($popup) ) {

			$cond = $this->SQLBaseCond();

			$popup = $this->db->QFetchArray(
				"SELECT * FROM 
					{$this->tables['plugin:popups']} as p WHERE
					p.popup_id = %d
					{$cond}
				",
				array($popup)
			);

		}
		



		if (!is_array($popup)) {
			return "";
		}

		$this->__init();

		if ($force == true) {
			$popup["popup_show"] = "click";
		}
		

		switch ($popup["popup_show"]) {

			case "click":
				return $this->private->templates["init"]->blockReplace("Click" , $popup);
			break;

			//onpage load
			case "1":
				return $this->private->templates["init"]->blockReplace("OnLoad" , $popup);
			break;

			//when bottom
			case "2":
				return $this->private->templates["init"]->blockReplace("OnBottom" , $popup);
			break;

			//when scroll more then
			case "3":
				$popup["popup_show_scroll"] = $popup["popup_show_scroll"] * 1;
				return $this->private->templates["init"]->blockReplace("OnScroll" , $popup);
			break;

			//after x seconds
			case "4":
				$popup["popup_show_seconds"] = $popup["popup_show_seconds"] * 1000;
				return $this->private->templates["init"]->blockReplace("OnTime" , $popup);
			break;

			//when mouse leaves site
			case "5":
				return $this->private->templates["init"]->blockReplace("OnUserLeave" , $popup);
			break;


		}
		
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxPopup() {
		global $_SESS, $_MODULES;

		if (is_array($_SESS["minibase"]["raw"])) {
			$cond = " AND popup_status in (1,2) ";
		} else {
			$cond = " AND popup_status = 1 ";
		}


		$popup = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['plugin:popups']} as p ,
				{$this->tables['plugin:popups_lang']} as l 
				
			WHERE
				p.popup_id = l.popup_id AND 
				l.lang_id = {$this->tpl_module[lang_id]} AND				
				p.popup_id = %d 
				{$cond}
			",
			array($_POST["id"])
		);

		if (!is_array($popup)) {
			return "";
		}
		


		//various checks

		if ($popup["popup_status"] == "2") {

			if (!is_array($_SESS["minibase"]["raw"])) {
				return "";
			}
			

		} else {
		
			//record status just for enabled popups
			if ($_COOKIE["p"] /*&& !$_GET["f"]*/) {

				$tmp = explode("," , $_COOKIE["p"]);

				if (in_array($popup["popup_code"] , $tmp)) {
					return "";
				}			
			}

			//check if its forced to show the popup
			if ($_GET["f"] == "true") {
			} else {
				if (is_array($_SESS["client"]) && $popup["popup_remember_in"]) {

					$period = $popup["popup_remember_for"] * 3600 * 24;

					$old = $this->db->QFetchArray("
						SELECT * FROM 
							{$this->tables['plugin:popups_users']} 
						WHERE 
							puid_user = %d AND 
							puid_popup = %d AND 
							puid_date < %d AND 
							puid_code LIKE '%s'
						",
						array(
							$_SESS["client"]["user_id"],
							$popup["popup_id"],
							(time() - $period),
							$popup["popup_code"]
						)
					);

					if (is_array($old)) {
						return "";
					}			
				}
			}
		}

		$tpl = &$this->private->templates["popup"];		

		//update popup stats
		$this->db->QueryUpdate(
			$this->tables["plugin:popups"],
			array(
				"popup_stat_show"	=> $popup["popup_stat_show"] + 1
			),
			"popup_id={$popup[popup_id]}"
		);
			

		$this->db->QueryInsert(
			$this->tables["plugin:popups_log"],
			array(
				"log_user"			=> $_SESS["client"]["user_id"],
				"log_date"			=> time(),
				"log_type"			=> $type,
				"log_url"			=> $popup["popup_id"],	
				"log_user_agent"	=> $_SERVER["HTTP_USER_AGENT"],
				"log_language"		=> $_SERVER["HTTP_ACCEPT_LANGUAGE"],
				"log_remote_addr"	=> $_SERVER["REMOTE_ADDR"],
				"log_referer"		=> $_SERVER["HTTP_REFERER"],
				"log_page"			=> $page,
			)
		);



		//popup content
		switch ($popup["popup_content_type"]) {
			default:

				$popup["link"] = $this->plugins["modules"]->BuildLink(array(
					"type"	=> $popup["popup_link_type"],
					"link"	=> $popup["popup_link_link"],
					"module"=> $popup["popup_link_module"],
					"global"=> $popup["popup_link_global"]
				));

				switch ($popup["popup_resource"]) {
					//none
					case "0":
						$resource = "";
					break;

					//image
					case "1":
						$resource = $popup["popup_image"] ? $tpl->blockReplace("ContentImage" , $popup)  :"";
					break;

					//icon
					case "2":
						$resource = $popup["popup_icon"] ? $tpl->blockReplace("ContentIcon" , $popup) : "";
					break;

					//youtube:
					case "3":
						$resource = $popup["popup_youtube"] ? $tpl->blockReplace("ContentYoutube" , $popup) : "";
					break;

					//vimeo
					case "4":
						$resource = $popup["popup_vimeo"] ? $tpl->blockReplace("ContentVimeo" , $popup) : "";
					break;
				}
				

				$content = $tpl->blockReplace(
					"Content",
					array(
						"title"		=> $popup["popup_title"] ? $tpl->blockReplace("ContentTitle" , $popup)  :"",
						"body"		=> $popup["popup_body"] ? $tpl->blockReplace("ContentBody" , $popup)  :"",
						"resource"	=> $resource,
						"button"	=> $popup["link"] ? $tpl->blockReplace("ContentButton" , $popup)  :"",
					)
				);
			break;

			case "1":
				$content = $popup["popup_html"];
			break;

		}


		//popup optional area
		switch ($popup["popup_social_type"]) {
			//social share
			case "1":
				$tmp = explode("," , $popup["popup_social"]);
				$action = $tpl->blockReplace(
					"Share",
					array(
						"popup_social"	=> 	str_replace('"' , '' , $popup["popup_social"]),
						"set_label"	=> $widget["settings"]["set_label"] ? "true" : "false",
						"set_count"	=> $widget["settings"]["set_count"] ? $widget["settings"]["set_count"] : "true",
					),
					$_MODULES["backgrounds"]->GetBg($popup["popup_action_bg"])
				);
			break;

			//raw html
			case "2":				
				$action = $tpl->blockReplace(
					"ActionRaw",
					$popup,
					$this->plugins["backgrounds"]->GetBg($popup["popup_action_bg"])
				);
			break;

			//text w/ button
			case "3":

				$popup["link2"] = $this->plugins["modules"]->BuildLink(array(
					"type"	=> $popup["popup_link2_type"],
					"link"	=> $popup["popup_link2_link"],
					"module"=> $popup["popup_link2_module"],
					"global"=> $popup["popup_link2_global"]
				));

				$action = $tpl->blockReplace(
					"ActionText",
					array(
						"title"	=> $popup["popup_title"] ? $tpl->blockReplace("ActionTitle" , $popup)  :"",
						"body"	=> $popup["popup_body"] ? $tpl->blockReplace("ActionBody" , $popup)  :"",
						"image"	=> $popup["popup_image"] ? $tpl->blockReplace("ActionImage" , $popup)  :"",
						"button"=> $popup["link2"] ? $tpl->blockReplace("ActionButton" , $popup)  :"",
					),
					$_MODULES["backgrounds"]->GetBg($popup["popup_action_bg"])
				);
			break;
		}
		
		if ($popup["popup_type"] >= 7) {
			$action = "";
		}


		return $tpl->blockReplace(
			$popup["popup-type"] < 7 ? "Main" : "Growl" ,
			$popup,
			array(
				"main"			=> $tpl->blockReplace(
					"MainBox",
					array(
						"content"		=> $content,
					),
					$_MODULES["backgrounds"]->GetBg($popup["popup_content_bg"])					
				),
				
				"action"		=> $action,
				"position"		=> $this->position[$popup["popup_type"]],
			),
			array(
				"align"			=> $this->align[$popup["popup_content_align"]],
				"bg:scheme"		=> "nc",
			),			
			$popup,
			$vars
		);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxClose() {
		global $_SESS;


		$popup = $this->db->QFetchArray(
			"SELECT * FROM 
				{$this->tables['plugin:popups']} as p WHERE
				p.popup_code LIKE '%s'
			",
			array($_POST["id"])
		);


		if (!is_array($popup)) {
			return "";
		}

		//set in cookie;
		$tmp = $_COOKIE["p"];

		if ($tmp != "") {
			$tmp = explode("," , $tmp);
		}
		
		$tmp[] = $_POST["id"];

		$period = $popup["popup_remember_for"] * 3600 * 24;

		setcookie("p", implode("," , $tmp) , time()+$period , "/");

		if ($_SESS["client"] && $popup["popup_remember_in"]) {

			if (!is_array($this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:popups_users']} WHERE puid_user={$_SESS[client][user_id]} AND puid_popup={$popup[popup_id]} AND puid_date <" . (time() - $period)))) {

				$this->db->QueryInsert(
					$this->tables['plugin:popups_users'],
					array(
						"puid_user"		=> $_SESS["client"]["user_id"],
						"puid_popup"	=> $popup["popup_id"],
						"puid_code"		=> $popup["popup_code"],
						"puid_date"		=> time(),
					)
				);
			}
		}
		
	}
	
	
}

?>