<?php
//-------------- Class AnalystsFormHanlder begins --------------->>>>>//
/**
 *
 * @category	Anova
 * @package		TopAnalystsFormHandler
 * @author 		senthil_52ag05
 * @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-19
 */
class AnalystsFormHanlder extends AnovaHandler
	{

		public $pagingArr;

		/**
		 * AnalystsFormHanlder::storeSearchFields()
		 *
		 * @return
		 */
		public function storeSearchFields()
			{
				$allowed_fields_arr = array(
										'search_member'=>$this->fields_arr['search_member'],
										'total_points'=>$this->fields_arr['total_points'],
										'maxtotal_points'=>$this->fields_arr['maxtotal_points'],
										'total_questions'=>$this->fields_arr['total_questions'],
										'maxtotal_questions'=>$this->fields_arr['maxtotal_questions'],
										'total_answers'=>$this->fields_arr['total_answers'],
										'maxtotal_answers'=>$this->fields_arr['maxtotal_answers']
										);

				$allowed_fields_arr = serialize($allowed_fields_arr);

				$sql = 'UPDATE '.$this->CFG['db']['tbl']['advanced_search'].' SET'.
						' member = '.$this->dbObj->Param('member').' WHERE'.
						' user_id = '.$this->dbObj->Param('user_id');

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($allowed_fields_arr, $this->CFG['user']['user_id']));
				    if (!$rs)
					    trigger_db_error($this->dbObj);
			}

		/**
		 * AnalystsFormHanlder::populateSearchFields()
		 *
		 * @return
		 */
		public function populateSearchFields()
			{
				if($this->fields_arr['so']=='adv')
					{
						$sql = 'SELECT member FROM '.$this->CFG['db']['tbl']['advanced_search'].
								' WHERE user_id='.$this->dbObj->Param('user_id');

						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt, array($this->CFG['user']['user_id']));
						    if (!$rs)
							    trigger_db_error($this->dbObj);

						if($row = $rs->FetchRow())
							{
								if($row['member'])
									{
										$search_fields_arr = unserialize($row['member']);
										$this->fields_arr = array_merge($this->fields_arr, $search_fields_arr);
									}
							}
					}
			}

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

		/**
		 * set the condition
		 *
		 * @access public
		 * @return void
		 **/
		public function buildConditionQuery()
			{
				$this->sql_condition = 'u.'.$this->getUserTableField('user_id').'=ua.user_id AND u.'.$this->getUserTableField('usr_status').'=\'Ok\' AND u.'.$this->getUserTableField('name').'!=\''.$this->CFG['user']['not_allowed'].'\'';
				if($this->fields_arr['week'])
					{
						$this->sql_condition .= ' AND u.'.$this->getUserTableField('user_id').'=ua.user_id AND u.'.$this->getUserTableField('user_id').'=T.user_id AND T.week_points>0';
						$this->pagingArr[] = 'week';
					}
				if($this->fields_arr['search_member'])
					{
						$search_value = $this->addSlashForPercentageOnly($this->fields_arr['search_member']);
						$this->sql_condition .= ' AND u.'.$this->getUserTableField('display_name').' like \'%'.$search_value.'%\'';
						$this->pagingArr[] = 'search_member';
					}
				if($this->fields_arr['total_points'])
					{
						$this->sql_condition .= ' AND ua.total_points >= '.$this->fields_arr['total_points'];
						$this->pagingArr[] = 'total_points';
					}
				if($this->fields_arr['maxtotal_points'])
					{
						$this->sql_condition .= ' AND ua.total_points <= '.$this->fields_arr['maxtotal_points'];
						$this->pagingArr[] = 'maxtotal_points';
					}
				if($this->fields_arr['total_questions'])
					{
						$this->sql_condition .= ' AND ua.total_ques >= '.$this->fields_arr['total_questions'];
						$this->pagingArr[] = 'total_questions';
					}
				if($this->fields_arr['maxtotal_questions'])
					{
						$this->sql_condition .= ' AND ua.total_ques <= '.$this->fields_arr['maxtotal_questions'];
						$this->pagingArr[] = 'maxtotal_questions';
					}
				if($this->fields_arr['total_answers'])
					{
						$this->sql_condition .= ' AND ua.total_ans >= '.$this->fields_arr['total_answers'];
						$this->pagingArr[] = 'total_answers';
					}
				if($this->fields_arr['maxtotal_answers'])
					{
						$this->sql_condition .= ' AND ua.total_ans <= '.$this->fields_arr['maxtotal_answers'];
						$this->pagingArr[] = 'maxtotal_answers';
					}
			}

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

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function displayTopAnalysts()
			{
				$displayTopAnalysts_arr = array();
				$inc = 1;
				while($row = $this->fetchResultRecord())
					{
						$displayTopAnalysts_arr[$inc]['clsOddOrEvenQuestion'] = 'clsEvenQuestion';
						if ($inc%2)
							$displayTopAnalysts_arr[$inc]['clsOddOrEvenQuestion'] = 'clsOddQuestion';
						$displayTopAnalysts_arr[$inc]['userLevelNumber'] = '';
						if($this->CFG['admin']['user_levels']['allowed'])
							$displayTopAnalysts_arr[$inc]['userLevelNumber'] = getUserLevelNumber($row['total_points']);

						$displayTopAnalysts_arr[$inc]['record'] = $row;
						$displayTopAnalysts_arr[$inc]['getResolvedQuestions'] = $this->getResolvedQuestions($row['user_id']);

						$displayTopAnalysts_arr[$inc]['myanswers']['url'] = getMemberUrl($row['user_id'], $row['name']);
						$displayTopAnalysts_arr[$inc]['myanswers']['href_val'] = stripString($row['analyst_by'], $this->CFG['username']['short_length']);
						$displayTopAnalysts_arr[$inc]['questions']['url'] = getAnovaUrl('questions', '?view=search&amp;uname='.$row['name'].'&amp;opt=ques', 'search/?uname='.$row['name'].'&amp;opt=ques');
						$displayTopAnalysts_arr[$inc]['questions_ans']['url'] = getAnovaUrl('questions', '?view=search&amp;uname='.$row['name'].'&amp;opt=ans', 'search/?uname='.$row['name'].'&amp;opt=ans');
						$displayTopAnalysts_arr[$inc]['questions_resolve']['url'] = getAnovaUrl('questions', '?view=search&amp;uname='.$row['name'].'&amp;opt=resolve', 'search/?uname='.$row['name'].'&amp;opt=resolve');

						$inc++;
					}
				return $displayTopAnalysts_arr;
			}
	}
