<?php

class CUsers extends CPlugin{
	
	var $tplvars; 

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

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

		parent::DoEvents();

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

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

			//read the module
			$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("users");
		

			switch ($sub) {

				case "autocomplete":
					return $this->JsonAutocomplete();
				break;


				case "landing":
					$sub="users";
				case "users":					
				case "groups":					

				case "memberships.fields":					
				case "memberships.periods":					
				case "logs":					
					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$this->PrepareFields($data->forms["forms"], $sub);
					if ($sub == "users") {
						$data->functions = array( 
								"onstore_prepare" => array(&$this , "StoreUser"),
								"onstore" => array(&$this , "StoreUser"),
						);					
					}				
					return $data->DoEvents();
				break;

				case "memberships":					
					$data = new CSQLAdmin($sub, $this->__parent_templates,$this->db,$this->tables,$extra);
					$this->PrepareMembershipFields($data->forms["forms"]);
					$this->PrepareFields($data->forms["forms"], $sub);

					$data->functions = array( 
							"onstore" => array(&$this , "StoreMembership"),
					);					

					return $data->DoEvents();
				break;


				case "texts":
						$_GET["module_id"] = $this->tpl_module["module_id"];
						return $this->__adminTexts();
				break;


				case "settings":
					$this->tpl_module = $this->module->plugins["modules"]->LoadDefaultModule("users");
					urlredirect("index.php?mod=modules&sub=default&action=details&module_id={$this->tpl_module['module_id']}&t=u");
				break;
			}
		}
	}

	
	function StoreUser($record) {
		//check if is a new user
		if (!$record["user_id"]) {
			$_POST["user_date"]				= time();
			$_POST["user_email_original"]	= $_POST["user_email"];
			$_POST["user_key_code"]			= md5($_POST["user_email"] . time());
			$_POST["user_key_date"]			= time();
			$_POST["user_password_plain"]	= $_POST["user_pass"];
			$_POST["user_password"]			= md5($_POST["user_pass"]);

			//update the record
			$record = $_POST;

			switch ($_POST["user_status"]) {
				case "1":	$email = "set_mail_confirm";	break;
				case "2":	$email = "set_mail_welcome";	break;
				case "3":	$email = "set_mail_pending";	break;
				case "4":	$email = "set_mail_suspended"; 	break;
			}

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

		}
		
		//update password
		if ($record["user_id"] && $record["user_pass"]) {

			$this->db->QueryUpdate(
				$this->tables["plugin:users"],
				array(
					"user_password" => md5($record["user_pass"]),
				),
				"user_id='{$record[user_id]}'"
			);
		}

		//notification emails if the status was changed
		if ($record["user_id"] && $_POST["send_mail"]) {


			switch ($_POST["user_status"]) {
				case "1":	$email = "set_mail_confirm";	break;
				case "2":	$email = "set_mail_welcome";	break;
				case "3":	$email = "set_mail_pending";	break;
				case "4":	$email = "set_mail_suspended"; 	break;
			}

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

			//hell knows why this happends
			$_POST["send_mail"] = 0;

		}
		

	}


	function adminGetWidgets($module) {

		//$this->tpl_module = $this->module->plugins["modules"]->getModuleInfo($_GET["module_id"]);

		$widgets = array(
			array(
				"type"				=> "1",
				"name"				=> "Quick Login",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),

			array(
				"type"				=> "3",
				"name"				=> "Register",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),

			array(
				"type"				=> "4",
				"name"				=> "Recover Password",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),

			array(
				"type"				=> "2",
				"name"				=> "User Menu",
				"module_name"		=> $module["module_name"],
				"module"			=> $module["module_id"],
				"module_type"		=> "2",
			),

		);
		return $widgets;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function ImportCleanup($config) {


		if ($config["batches"]) {
			for ($i = 1; $i <= $config["batches"] ; $i++ ) {

				if (file_exists("../upload/import/users_batch_{$i}.queue")) {
					unlink("../upload/import/users_batch_{$i}.queue");				
				}				
			}			
		}

		@unlink($config["file"]);
		@unlink("../upload/import/import.users.queue");
		
		return true;
	}
		

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

		global $_USER;

		if ($_SERVER["REQUEST_METHOD"] == "POST") {

			if ($_POST["default"]) {
				$data= $this->db->QFetchRowArray("SELECT * FROM {$this->tables['plugin:users']} WHERE user_id IN ({$_POST['default']}) ");

				if (is_array($data)) {
					foreach ($data as $key => $val) {
						$_data[$val["user_id"]] = $val["user_first_name"] . " " . $val["user_last_name"] . " ( {$val[user_login]} ) "  ;
					}
					
				}
				
			}
			

			return json_encode($_data);
		}
		

		if (!$_USER) {
			return json_encode(array(				
				"status"	=> "empty" , 
				"message"	=> "Session expired, please login again !"
			));
		}

		$keyword = $_GET["mt_filter"];

		if ($keyword) {
			$tmp = explode(" " , $keyword);

			if (count($tmp)) {
				foreach ($tmp as $key => $val) {
					$cond[] = " ( user_first_name LIKE '%{$val}%' OR user_last_name LIKE '%{$val}%'  OR user_login LIKE '%{$val}%'  OR user_email LIKE '%{$val}%') ";
				}				
			}			
		}

		if (is_array($cond)) {
			$cond = " WHERE " . implode(" AND " , $cond);
		}			

		$items = $this->db->QFetchRowArray(
			"SELECT * " . 
			"FROM 
				{$this->tables['plugin:users']}

			{$cond}
			ORDER BY  user_last_name 
			LIMIT 5"
		);

		if (is_array($items)) {
			foreach ($items as $key => $val) {
				$_data[] = array(
					"id"	=> $val["user_id"],
					"name"	=> $val["user_first_name"] . " " . $val["user_last_name"] . " ( {$val[user_login]} )",
					"description"	=> $val["user_email"],
					"picture_path"	=> "../upload/users/" . ($val["user_image"] ? "{$val[user_id]}.jpg" : "user.png"),
				);
			}
			
			return json_encode(array(
				"status"	=> "ok" , 
				"results"	=>  $_data
			));
		}
		
		return json_encode(array(
				"status"	=> "empty" , 
				"message"	=> "No results available"
		));


	}
	

	
	function AddUser($data) {

		if (!$data["login"]) {
			return "";
		}

		if ($data["gid"]) {
			$gid = $data["gid"];
		}
		
		if ($data["group"] && !$gid) {
	
			if (is_string($data["group"]) && strstr($data["group"] , ",")) {
				$data["group"] = explode("," , $data["group"]);
			}			

			if (is_array($data["group"])) {
				foreach ($data["group"] as $key => $val) {
					$group = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:users_groups']} WHERE group_name LIKE '{$val}'");

					if (!is_array($group)) {
						$gid[] = $this->db->QueryInsert(
							$this->tables['plugin:users_groups'],
							array(
								"group_name"	=> $val,
							)
						);
					} else {
						$gid[] = $group["group_id"];
					}					

				}				

			} else {		
				$group = $this->db->QFetchArray("SELECT * FROM {$this->tables['plugin:users_groups']} WHERE group_name LIKE '{$data[group]}'");

				if (!is_array($group)) {
					$gid = $this->db->QueryInsert(
						$this->tables['plugin:users_groups'],
						array(
							"group_name"	=> $data["group"],
						)
					);
				} else {
					$gid = $group["group_id"];
				}					
			}
		}

		//check if the contact exists

		if ($data["login"]) {
			$user = $this->db->QFetchArray(
				"SELECT * FROM {$this->tables['plugin:users']} WHERE user_login like '{$data['login']}'"
			);
		}

		if ($data["email"] && !is_array($user)) {
			$user = $this->db->QFetchArray(
				"SELECT * FROM {$this->tables['plugin:users']} WHERE user_email like '{$data['email']}'"
			);
		}
		
		

		if (!is_array($user)) {

			$id = $this->db->QueryInsert(
				$this->tables["plugin:users"],
				$user = array(
					"user_login"		=> $data["login"],
					"user_groups"		=> is_array($gid) ? implode("," , $gid) : $gid,
					"user_date"			=> time(),
					"user_key_code"		=> md5($data["email"] . time()),
					"user_key_date"		=> time(),
					"user_password"		=> md5($_POST['password']),

					"user_email"		=> $data["email"],

					"user_first_name"	=> $data["first_name"],
					"user_last_name"	=> $data["last_name"],

					"user_status"		=> $data["status"],
				)
			);


			$user["user_id"] = $id;

			return $user;
				
		} else {

			return $user;
		}			

	}

	
	function PrepareMembershipFields(&$forms){

		if ($_REQUEST["membership_id"]) {
			$membership = $this->db->QFetchArray(
				"SELECT * FROM {$this->tables['plugin:users_memberships']} as p , {$this->tables['plugin:users_memberships_lang']} as l 
				WHERE p.membership_id = l.membership_id and l.lang_id = {$this->tpl_module[lang_id]} AND p.membership_id = {$_REQUEST[membership_id]} "
			);

			$val1 = RemoveArraySlashes(unserialize(base64_decode($membership["membership_details"])));
			$val2 = RemoveArraySlashes(unserialize(base64_decode($membership["membership_pricing"])));
			$val3 = RemoveArraySlashes(unserialize(base64_decode($membership["membership_details_lang"])));

			$values = array_merge(
				(array)$val1, 
				(array)$val2, 
				(array)$val3
			);
		}
		

		$fields = $this->db->QFetchRowArray(
			"SELECT * FROM {$this->tables['plugin:users_membership_fields']} as p , {$this->tables['plugin:users_membership_fields_lang']} as l 
			WHERE p.field_id = l.field_id and l.lang_id = {$this->tpl_module[lang_id]} ORDER BY field_order ASC"
		);

		if (is_array($fields)) {
			foreach ($fields as $key => $val) {

				switch ($val["field_type"]) {
					case "1":
						$_fields["dl_" . $val["field_id"]] = array(
							"lang"		=> "true",
							"extend"	=> "true",
							"title"		=> $val["field_title"],
							"type"		=> "textbox",
							"width"		=> "100%",
							"forcevalue"=>	$values["dl_" . $val["field_id"]]
						);
					break;

					case "4":
						$_fields["dl_" . $val["field_id"]] = array(
							"lang"		=> "true",
							"extend"	=> "true",
							"title"		=> $val["field_title"],
							"type"		=> "textarea",
							"width"		=> "100%",
							"height"	=> "50px",
							"forcevalue"=>	$values["dl_" . $val["field_id"]]

						);
					break;

					case "2":
						$_fields["details_" . $val["field_id"]] = array(
							"extend"	=> "true",
							"title"		=> $val["field_title"],
							"type"		=> "checkbox",
							"checked"	=> "1",
							"label"		=> "yes",
							"forcevalue"=>	$values["details_" . $val["field_id"]]
						);
					break;

					case "3":
						$_fields["set_plan_" . $val["field_id"]] = array(
							"title"		=> $val["field_title"],
							"type"		=> "subtitle",
						);
					break;

				}

				
			}			

			$box = array(
				"title"		=> "Plan Details" ,
				"width"		=> "6",
				"fields"	=> $_fields,
			);


			$forms["details"]["fields"]["box"][] = $box;
			$forms["add"]["fields"]["box"][] = $box;
			$forms["edit"]["fields"]["box"][] = $box;
		}

		//payment terms
		$periods = $this->db->QFetchRowArray(
			"SELECT * FROM {$this->tables['plugin:users_membership_periods']} as p , {$this->tables['plugin:users_membership_periods_lang']} as l 
			WHERE p.period_id = l.period_id and l.lang_id = {$this->tpl_module[lang_id]} ORDER BY period_order ASC"
		);

		$_periods["membership_free"] = array(
			"type"			=> "checkbox",
			"checked"		=> "1",
			"label"			=> "free membership",
			"description"	=> "if checked the prices bellow will be ignored",
			"default"		=> $membership["membership_free"],
		);

		if (is_array($periods)) {
			foreach ($periods as $key => $val) {

					$_periods["set_period_" . $val["period_id"]] = array(
						"title"		=> $val["period_title"],
						"type"		=> "textbox",
						"width"		=> "6",
						"align"		=> "right",
						"preffix"	=> "{CUR:PREF}",
						"suffix"	=> "{CUR:SUF}",
						"forcevalue"=>	$values["set_period_" . $val["period_id"]]

					);
			}

			$box = array(
				"title"		=> "Pricing" ,
				"width"		=> "6",
				"fields"	=> $_periods,
			);


			$forms["details"]["fields"]["box"][] = $box;
			$forms["add"]["fields"]["box"][] = $box;
			$forms["edit"]["fields"]["box"][] = $box;

		}
		
	}

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

		
		if ($record["membership_id"]) {

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

				if (stristr($key , "details_")) {
					$details[$key] = $val;
				}

				if (stristr($key , "dl_")) {
					$dl[$key] = $val;
				}

				if (stristr($key , "set_period_")) {
					$periods[$key] = $val;
				}
				
			}

			$this->db->QueryUpdate(
				$this->tables["plugin:users_memberships"] , 
				array(
					"membership_details"	=> base64_encode(serialize($details)),
					"membership_pricing"	=> base64_encode(serialize($periods)),
				),
				"membership_id={$record[membership_id]}"
			);

			$this->db->QueryUpdate(
				$this->tables["plugin:users_memberships_lang"] , 
				array(
					"membership_details_lang"	=> base64_encode(serialize($dl)),

				),
				"membership_id={$record[membership_id]} AND lang_id={$record[lang_id]}"
			);
					
		}
		
	}


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

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

		if (is_array($module)) {
			$_CONF["forms"]["adminpath"] = _MODPATH . "users/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
					),
				);
			}
		}
		
	}
	

}

?>