<?php

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

	function __construct() {
		$this->name = "newsletters";
	}

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


		if ($_GET["mod"] ==  $this->name) {

			$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule($this->name);
			parent::DoEvents();

			$sub = $_GET["sub"];
			$action = $_GET["action"];

			switch ($sub) {

				case "landing":
					$sub = "contacts/subscribers";
				case "contacts/subscribers":
					$this->plugins["dashboard"]->UpdateModuleAction($this->tpl_module["module_id"]);

				case "contacts/lists":				
					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$data->setAclMod($this->tpl_module);
					$this->PrepareFields($data->forms["forms"]);

					switch ($sub) {
						case "contacts/lists":
							$data->functions = array( 
									"ondelete" => array(&$this , "ListDelete"),
							);					
						break;


						case "contacts/subscribers":
							$data->functions = array( 
									"onstore" => array(&$this , "SubscriberStore"),
									"ondelete" => array(&$this , "SubscriberDelete"),
							);					
						break;
					}
					
					return $data->DoEvents();
				break;



				case "contacts/import":
					if (!$_GET["action"]) {
						$_GET["action"] = "edit";
					}

				case "contacts/import.process":

					
					$data = new CFormSettings($this->forms_path  . $sub . ".xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables);
					$this->PrepareDashboard($data->form);

					if ($data->Done()) {

						switch ($sub) {
							case "contacts/import":


								if (!$_FILES["file"]["error"]) {
									move_uploaded_file(
										$_FILES["file"]["tmp_name"] , 
										"../upload/import/" . $_FILES["file"]["name"]
									);
								}

								if ($_POST["list"]) {
									//generate the 
									SaveFileContents(					
										"../upload/import/" . "import.subscribers.list",
										$_POST["list"]
									);
								}
								


								//generate the 
								SaveFileContents(					
									"../upload/import/" . "import.subscribers.queue",
									"../upload/import/" . $_FILES["file"]["name"] . "\n" .
									serialize($_POST)
								);

								$_SESS["admin"]["action_import_newsletters"] = $_POST;

								urlredirect("index.php?mod=newsletters&sub={$sub}.process");
								//debug($_POST,1);
							break;
						}
						

					}
					
					return $data->Show($_SESS["admin"]["action_import_newsletters"]);
				break;

				case "contacts/export":
					if (!$_GET["action"]) {
						$_GET["action"] = "edit";
					}
					
					$data = new CFormSettings($this->forms_path  . $sub . ".xml" ,$_CONF["forms"]["admintemplate"] , $this->db,$this->tables);
					$this->PrepareDashboard($data->form);

					if ($data->Done()) {

						switch ($sub) {
							case "contacts/export":
								return $this->ContactsExport();
							break;
						}
					}

					return $data->Show();
				break;


				case "contacts/import.queue":
					return $this->ContactsImport();
				break;

				case "action.resend-activation":
					$this->ResendActivation();
				break;

	
			}
		}
	}


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

		//load items
		set_time_limit(0);
		$limit = 10000;


		if (is_array($_POST["groups"])) {

			foreach ($_POST["groups"] as $key => $val) {
				$cond_gr[] = " find_in_set({$val} , item_list) ";
			}

			$cond[] = "(" . implode(" OR " , $cond_gr) . ") ";			
		}

		if ($_POST["confirm"]) {
			$cond[] = " item_confirm={$_POST[confirm]} ";
		}
		
		
		if ($_POST["status"]) {
			$cond[] = " item_status={$_POST[status]} ";
		}

		$items = $this->db->QFetchRowArray(
			"
				SELECT * FROM {$this->tables['plugin:newsletters_subscribers']} 			
			" . (is_array($cond) ? " WHERE "  . implode(" AND " , $cond) : "") .
			" LIMIT {$limit} "
		);


	
		if (is_array($items)) {
			foreach ($items as $key => $val) {
				$_items[$val["item_email"]] = $val;
			}			

			$items = $_items;
		}


		$objPHPExcel = new PHPExcel();

		// Set document properties
		$objPHPExcel->getProperties()->setCreator("DevSaver CMS")
									 ->setLastModifiedBy("DevSaver CMS")
									 ->setTitle("Subscribers")
									 ->setSubject("Subscribers")
									 ->setDescription("Exported subscribers from your site.")
									 ->setKeywords("")
									 ->setCategory("");


		// Add some data
		$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue('A1', 'E-Mail')
					->setCellValue('B1', 'First Name')
					->setCellValue('C1', 'Last Name');

		if (is_array($items)) {

			$cnt = 1;
			foreach ($items as $key => $val) {

				$cnt ++;

				$objPHPExcel->setActiveSheetIndex(0)
					->setCellValue("A{$cnt}", $val["item_email"])
					->setCellValue("B{$cnt}", $val["item_first_name"])
					->setCellValue("C{$cnt}", $val["item_last_name"]);
			}			
		}

		$filename = "subscribers";

		switch ($_POST["format"]) {

			//csv
			case "1":
				header('Content-Type: text/csv');
				header("Content-Disposition: attachment;filename=\"{$filename}.csv\"");
				header('Cache-Control: max-age=0');
				// If you're serving to IE 9, then the following may be needed
				header('Cache-Control: max-age=1');

				$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
			break;

			//xls
			case "2":
				header('Content-Type: application/vnd.ms-excel');
				header("Content-Disposition: attachment;filename=\"{$filename}.xls\"");
				header('Cache-Control: max-age=0');
				// If you're serving to IE 9, then the following may be needed
				header('Cache-Control: max-age=1');

				$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

			break;

			//xlsx
			case "3":
				header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
				header("Content-Disposition: attachment;filename=\"{$filename}.xlsx\"");
				header('Cache-Control: max-age=0');
				$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
			break;

			case "4":
				header('Content-Type: application/pdf');
				PHPExcel_Settings::setPdfRenderer( "tcPDF" , "3rdparty/tcpdf/");
				$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
			break;



		}		

		$objWriter->save('php://output');
		exit;

	}

	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ContactsImport() {
		global $_CONF;
		
		$importer = new CFormsQueue(
			$_CONF["upload"] . "import/import.subscribers.queue",
			"index.php?mod=newsletters&sub=contacts/import"			
		);

		$importer->AddFunction("data"	,	array(&$this , "ContactsReadData"));
		$importer->AddFunction("batch"	,	array(&$this , "ContactsReadBatch"));
		$importer->AddFunction("store"	,	array(&$this , "ContactsImportStoreUser"));
		$importer->AddFunction("finish"	,	array(&$this , "ContactsCleanup"));

		return $importer->Run();
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ContactsImportStoreUser($config , $data) {
		global $_SESS;

		$data["E-Mail"] = trim($data["E-Mail"]);

		if (!Validate::Email($data["E-Mail"])) {
			return 3;
		}
		

		$user = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:newsletters_subscribers']} WHERE item_email LIKE '{$data['E-Mail']}'");

		if (is_array($user)) {
			$groups = explode("," , $user["item_list"]);

			if (!in_array($_SESS["admin"]["action_import_newsletters"]["groups"] , $groups)) {
				$groups[] = $config["vars"]["groups"];

				$this->db->QueryUpdate(
					$this->tables["plugin:newsletters_subscribers"],
					array(
						"item_list"	=> implode("," , $groups),
					),
					"item_id={$user[item_id]}"
				);

				return "2";
			} else {
				return "4";
			}
							
		} else {
			$this->db->QueryInsert(
				$this->tables["plugin:newsletters_subscribers"],
				array(
					"item_email"		=> $data["E-Mail"],
					"item_key"			=> md5($data["E-Mail"]),
					"item_first_name"	=> $data["First Name"],
					"item_last_name"	=> $data["Last Name"],
					"item_list"			=> $_SESS["admin"]["action_import_newsletters"]["groups"],

					"item_confirm"		=> "1",
					"item_status"		=> "1",
					"item_date"			=> time(),
					"item_stats_date"	=> time(),


				)
			);

			return "1";
		}
		
	}



	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ContactsReadData($config) {
		global $_CONF;

		$array_data = CFile::LoadArray($config["file"] , true);

		if (file_exists($_CONF["upload"] . "import/import.subscribers.list")) {

			$emails = file($_CONF["upload"] . "import/import.subscribers.list");

			if (is_array($emails) && count($emails)) {
				foreach ($emails as $key => $val) {
					$array_data[] = array("E-Mail" => $val);
				}			
			}			
		}


		$files = array_chunk ( 
			$array_data , 
			100
		);

		$cnt = 1;
		foreach ($files as $key => $val) {
			savefilecontents(
				$_CONF["upload"] . "import/subscribers_batch_{$cnt}.serial",
				serialize($val)
			);

			$cnt++;
		}

		$config["total"] = count($array_data);
		$config["batches"] = $cnt-1;
				
		return $config;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ContactsReadBatch($config) {
		global $_CONF;
		return CFile::LoadArray($_CONF["upload"] . "import/subscribers_batch_" . (int) ($config["current"]+1)  .".serial" , true);
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ContactsCleanup($config) {
		global $_CONF , $_SESS;

		if ($config["batches"]) {
			for ($i = 1; $i <= $config["batches"] ; $i++ ) {
				CFile::Remove($_CONF["upload"] . "import/subscribers_batch_{$i}.serial");
			}			
		}

		if ($config["file"] && is_file($config["file"])) {
			CFile::Remove($config["file"]);
		}


		if ($_SESS["admin"]["action_import_newsletters"]["groups"]) {
			$this->ListUpdateCount($_SESS["admin"]["action_import_newsletters"]["groups"]);
		}	

		unset($_SESS["admin"]["action_import_newsletters"]);


		CFile::Remove($_CONF["upload"] . "import/import.subscribers.queue");
		CFile::Remove($_CONF["upload"] . "import/import.subscribers.list");
		
		return true;
	}
		




	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function SubscriberStore($record) {

		if ($record["item_id"]) {
			$this->db->QueryUpdate(
				$this->tables["plugin:newsletters_subscribers"],
				array(
					"item_key"	=> md5($record["item_email"])
				),
				"item_id={$record[item_id]} AND item_key = '' "
			);

			if ($record["item_list"]) {
				$this->ListUpdateCount($record["item_list"]);
			}
			
		}
		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function SubscriberDelete($record) {
	}



	//// TO BE DONE LATER 



	function ListDelete($record) {

		if (!is_array($record)) {
			return false;
		}

		//delete all users
		$this->db->Query(
			"DELETE FROM {$this->tables['plugin:newsletters_subscribers']} WHERE item_list={$record[group_id]}"
		);
	
	}

	function DeleteSubscriber($record) {
		if (!is_array($record)) {
			return false;
		}


	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ListUpdateCount($lists) {

		if (!$lists) {
			return "";
		}

		$lists = explode("," , $lists);

		foreach ($lists as $key => $val) {

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

	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DashboardWidgets($mod_id = null) {
		global $base , $_CONF;

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

		if (!$module["module_status"]) {
			return "";
		}

		if (!$base->acl->checkModRule($module , "subscribers.list")) {
			return "";
		}


		if (is_array($module)) {
			$_CONF["forms"]["adminpath"] = _MODPATH . "newsletters/forms/";
			$latest = new CSQLAdmin("dashboard/latest", $this->__parent_templates,$this->db,$this->tables,$extra);
			$content = $latest->DoEvents();
			//if (!(stristr($content , "No available records.") && !$_GET["showempty"])) {

				return array(
					array(
						"width"	=> "6",
						"type"	=> "widget",
						"pos"	=> "1",
						"body"	=> $content
					),
				);
			//}
		}
		
	}

	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function DashboardNumbers($mod_id=null) {
		global $_SESS , $base;
		$module = $this->module->plugins["modules"]->LoadDefaultModule("newsletters");

		if (!$module["module_status"]) {
			return "";
		}

		if (!$base->acl->checkModRule($module , "subscribers.list")) {
			return "";
		}

		

		if (is_array($module)) {
			return array(
				array(
					"skin"		=> "Orange",
					"icon"		=> "user-check",
					"link"		=> "index.php?mod=newsletters&sub=landing",
					"count"		=> $this->db->RowCount($this->tables['plugin:newsletters_subscribers'], "WHERE item_confirm=1 AND item_date > " . $this->plugins["dashboard"]->GetAccessDate($module["module_id"])),
					"title"		=> "New Subscribers",
					"subtitle"	=> $module["module_name"],
				),
			);

		}
	}
	


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

		if (is_array($_POST["item_id"]) && count($_POST["item_id"])) {

			$email = $this->tpl_module["settings"]["set_mail_resendconfirm"] ? $this->tpl_module["settings"]["set_mail_resendconfirm"]  : $this->tpl_module["settings"]["set_mail_subscribe"] ;

			foreach ($_POST["item_id"] as $key => $val) {

				$user = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:newsletters_subscribers']} WHERE item_id=%d" , array($val));

				//update the 
				$user["item_confirm_resend_date"] = time();

				$this->db->QueryUpdate(
					$this->tables['plugin:newsletters_subscribers'],
					array(
						"item_confirm_resend_date"	=> $user["item_confirm_resend_date"],
					),
					"item_id={$user[item_id]}"
				);

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

			}			
		}

		die("ok");
		
	}


	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function mailTemplateVars($module , $operation = "list" , $template = "") {

		switch ($operation) {
			case "list":
				//return the list of possible templates for this 
				return array(
					"confirm"		=> "Confirm Email",
					"confirmed"		=> "Confirmed Email",
				);
			break;

			case "vars":
				return $this->MailTemplateVarsList($template);
			break;
		}		
	}


	
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function mailTemplateVarsList($template) {
		
		$misc = array(
			"set"		=> "Client",
			"fields"	=> array(
				"email"		=> "Email Address",
			),
		);

		if ($template == "confirm") {
			$misc["fields"]["confirm_link"]	= "Confirmation Link";
		}

		$sets[] = $misc;

		return $sets;
	}


}

?>