//<<<<<-------------- Class AnalystsFormHanlder begins ---------------//
//-------------------- Code begins -------------->>>>>//
$analysts = new AnalystsFormHanlder();

$analysts->setPageBlockNames(array('form_search', 'form_analysts', 'form_advanced_search', 'form_week_experts', 'form_search_heading', 'form_normal_heading'));

//default form fields and values...
$analysts->setFormField('search_question', '');

$pagename = $LANG['common_top_analyst_title'];
$LANG['analysts_title'] = $LANG['common_top_analyst_title'];
$cfg_title = $LANG['analysts_title'];

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

$analysts->setMinRecordSelectLimit($CFG['data_tbl']['min_record_select_limit']);
$analysts->setMaxRecordSelectLimit($CFG['data_tbl']['max_record_select_limit']);
$analysts->setNumPerPageListArr($CFG['data_tbl']['numperpage_list_arr']);
//Set tables and fields to return
$analysts->setTableNames(array());
$analysts->setReturnColumns(array());
//orderby field and orderby
$analysts->setFormField('week', '');
$analysts->setFormField('search_member', '');
$analysts->setFormField('maxtotal_points', '');
$analysts->setFormField('total_points', '');
$analysts->setFormField('maxtotal_questions', '');
$analysts->setFormField('total_questions', '');
$analysts->setFormField('maxtotal_answers', '');
$analysts->setFormField('total_answers', '');
$analysts->setFormField('adv_search', '');
$analysts->setFormField('so', 'min');
$analysts->setFormField('orderby_field', '');
$analysts->setFormField('orderby', '');
/*************End navigation******/
$analysts->sanitizeFormInputs($_REQUEST);
// Default page block
$analysts->setAllPageBlocksHide();
$analysts->setPageBlockShow('form_normal_heading');
$analysts->clsAllTime = $analysts->clsLastWeek = '';

