<?php
/**
 * List all portfolios page
 *
 * PHP version 5.0
 *
 * @category	Anova
 * @package		ManageMembersFormHandler
 * @author 		shankar_76ag08
 * @copyright	Copyright (c) 2009 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id:
 * @since 		2008-12-23
 */
require_once('../common/configs/config.inc.php');

$CFG['lang']['include_files'][] = 'languages/%s/admin/manageAnswersMembers.php';
$CFG['lang']['include_files'][] = 'languages/%s/common/email_notify.inc.php';

$CFG['html']['header'] = 'admin/html_header.php';
$CFG['html']['footer'] = 'admin/html_footer.php';

$CFG['mods']['include_files'][] = 'common/classes/class_ListRecordsHandler.lib.php';
$CFG['mods']['include_files'][] = 'common/classes/class_AnovaHandler.lib.php';

//compulsory
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;

if ($_POST)
	$CFG['mods']['include_files'][] = 'common/classes/swiftmailer/lib/EasySwift.php';

/**
 * File to include the header file, database access file, session management file, help file and necessary functions
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');
//-------------- Class LoginFormHandler begins --------------->>>>>//
class ManageMembersFormHandler extends AnovaHandler
	{

		public function addSlashForPercentageOnly($value)
			{
				//$value = 'demo % ';'%%%';'% %%';%demo%';
				$value_rep = addslashes($value);
				$search_value = trim($value_rep);
				$str_arr = str_split($search_value);
				$percentage_avail = false;
				$slashed_value = '';
				foreach($str_arr as $str_val)
					{
						if($str_val == '%')
							{
								$percentage_avail = true;
								$slashed_value .= '\\'.$str_val;
							}
						else
							$slashed_value .= $str_val;
					}

				if($percentage_avail)
					return $slashed_value;

				return $value_rep;
			}
		/**
		 * ManageMembersFormHandler::buildConditionQuery()
		 *
		 * set the condition
		 *
		 * @return
		 */
		public function buildConditionQuery()
			{
				#$this->sql_condition = 'u.'.$this->getUserTableField('user_id').'=ua.user_id AND u.'.$this->getUserTableField('usr_status').'=\'Ok\'';
				$this->sql_condition = 'u.'.$this->getUserTableField('user_id').'=ua.user_id AND u.'.$this->getUserTableField('usr_status').'!=\'Deleted\' AND u.'.$this->getUserTableField('name').'!=\''.$this->CFG['user']['not_allowed'].'\'';
				if ($search_text = $this->fields_arr['search_name'])
					{
						switch($this->fields_arr['search_cat']){
							case '1':
								$search_value = $this->addSlashForPercentageOnly($search_text);
								$this->sql_condition .= ' AND u.'.$this->getUserTableField('display_name').' LIKE \'%'.$search_value.'%\'';
								break;
							case '2':
								$this->sql_condition .= ' AND u.'.$this->getUserTableField('email').' LIKE \''.addslashes($search_text).'\'';
								break;
						} // switch
					}
				if($this->fields_arr['plan_type'])
					{
						$this->sql_condition .= ' AND u.'.$this->getUserTableField('signup_type').' = '.$this->fields_arr['plan_type'];
					}
			}

		/**
		 * ManageMembersFormHandler::buildSortQuery()
		 *
		 * To sort the query
		 *
		 * @return
		 */
		public function buildSortQuery()
			{
				$this->sql_sort = $this->fields_arr['orderby_field'].' '.$this->fields_arr['orderby'];
			}

		/**
		 * ManageMembersFormHandler::displayTopAnalysts()
		 *
		 * @return
		 */
		public function displayTopAnalysts()
			{
				if (!$this->isResultsFound())
					{
						return ;
					}

				$displayTopAnalysts_arr = array();

				$inc = 1;
				$i = 0;
				while($row = $this->fetchResultRecord())
					{
						$userDetails = $this->getUserDetailsFromUsersTable($this->CFG['db']['tbl']['users'], $row['user_id']);

						$displayTopAnalysts_arr[$inc]['userLevelNumber'] = '';
						if($this->CFG['admin']['user_levels']['allowed'])
							$displayTopAnalysts_arr[$inc]['userLevelNumber'] = getUserLevelNumber($row['total_points']);
						$displayTopAnalysts_arr[$inc]['userLevelTitle'] = $this->getUserLevelTitle($displayTopAnalysts_arr[$inc]['userLevelNumber']);
						if($userDetails['usr_status'] == 'Ok')
							$displayTopAnalysts_arr[$inc]['status'] = $this->LANG['common_display_active'];
						else
							$displayTopAnalysts_arr[$inc]['status'] = $this->LANG['common_display_inactive'];

						$displayTopAnalysts_arr[$inc]['record'] = $row;
						$displayTopAnalysts_arr[$inc]['userDetails'] = $userDetails;

						if($this->CFG['admin']['module']['payment'] AND (isset($this->CFG['admin']['payment']['needed']) AND $this->CFG['admin']['payment']['needed']  or $row['signup_type']))
							$displayTopAnalysts_arr[$inc]['userPlanName'] = $this->getPaymentPlanName($row['signup_type']);

						$displayTopAnalysts_arr[$inc]['checkbox_checked'] = '';
						if((is_array($this->getFormField('user_ids'))) && (in_array($row['user_id'], $this->getFormField('user_ids'))))
							$displayTopAnalysts_arr[$inc]['checkbox_checked'] = "CHECKED";

						$displayTopAnalysts_arr[$inc]['row_analyst_by_manual'] = stripString($row['analyst_by'], $this->CFG['username']['short_length']);

						$inc++;
						$i++;
					} // while

				return $displayTopAnalysts_arr;
			}

		/**
		 * ManageMembersFormHandler::getAbuseQuestionsCount()
		 *
		 * @param mixed $uid
		 * @return
		 */
		public function getAbuseQuestionsCount($uid)
		    {
				$sql = 'SELECT COUNT(ques_id) AS abuse_count FROM '.$this->CFG['db']['tbl']['questions'].
						' WHERE user_id='.$this->dbObj->Param('uid').' AND abuse_count>0';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($uid));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				$row = $rs->FetchRow();
				return $row['abuse_count'];
		    }

		/**
		 * ManageMembersFormHandler::getAbuseAnswersCount()
		 *
		 * @param mixed $uid
		 * @return
		 */
		public function getAbuseAnswersCount($uid)
		    {
				$sql = 'SELECT COUNT(ans_id) AS abuse_count FROM '.$this->CFG['db']['tbl']['answers'].
						' WHERE user_id='.$this->dbObj->Param('uid').' AND abuse_count>0';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($uid));
				if (!$rs)
					    trigger_db_error($this->dbObj);
				$row = $rs->FetchRow();
				return $row['abuse_count'];
		    }

		/**
		 * ManageMembersFormHandler::updateStatus()
		 *
		 * @param mixed $is_block
		 * @return
		 */
		public function updateStatus($is_block)
		    {
				if(!$this->fields_arr['user_ids'])
					return ;

				$id = $this->fields_arr['user_ids'];


				$sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].' SET is_blocked='.$this->dbObj->Param($is_block).' WHERE user_id IN ('.$id.')';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($is_block));
				if (!$rs)
				        trigger_db_error($this->dbObj);
		    }

		/**
		 * ManageMembersFormHandler::updateUserStatus()
		 *
		 * @param mixed $is_block
		 * @return
		 */
		public function updateUserStatus($is_block)
		    {
				if(!$this->fields_arr['user_ids'])
					return ;

				$id = $this->fields_arr['user_ids'];

				if($is_block == 'Ok')
					{
						$this->sendActivatedMail($id);
						$this->isNewlyActivated($id);

					}

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['users'].' SET usr_status='.$this->dbObj->Param($is_block).' WHERE user_id IN ('.$id.')';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($is_block));
				if (!$rs)
				        trigger_db_error($this->dbObj);

		    }

		/**
		 * ManageMembersFormHandler::updateIdentityStatus()
		 *
		 * @param mixed $is_block
		 * @return
		 */
		public function updateIdentityStatus($is_block)
		    {
				if(!$this->fields_arr['user_ids'])
					return ;
				$id = $this->fields_arr['user_ids'];
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['user_identity'].' SET status='.$this->dbObj->Param($is_block).' WHERE user_id IN ('.$id.')';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($is_block));
				if (!$rs)
				        trigger_db_error($this->dbObj);

		    }

		/**
		 * ManageMembersFormHandler::sendActivatedMail()
		 *
		 * @param mixed $ids
		 * @return
		 */
		public function sendActivatedMail($ids)
		    {
				$sql = 'SELECT '.$this->getUserTableFields(array('user_id', 'name', 'display_name', 'email')).
						' FROM '.$this->CFG['db']['tbl']['users'].
						' WHERE '.$this->getUserTableField('usr_status').'=\'ToActivate\''.
						' AND '.$this->getUserTableField('user_id').' IN ('.$ids.')';

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					    trigger_db_error($this->dbObj);

				while($row=$rs->FetchRow())
					{
						$activation_link = "<a target=\"_blank\" href=\"".URL($this->CFG['site']['url'])."\">".URL($this->CFG['site']['url'])."</a>";
						$subject = $this->getMailContent($this->LANG['admin_activation_subject'], array('VAR_DISPLAYNAME'=>$row['display_name'], 'VAR_USERNAME'=>$row['name'], 'VAR_EMAIL'=>$row['email'], 'VAR_SITENAME'=>$this->CFG['site']['name'], 'VAR_LINK'=>$activation_link));
						$content = $this->getMailContent($this->LANG['admin_activation_message'], array('VAR_DISPLAYNAME'=>$row['display_name'], 'VAR_USERNAME'=>$row['name'], 'VAR_EMAIL'=>$row['email'], 'VAR_SITENAME'=>$this->CFG['site']['name'], 'VAR_LINK'=>$activation_link));
						$this->_sendMail($row['email'],
											$subject,
											$content,
											$this->CFG['site']['noreply_name'],
											$this->CFG['site']['noreply_email']);
					}
			}

		/**
		 * ManageMembersFormHandler::isNewlyActivated()
		 *
		 * @param mixed $ids
		 * @return
		 */
		public function isNewlyActivated($ids)
			{
				$sql = 'SELECT '.$this->getUserTableField('user_id').
						' ,'.$this->getUserTableField('signup_type').
						' FROM '.$this->CFG['db']['tbl']['users'].
						' WHERE '.$this->getUserTableField('last_logged').' IS NULL'.
						' AND '.$this->getUserTableField('user_id').' IN ('.$ids.')';

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					    trigger_db_error($this->dbObj);

				if(!$rs->PO_RecordCount())
					return;

				while($row=$rs->FetchRow())
					{
						$sql1 = 'UPDATE '.$this->CFG['db']['tbl']['users'].
							' SET '.$this->getUserTableField('last_logged').'=NOW()'.
							' WHERE user_id='.$row['user_id'];
						$stmt1 = $this->dbObj->Prepare($sql1);
						$rs1 = $this->dbObj->Execute($stmt1);
						if (!$rs1)
				        		trigger_db_error($this->dbObj);

						if($this->CFG['admin']['register_points']['allowed'])
							{
								$sql2 = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
									' SET total_points=total_points+'.$this->CFG['admin']['sign_up']['points'].
									' WHERE user_id='.$row['user_id'];
								$stmt2 = $this->dbObj->Prepare($sql2);
								$rs2 = $this->dbObj->Execute($stmt2);
								if (!$rs2)
						        		trigger_db_error($this->dbObj);
							}
						if((isset($this->CFG['admin']['payment']['needed']) AND $this->CFG['admin']['payment']['needed']) or $row['signup_type'])
							{
								$plan_details = $this->getTariffDetails($row['signup_type']);
								$expiry_date = $this->getExpiryDate($plan_details['plan_expired'],'DAY');

								$sql3 = 'UPDATE '.$this->CFG['db']['tbl']['users'].
										' SET '.$this->getUserTableField('expiry_date').'=\''.$expiry_date.'\''.
										' WHERE user_id='.$row['user_id'];

								$stmt3 = $this->dbObj->Prepare($sql3);
								$rs3 = $this->dbObj->Execute($stmt3);
								if (!$rs3)
							    	trigger_db_error($this->dbObj);
							}
					}
			}

		/**
		 * ManageMembersFormHandler::_sendMail()
		 *
		 * To send email
		 *
		 * @param 		string $to_email to email id
		 * @param 		string $subject subject
		 * @param		string $body mail body
		 * @param 		string $sender_name sender name
		 * @param 		string $sender_email sender email
		 * @return 		void
		 * @access 		private
		 */
		private function _sendMail($to_email, $subject, $body, $sender_name, $sender_email)
			{
			    $this->buildEmailTemplate($subject, $body, false, true);
				$EasySwift = new EasySwift($this->getSwiftConnection());
				$EasySwift->flush();
				$EasySwift->addPart($this->getEmailContent(), "text/html");
				$from_address = $sender_name.'<'.$sender_email.'>';
				return $EasySwift->send($to_email, $from_address, $this->getEmailSubject());
			}

		 public function getPaymentPlanList()
			{

				$sql = 'SELECT plan_name, plan_id FROM ' .$this->CFG['db']['tbl']['payment_plan_settings'].
				 	   ' WHERE plan_status =\'Yes\'';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
						trigger_db_error($this->dbObj);

				$i = 0;
				$this->planListarr = array();
				while($row=$rs->FetchRow())
					{
						$this->planListarr['plan_id'][$i] = $row['plan_id'];
						$this->planListarr['plan_name'][$i] = $row['plan_name'];
						$i++;
					}

				$plan_arr = @array_combine($this->planListarr['plan_id'], $this->planListarr['plan_name']);
				return $plan_arr;
			}
		/**
		 * ManageMembersFormHandler::updateFacebookIdentityStatus()
		 *
		 * @param mixed $is_block
		 * @return
		 */
		public function updateFacebookIdentityStatus($is_block)
		    {
				if(!$this->fields_arr['user_ids'])
					return ;
				$id = $this->fields_arr['user_ids'];
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['facebook_identity'].' SET status='.$this->dbObj->Param($is_block).' WHERE user_id IN ('.$id.')';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($is_block));
				if (!$rs)
				        trigger_error($this->dbObj->ErrorNo().' '.$this->dbObj->ErrorMsg(), E_USER_ERROR);
		    }
	}
