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

// dependencies

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

	function __construct() {
		//$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",
		);

		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 LIKE '%s'" , array($_POST["email"])))) {

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

			$this->db->QueryUpdate(
				$this->tables['plugin:newsletters_subscribers'],
				array(
					"item_status"
				),
				$this->db->Statement("item_email LIKE '%s'" , array($_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 , $_CONF;

		$this->__init();


		$response = CFormError::newInstance()
			->SetErrorStyle($this->tpl_module["settings"]["set_form_validate"])
			->SetSuccessStyle($this->tpl_module["settings"]["set_form_success"])
			->SetSuccessRedirect($this->plugins["modules"]->BuildLink(array(
					"type"	=> $this->tpl_module["settings"]["set_form_link_type"],
					"link"	=> $this->tpl_module["settings"]["set_form_link_link"],
					"module"=> $this->tpl_module["settings"]["set_form_link_module"],
					"global"=> $this->tpl_module["settings"]["set_form_link_global"]
			)))
			->SetPopupBtn($this->tpl_module["settings"]["lang_popup_close"])
			->SetPopupBg($this->tpl_module["settings"]["set_form_popup_bg"])
			->SetScript("newsletterResponse(form)");


		if (!Validate::Email($_POST["email"])) {
			$response->AddField("email" , $this->tpl_module["settings"]["lang_error_email"]);
		} else {
			if (!$this->plugins["antispam"]->ValidateEmail($this->tpl_module, $_POST["email"])) {
				$response->AddField("email" , $this->plugins["antispam"]->EmailError());
			}
		}


		if (!$this->plugins["antispam"]->ValidateClient($this->tpl_module)) {
			$response->AddField("__global" , $this->plugins["antispam"]->ClientError());
		}

		if ($response->HasErrors()) {
			return $response->GetJson();
		}


		if ($_POST["w"]) {
			$widget = $this->plugins["widgets"]->GetWidget($_POST["w"]);
			$list = $widget["settings"]["set_group"];
		} elseif ($_POST["l"] ) {
			$list = $_POST["l"] ;
		} else {
			$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)) {
			$response->AddField("email" , $this->tpl_module["settings"]["lang_error_exists"]);
		}

		if ($response->HasErrors()) {
			return $response->GetJson();
		}

		if (!$this->plugins["antispam"]->ValidateCaptcha($this->tpl_module["settings"]["set_post_capcha"] , "newsletters")) {
			$response->AddField("image_code" , $this->plugins["antispam"]->CaptchaError());
		}

		if ($response->HasErrors()) {
			return $response->GetJson();
		}

		$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"]),
		);

		$user["confirm_link"] = $_CONF["url"] . "/newsletters/confirm/" . $user["key_code"];

		$result = $this->RecordUser($user);

		if ($result !== true) {
			$response->AddField("email" , $result);
		}		

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

		return $response->SetReset()
			->SetSuccess($this->tpl_module["settings"]["lang_success"])
			->SetScript("newsletterReset(form)")
			->GetJson();
	}
	

	/**
	* 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)) {
					return $this->tpl_module["settings"]["lang_error_exists"];					
				}
				

				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"]),

							"log_ip"			=> $_SERVER["REMOTE_ADDR"],
							"log_domain"		=> $_SERVER["REMOTE_HOST"],
							"log_agent"			=> $_SERVER["HTTP_USER_AGENT"],
							"log_referer"		=> $_COOKIE["uref"],

						)
					);

					//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
		return true;

	}	
	
	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}" : "")
		);
		

	}



	/**
	* 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 '%s' AND 
				item_confirm=2
			",
			array(
				$_GET["key"]
			)
		);

		$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"]
		);
		
	}
	



}