if ($analysts->isFormPOSTed($_GET, 'week'))
	{
		$analysts->setPageBlockShow('form_week_experts');
		$analysts->LANG['analysts_lastweek_title'] = $LANG['analysts_this_week'];
		$analysts->LANG['analysts_alltime_title'] = '<a href="'.getAnovaUrl('topanalysts').'">'.$LANG['analysts_all_time'].'</a>';
		$analysts->LANG['analysts_this_week_note'] = str_ireplace('VAR_REFRESH_TIME',$CFG['admin']['week_experts']['refresh'],$LANG['analysts_this_week_note']);
		$analysts->createWeekExperts();

		$analysts->setTableNames(array($CFG['db']['tbl']['users_ans_log'].' as ua', $CFG['db']['tbl']['users'].' as u', $CFG['db']['tbl']['view_weekly_experts'].' as T'));
		$analysts->setReturnColumns(array('T.user_id','T.week_points','ua.user_id', 'total_ques', 'total_ans', 'total_points', $analysts->getUserTableField('display_name').' as analyst_by', $analysts->getUserTableField('name').' as name', 'u.'.$analysts->getUserTableField('user_id').' as img_user_id', $analysts->getUserTableFields(array('image_path', 'gender', 't_height', 't_width', 's_height', 's_width', 'photo_server_url', 'photo_ext'), false).'UNIX_TIMESTAMP(date_updated) as date_updated'));
		$analysts->setFormField('orderby_field', 'T.week_points');
		$analysts->setFormField('orderby', 'DESC');
		$analysts->clsLastWeek = 'clsActive';
	}
else
	{
		$analysts->setPageBlockShow('form_analysts');
		$analysts->LANG['analysts_alltime_title'] = $LANG['analysts_all_time'];
		$analysts->LANG['analysts_lastweek_title'] = '<a href="'.getAnovaUrl('topanalysts', '?week=1', '?week=1').'">'.$LANG['analysts_this_week'].'</a>';
		$analysts->LANG['analysts_this_week_note'] = str_ireplace('VAR_REFRESH_TIME',$CFG['admin']['week_experts']['refresh'],$LANG['analysts_this_week_note']);
		$analysts->setTableNames(array($CFG['db']['tbl']['users_ans_log'].' as ua', $CFG['db']['tbl']['users'].' as u'));
		$analysts->setReturnColumns(array('ua.user_id', 'total_ques', 'total_ans', 'total_points', $analysts->getUserTableField('display_name').' as analyst_by', $analysts->getUserTableField('name').' as name', 'u.'.$analysts->getUserTableField('user_id').' as img_user_id', $analysts->getUserTableFields(array('image_path', 'gender', 't_height', 't_width', 's_height', 's_width', 'photo_server_url', 'photo_ext'), false).'UNIX_TIMESTAMP(date_updated) as date_updated'));
		$analysts->setFormField('orderby_field', 'ua.total_points');
		$analysts->setFormField('orderby', 'DESC');

		$analysts->clsAllTime = 'clsActive';
	}

if($analysts->getFormField('so')=='adv' and !$analysts->isFormPOSTed($_REQUEST, 'adv_search'))
	{
		$analysts->populateSearchFields();
		$analysts->setPageBlockHide('form_analysts');
		$analysts->setPageBlockHide('form_week_experts');
		$analysts->setPageBlockHide('form_search_heading');
		$analysts->setPageBlockHide('form_normal_heading');
		$analysts->setPageBlockShow('form_advanced_search');
	}