//<<<<<-------------- Class LoginFormHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
$managefrm = new ManageMembersFormHandler();

$managefrm->setPageBlockNames(array('form_search', 'form_analysts', 'show_form_confirm'));

//default form fields and values...
$managefrm->setFormField('search_question', '');
$managefrm->setFormField('search_name', '');
$managefrm->setFormField('search_cat', '');
$managefrm->setFormField('plan_type', '');
$managefrm->setFormField('action', '');
$managefrm->setFormField('user_ids', array());
$managefrm->setFormField('check_all', '');
$managefrm->setFormField('type', '');
$managefrm->setFormField('order', '');
$managefrm->title = $LANG['manage_answers_members'];

/*************Start navigation******/
$managefrm->numpg = $CFG['data_tbl']['numpg'];
$managefrm->setFormField('start', 0);
$managefrm->setFormField('numpg', $CFG['data_tbl']['numpg']);//

$managefrm->setMinRecordSelectLimit($CFG['data_tbl']['min_record_select_limit']);
$managefrm->setMaxRecordSelectLimit($CFG['data_tbl']['max_record_select_limit']);
$managefrm->setNumPerPageListArr($CFG['data_tbl']['numperpage_list_arr']);
//Set tables and fields to return
$managefrm->setTableNames(array());
$managefrm->setReturnColumns(array());
//orderby field and orderby
$managefrm->setFormField('orderby_field', 'u.display_name');
$managefrm->setFormField('orderby', 'ASC');
/*************End navigation******/
$managefrm->sanitizeFormInputs($_REQUEST);
// Default page block
$managefrm->setAllPageBlocksHide();
$managefrm->setPageBlockShow('form_search');
$managefrm->setPageBlockShow('form_analysts');

