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

// dependencies

/**
* description
*
* @library	
* @author	
* @since	
*/
class CNewsletters extends CPlugin{
	
	var $tplvars; 

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

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


		parent::DoEvents();

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

			$this->__init();

			switch ($_GET["sub"]) {

				case "ajax.subscribe":
					return $this->AjaxSubscribe();
				break;

				case "action.confirm":
					return $this->ConfirmSubscription();
				break;

			}
			
		}

	}

	function __init() {
		global $_CONF;

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


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

		$templates = array(
			"success"	=> "success.htm",
			"invalid"	=> "invalid.htm",
			"main"					=> "main.htm",
			"aker"					=> "aker.htm",



			"widget.subscribe"		=> "widget.subscribe.htm",
		);

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

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


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Unsubscribe() {

		$this->__init();

		if (is_array($uid = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:newsletters_subscribers']} WHERE item_email='{$_POST[email]}'"))) {

			echo $this->private->templates["success"]->blockReplace(
				"Main" , 
				$uid
			);

			$this->db->Query(
				"UPDATE {$this->tables['plugin:newsletters_subscribers']} SET item_status=2 WHERE item_email=\"{$_POST[email]}\" "
			);

			//record an event
			$this->db->QueryInsert(
				$this->tables['plugin:newsletters_events'],
				array(
					"event_user"	=> $uid["item_id"],
					"event_date"	=> time(),
					"event_type"	=> "4",
					"event_list"	=> $uid["item_list"],
				)		
			);


			die();

		} else {

			echo $this->private->templates["invalid"]->blockReplace(
				"Main" , 
				array()
			);

			die();

		}		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Landing() {
		$this->__init();
		
		echo $this->private->templates["main"]->blockREplace(
			"Main",
			array(
				"email"	=> $_GET["email"]
			)
		);
	}



	function Main() {
		global $base , $_LANG_DATA;

		$this->__init();

		//load the module

		if ($this->tpl_module["module_unique_enabled"]) {
			return CTemplateStatic::Replace(
				$this->private->templates["main"]->blockReplace(
					"Main" ,
					$this->tpl_module["settings"]
				),
				$_LANG_DATA
			);
		} else {
			return "";
		}
	}



	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function AjaxSubscribe() {
		global $_LANG_DATA;

		$this->__init();


		if (!Validate::Email($_POST["email"])) {
			return $this->module->plugins["common"]->ErrorMsg(				
				$this->tpl_module["settings"]["lang_error_email"]
			);
		}

		if ($_POST["w"]) {
			$widget = $this->plugins["widgets"]->GetWidget($_POST["w"]);
			$list = $widget["settings"]["set_group"];
		} 
		
		if (!$list) {
			$list = $this->tpl_module["settings"]["set_group"];
		}

		//check if user exists
		$user = $this->db->QFetchArray("
			SELECT * FROM 
				{$this->tables['plugin:newsletters_subscribers']} 
			WHERE 
				item_email='%s' AND 
				item_list=%d",
			array(
				$_POST["email"],
				$list
			)
		);

		if (is_array($user)) {
			return $this->module->plugins["common"]->ErrorMsg(
				$this->tpl_module["settings"]["lang_error_exists"]
			);
		}

		$user = array(
			"first_name"	=> $_POST["first_name"],
			"last_name"		=> $_POST["last_name"],
			"name"			=> $_POST["name"],
			"email"			=> $_POST["email"],
			"list"			=> $list,
			"date"			=> time(),
			"key_code"		=> md5($_POST["email"]),

		);

		$this->RecordUser($user);



		$email = $this->module->plugins["mail"]->SendMail(
			$this->module->plugins["mail"]->GetMail(
				$this->tpl_module["settings"]["set_mail_subscribe"],
				$user
			)
		);

		return $this->module->plugins["common"]->SuccessMsg(
			$this->tpl_module["settings"]["lang_success"]
		);
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function RecordUser($user) {
		
		$lists = $user["list"];

		if (!is_array($lists)) {
			$lists = explode("," , $lists);
		}	

		if (is_array($lists)) {
			foreach ($lists as $key => $list) {

				$data = $this->db->QFetchArray("
					SELECT * FROM 
						{$this->tables['plugin:newsletters_subscribers']} 
					WHERE 
						item_email=\"{$user[email]}\" AND 
						item_list={$list}
					"
				);

				if (!is_array($data)) {

					$this->db->QueryInsert(
						$this->tables["plugin:newsletters_subscribers"],
						array(
							"item_name"			=> $user["name"],
							"item_first_name"	=> $user["first_name"],
							"item_last_name"	=> $user["last_name"],
							"item_email"		=> $user["email"],
							"item_list"			=> $list,
							"item_date"			=> time(),
							"item_status"		=> "1",
							"item_confirm"		=> "2",
							"item_key"			=> md5($user["email"]),
						)
					);

					//ceck if there exists any confirmed email and then confirm it too 
					if ($this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:newsletters_subscribers']} WHERE item_email LIKE '{$user[email]}' AND item_status=2")) {

						$this->db->QueryUpdate(
							$this->tables['plugin:newsletters_subscribers'],
							array(
								"item_confirm"				=> "1",
								"item_stats_confirm_date"	=>  time(),
								"item_stats_confirm_ip"		=> $_SERVER["REMOTE_ADDR"],
							),

							"
								item_email LIKE '{$user[email]}' AND 
								item_confirm=2,
							"
						);
						
					}
					

					$this->db->QueryUpdate(
						$this->tables['plugin:newsletters_groups'],
						array(
							"group_contacts"	=> $this->db->RowCount(
								$this->tables['plugin:newsletters_subscribers'],
								"WHERE item_list={$list}"
							)
						),
						"group_id={$list}"
					);

				} elseif ($user["item_status"] == "2") {
					//mark it again as subscribed, without touching the 
					$this->db->QueryUpdate(
						$this->tables["plugin:newsletters_subscribers"],
						array(
							"item_status" => "1",
						),
						"item_id={$user[item_id]}"
					);
				}
				
			}
			
		}
		



		//update the rowcount

	}	
	
	function RemoveUser($email , $group = "") {

		//dont delete the user just mark it as unsubscribed

		$this->db->QueryUpdate(
			$this->tables['plugin:newsletters_subscribers'],
			array(
				"item_status"	=> "2"
			),	
			"item_email like '{$email}' " . ($group ? "AND item_list={$group}" : "")
		);
		

	}
	
	
	function Widget($widget) {

		$this->__init();

		switch ($widget["widget_type"]) {
			case "1":
				return $this->widgetSubscribe($widget);
			break;

		}
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function widgetSubscribe($widget) {

		$this->__init();

		return $this->private->templates["widget.subscribe"]->BlockReplace(
				"Main" , 
				array(
					"title"	=> $widget["widget_name"],
					"w"		=> $widget["widget_id"],

					"script"=> $this->plugins["modules"]->ScriptLink("newsletters.ajax.subscribe.php")
				),
				$widget["mod_settings"],
				$widget["settings"]
		);
	}
	



	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ConfirmSubscription() {

		$user = $this->db->QFetchArray(
			"
				SELECT * FROM 
					{$this->tables['plugin:newsletters_subscribers']}
				WHERE
					item_key LIKE '%s' AND 
					item_confirm = 2
			",
			array(
				$_GET["key"]
			)
		);

		if (!is_array($user)) {
			$this->module->plugins["modules"]->RedirectToModule(
				$this->tpl_module["settings"]["set_page_invalid"]
			);
		}

		//update all unconfirmed addresses
		$this->db->QueryUpdate(
			$this->tables['plugin:newsletters_subscribers'],
			array(
				"item_confirm"				=> "1",
				"item_stats_confirm_date"	=>  time(),
				"item_stats_confirm_ip"		=> $_SERVER["REMOTE_ADDR"],
			),

			"
				item_key LIKE '{$_GET[key]}' AND 
				item_confirm=2
			"
		);

		$email = $this->module->plugins["mail"]->SendMail(
			$this->module->plugins["mail"]->GetMail(
				$this->tpl_module["settings"]["set_mail_subscribed"],
				array(
					"first_name"	=> $user["item_first_name"],
					"last_name"		=> $user["item_last_name"],
					"name"			=> $user["item_name"],
					"email"			=> $user["item_email"],
				)
			)
		);		

				

		//get the list for this user

		if ($user["item_list"]) {
			$list_data = $this->db->QFetchRowArray("SELECT * FROM {$this->tables['plugin:newsletters_groups']} WHERE group_id in ({$user[item_list]}) AND group_mc_status=1 AND group_mc_apikey != '' AND group_mc_listid != ''");
		}

		if (is_array($list_data)) {

			foreach ($list_data as $key => $list) {
				$test = MailChimp::newInstance()
					->SetApiKey($list["group_mc_apikey"])
					->Subscribe(
						$list["group_mc_listid"], 
						array(
							"email"			=> $user["item_email"],						
							"first_name"	=> $user["item_first_name"],						
							"last_name"		=> $user["item_last_name"],						
						)
					);
			}
			
		}

		//redirect to confirmed page
		$this->module->plugins["modules"]->RedirectToModule(
			$this->tpl_module["settings"]["set_page_confirmed"]
		);
		
	}
	



}

?>