<?php

/**
* 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") {
			$sub = $_GET["sub"];
			$action = $_GET["action"];

			$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("newsletters");
			$this->tpl_module["mod_name"] = "Subscribers";
							
			switch ($sub) {

				case "landing":
					$sub = "contacts/subscribers";

				case "contacts/subscribers":
				case "contacts/lists":
					

					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$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;
	
			}
		}
	}


	/**
	* 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_config={$_POST[confirm]} ";
		}
		
		if ($_POST["confirm"]) {
			$cond[] = " item_config={$_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;
		}

		External::Load("phpexcel");

		$objPHPExcel = new PHPExcel();

		// Set document properties
		$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
									 ->setLastModifiedBy("Maarten Balliauw")
									 ->setTitle("Office 2007 XLSX Test Document")
									 ->setSubject("Office 2007 XLSX Test Document")
									 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
									 ->setKeywords("office 2007 openxml php")
									 ->setCategory("Test result file");


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

	
	function adminGetWidgets($module) {


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


		$widgets = array(
			array(
				"type"				=> "1",
				"name"				=> "Subscribe Form",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),
		);

		return $widgets;

	}


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

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

		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
					),
				);
			}
		}
		
	}
	
}

?>