if(isset($managefrm->CFG['admin']['payment']['needed']) AND $managefrm->CFG['admin']['payment']['needed'])
	$managefrm->populatePaymentPlansList = $managefrm->getPaymentPlanList();

if($managefrm->isFormPOSTed($_POST, 'reset'))
	{
		$managefrm->setFormField('search_name', '');
	}
if(isDemoSite() AND $managefrm->isFormPOSTed($_POST, 'confirm_action'))
	{
		$managefrm->setCommonErrorMsg($LANG['no_permission_for_demo_user']);
		$managefrm->setPageBlockShow('block_msg_form_error');
	}
elseif($managefrm->isFormPOSTed($_POST, 'confirm_action'))
	{
		$valid_ids = explode(",", $managefrm->getFormField('user_ids'));
  		$webmaster_ids = array("1");
  		$webmaster_error_msg = '';
		if(in_array('1', $valid_ids))
			{
				$webmaster_error_msg = $LANG['webmaster_action_arr'];
				$valid_ids = array_diff($valid_ids, $webmaster_ids);
			}
		if(is_array($valid_ids))
			{
				$valid_ids = implode(",", $valid_ids);
				$managefrm->setFormField('user_ids', $valid_ids);
			}
		if($managefrm->getFormField('action') == 'block_member')
		  	{
			  	$managefrm->updateStatus('Yes');
				$managefrm->setCommonSuccessMsg($LANG['managemembers_block_success'].' <br />'.$webmaster_error_msg);
		  	}
		elseif($managefrm->getFormField('action') == 'unblock_member')
		  	{
				$managefrm->updateStatus('No');
				$managefrm->setCommonSuccessMsg($LANG['managemembers_unblock_success']);
		  	}
		elseif($managefrm->getFormField('action') == 'active_member')
		  	{
				$managefrm->updateUserStatus('Ok');
				if ($CFG['admin']['module']['facebook'])
					$managefrm->updateFacebookIdentityStatus('Ok');
				$managefrm->setCommonSuccessMsg($LANG['managemembers_active_success']);
		  	}
		elseif($managefrm->getFormField('action') == 'inactive_member')
		  	{
				$managefrm->updateUserStatus('ToActivate');
				if ($CFG['admin']['module']['facebook'])
					$managefrm->updateFacebookIdentityStatus('ToActivate');
				$managefrm->setCommonSuccessMsg($LANG['managemembers_inactive_success'].' <br />'.$webmaster_error_msg);
		  	}
		$managefrm->setPageBlockShow('block_msg_form_success');
	}