if($analysts->isFormPOSTed($_POST, 'adv_search'))
	{
		$analysts->getFormField('total_points') AND
			$analysts->chkIsNumeric('total_points', $LANG['common_err_tip_numeric']);

		if ($analysts->getFormField('maxtotal_points'))
			{
				if (!$analysts->chkIsNumeric('maxtotal_points', $LANG['common_err_tip_numeric']))
					$analysts->setFormFieldErrorTip('total_points', $LANG['common_err_tip_numeric']);
			}

		$analysts->getFormField('total_questions') AND
			$analysts->chkIsNumeric('total_questions', $LANG['common_err_tip_numeric']);

		if ($analysts->getFormField('maxtotal_questions'))
			{
				if (!$analysts->chkIsNumeric('maxtotal_questions', $LANG['common_err_tip_numeric']))
					$analysts->setFormFieldErrorTip('total_questions', $LANG['common_err_tip_numeric']);
			}

		$analysts->getFormField('total_answers') AND
			$analysts->chkIsNumeric('total_answers', $LANG['common_err_tip_numeric']);

		if ($analysts->getFormField('maxtotal_answers'))
			{
				if (!$analysts->chkIsNumeric('maxtotal_answers', $LANG['common_err_tip_numeric']))
					$analysts->setFormFieldErrorTip('total_answers', $LANG['common_err_tip_numeric']);
			}

		if ($analysts->isValidFormInputs())
			{
				$analysts->storeSearchFields();
			}
		else
			{
				$analysts->setPageBlockHide('form_analysts');
				$analysts->setPageBlockHide('form_week_experts');
				$analysts->setPageBlockShow('form_advanced_search');
				$analysts->setPageBlockShow('block_msg_form_error');
				$analysts->setCommonErrorMsg($LANG['err_msg_invalid_search_option']);
			}
	}

if(($analysts->getFormField('adv_search')) OR $analysts->isFormPOSTed($_REQUEST, 'search_member'))
	{
		$analysts->LANG['analysts_home_title'] = '<a href="'.getAnovaUrl('topanalysts').'">'.$LANG['common_top_analyst_title'].'</a> - <span>'.$LANG['search_results'].'</span>';
		$analysts->setPageBlockHide('form_normal_heading');
		$analysts->setPageBlockShow('form_search_heading');
	}
if($analysts->isShowPageBlock('form_advanced_search'))
	{
		$analysts->LANG['analysts_home_title'] = '<a href="'.getAnovaUrl('topanalysts').'">'.$LANG['common_top_analyst_title'].'</a> - <span>'.$LANG['advanced_search'].'</span>';
		$analysts->form_advanced_search['form_action'] = getAnovaUrl('topanalysts', '?so=adv', '?so=adv');
		$analysts->setPageBlockHide('form_normal_heading');
		$analysts->setPageBlockShow('form_search_heading');
	}

//<<<<--------------------Code Ends----------------------//
//--------------------Page block templates begins-------------------->>>>>//
$CFG['html']['page_id'] .= 'analysts';
$CFG['site']['title'] = $cfg_title.' - '.$CFG['site']['title'];
$analysts->resultspage = 0;
if ($analysts->isShowPageBlock('form_analysts') OR $analysts->isShowPageBlock('form_week_experts'))
	{
		$analysts->pagingArr = array('orderby_field', 'orderby');
		$analysts->buildSelectQuery();
		$analysts->buildConditionQuery();
		$analysts->buildSortQuery();
		$analysts->buildQuery();
		$analysts->executeQuery();
		$analysts->resultspage = 1;
		if ($analysts->isResultsFound())
			{
				$analysts->form_analysts['TopAnalysts'] = $analysts->displayTopAnalysts();
				$smartyObj->assign('smarty_paging_list', $analysts->populatePageLinksGET($analysts->getFormField('start'), $analysts->pagingArr));
			}
	}

//include the header file
$analysts->includeHeader();
//include the content of the page
setTemplateFolder('general/', $CFG['admin']['index']['anova_module']);
$smartyObj->display('topAnalysts.tpl');
//include the footer of the page
//<<<<<<--------------------Page block templates Ends--------------------//
?>
<script language="javascript" type="text/javascript">
	var popupPosition = -10;
</script>
<?php
$analysts->includeFooter();
?>