//<<<<<<<---------------code ends-------------///
if ($managefrm->isShowPageBlock('form_search'))
	{
		$managefrm->form_search['search_cat_arr'] = array("1" => $LANG['member_display_name'], "2" => $LANG['search_type_email']);
	}

if ($managefrm->isShowPageBlock('form_analysts'))
	{
		$managefrm->setTableNames(array($CFG['db']['tbl']['users_ans_log'].' as ua', $CFG['db']['tbl']['users'].' as u'));
		$managefrm->setReturnColumns(array('ua.user_id', 'signup_type', 'total_ques', 'is_blocked', 'total_ans', 'total_points', $managefrm->getUserTableField('display_name').' as analyst_by', 'UNIX_TIMESTAMP(date_updated) as date_updated','doj','usr_status' ));
		$managefrm->buildSelectQuery();
		$managefrm->buildConditionQuery();
		$managefrm->buildSortQuery();
		$managefrm->buildQuery();
		$managefrm->executeQuery();
		$managefrm->form_analysts['hidden_arr'] = array('start', 'numpg','search_name','search_cat','orderby_field', 'orderby');

		$managefrm->form_analysts['displayTopAnalysts_arr'] = $managefrm->displayTopAnalysts();
		if ($managefrm->isResultsFound())
			{
				$managefrm->form_analysts['action_arr'] = array(""=>$LANG['common_select_action'], "block_member" => $LANG['common_block'],
													                "unblock_member" => $LANG['common_unblock'],
													                "active_member" => $LANG['common_display_active'],
													                "inactive_member" => $LANG['common_display_inactive']);
				$managefrm->form_analysts['pagingArr'] = array('type', 'orderby_field', 'orderby');
				if ($managefrm->getFormField('search_name'))
					$managefrm->form_analysts['pagingArr'][] .= 'search_name';

				if ($managefrm->getFormField('search_cat'))
					$managefrm->form_analysts['pagingArr'][] .= 'search_cat';
				if ($managefrm->getFormField('plan_type'))
					$managefrm->form_analysts['pagingArr'][] .= 'plan_type';
				$smartyObj->assign('smarty_paging_list', $managefrm->populatePageLinksGET($managefrm->getFormField('start'), $managefrm->form_analysts['pagingArr']));
			}
	}


//--------------------Page block templates begins-------------------->>>>>//
//include the header file
$managefrm->includeHeader();
//include the content of the page
setTemplateFolder('admin/');
$smartyObj->display('manageAnswersMembers.tpl');
?>
<script language="javascript" type="text/javascript">
	var block_arr= new Array('selMsgConfirm');
	var replace_url = '<?php echo $CFG['site']['url'];?>login.php';
</script>
<?php
//<<<<<<<<<---------Page block template ends--------------------------//
$managefrm->includeFooter();
?>