<?php
require_once('../common/configs/config.inc.php');
$CFG['lang']['include_files'][] = 'languages/%s/admin/editRewardPoints.php';
$CFG['html']['header'] = 'admin/html_header.php';
$CFG['html']['footer'] = 'admin/html_footer.php';
$CFG['mods']['include_files'][] = 'common/classes/class_FormHandler.lib.php';
$CFG['mods']['include_files'][] = 'common/classes/class_ListRecordsHandler.lib.php';
//partial optimization. Don't use DB unnecessarily ie, DB only needed when the form is submitted/posted.
//compulsory
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
/**
 * 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 RewardPointsHandler extends ListRecordsHandler
	{

		public $pagingArr;

		public function storeSearchFields()
			{
				$allowed_fields_arr = array(
										'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);
			}

		/**
		 * 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'].'\'';

			}

		/**
		 * 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 displayRewardPoints()
			{
				global $smartyObj;
				$displayRewardpoints_arr	=	array();
				$i = 0;
				$inc=1;
				if ($this->isResultsFound())
					{
						while($row = $this->fetchResultRecord())
						  {
							$i++;
							$userDetails = $this->getUserDetailsFromUsersTable($this->CFG['db']['tbl']['users'], $row['user_id']);
							$displayRewardpoints_arr[$inc]['userDetails'] = $userDetails;
							$displayRewardpoints_arr[$inc]['record'] = $row;
							$displayRewardpoints_arr[$inc]['userLevelNumber'] = getUserLevelNumber($row['total_points']);
						    $displayRewardpoints_arr[$inc]['analyst'] = stripString($row['analyst_by'], $this->CFG['username']['short_length']);
							$displayRewardpoints_arr[$inc]['user_id'] = $this->getColumnValue('user_id');
							$inc++;
						  } // while

					 }
				$smartyObj->assign('smarty_paging_list', $this->populatePageLinksGET($this->getFormField('start'), array('type', 'orderby_field')));
				return 	$displayRewardpoints_arr	;
			}
		public function updateRewardpoints()
			{
				$user_ids = $this->getFormField('user_id');
				$points =  $this->getFormField('points');
				$cnt = count($user_ids);
				for($i =0;$i<$cnt;$i++)
					{
						$sql = 'UPDATE '.$this->CFG['db']['tbl']['users_ans_log'].
							   ' SET total_points='.$points[$i].''.
							   ' WHERE user_id='.$user_ids[$i].'';
						$stmt = $this->dbObj->Prepare($sql);
						$rs = $this->dbObj->Execute($stmt);
						if (!$rs)
							trigger_db_error($this->dbObj);
					}
			}

	}
//<<<<<-------------- Class RewardPointsHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
#print_r($_POST);
$points = new RewardPointsHandler();
$points->setPageBlockNames(array( 'form_reward_list', 'form_normal_heading', 'block_msg_form_error', 'block_msg_form_success'));
//default form fields and values...
$points->setFormField('search_question', '');
$pagename = $LANG['common_reward_points_title'];
$title = $LANG['common_reward_points_title'];
$cfg_title = $title;
$smartyObj->assign('title', $title);
$points->setDBObject($db);
/*************Start navigation******/
$points->numpg = $CFG['data_tbl']['numpg'];
$points->setFormField('start', 0);
$points->setFormField('numpg', $CFG['data_tbl']['numpg']);
$points->setMinRecordSelectLimit($CFG['data_tbl']['min_record_select_limit']);
$points->setMaxRecordSelectLimit($CFG['data_tbl']['max_record_select_limit']);
$points->setNumPerPageListArr($CFG['data_tbl']['numperpage_list_arr']);
//Set tables and fields to return
$points->setTableNames(array());
$points->setReturnColumns(array());
//orderby field and orderby
$points->setFormField('week', '');
$points->setFormField('search_member', '');
$points->setFormField('maxtotal_points', '');
$points->setFormField('total_points', '');
$points->setFormField('maxtotal_questions', '');
$points->setFormField('total_questions', '');
$points->setFormField('maxtotal_answers', '');
$points->setFormField('total_answers', '');
$points->setFormField('adv_search', '');
$points->setFormField('msg', '');

$points->setFormField('orderby_field',  $points->getUserTableField('display_name'));
$points->setFormField('orderby', 'ASC');
$points->setFormField('points', array());
$points->setFormField('user_id', array());
$points->setFormField('order', '');
$points->setFormField('action', '');
$points->setFormField('value', '');
$points->setFormField('type', '');

/*************End navigation******/
$points->sanitizeFormInputs($_REQUEST);
// Default page block
$points->setAllPageBlocksHide();
$points->setPageBlockShow('form_normal_heading');
$points->setPageBlockShow('form_reward_list');
$title = $LANG['header_reward_points_links'];
$smartyObj->assign('title', $title);
$points->setTableNames(array($CFG['db']['tbl']['users_ans_log'].' as ua', $CFG['db']['tbl']['users'].' as u'));
$points->setReturnColumns(array('ua.user_id', 'total_ques', 'total_ans', 'total_points', $points->getUserTableField('display_name').' as analyst_by', $points->getUserTableField('name').' as name', 'u.'.$points->getUserTableField('user_id').' as img_user_id', $points->getUserTableFields(array('image_path', 'gender', 't_height', 't_width', 's_height', 's_width', 'photo_server_url', 'photo_ext'), false).'TIMEDIFF(NOW(), date_updated) as date_updated'));



if($points->isFormPOSTed($_POST, 'action_points'))
	{
		$pts =  $points->getFormField('points');
		$cnt = count($pts);
		for($i =0;$i<$cnt;$i++)
			{
				if(!ctype_digit($pts[$i]))
					{
						$points->setCommonErrorMsg($LANG['err_tip_numeric']);
						$points->setPageBlockShow('block_msg_form_error');
						$points->setFormFieldErrorTip('points', $LANG['err_tip_numeric']);
						Redirect2URL('editRewardPoints.php?start='.$points->getFormField('start').'&msg=error&type='.$points->getFormField('type'));
					}

			}
		if ($points->isValidFormInputs())
			{
				$points->sanitizeFormInputs($_REQUEST);
				$points->updateRewardpoints();
				$points->setCommonSuccessMsg($LANG['successfully_updated']);
				$points->setPageBlockShow('block_msg_form_success');
				Redirect2URL('editRewardPoints.php?start='.$points->getFormField('start').'&msg=success&type='.$points->getFormField('type'));
			}
	}

if($points->isFormGETed($_GET, 'msg'))
	{
		if($points->getFormField('msg') == 'success')
			{
				$points->setCommonSuccessMsg($LANG['successfully_updated']);
				$points->setPageBlockShow('block_msg_form_success');
			}
		elseif($points->getFormField('msg') == 'error')
			{
				$points->setCommonErrorMsg($LANG['err_tip_numeric']);
				$points->setPageBlockShow('block_msg_form_error');
				$points->setFormFieldErrorTip('points', $LANG['err_tip_numeric']);
			}
	}



//--------------------Page block templates begins-------------------->>>>>//


if ($points->isShowPageBlock('form_reward_list'))
	{
		$points->buildSelectQuery();
		$points->buildConditionQuery();
		$points->buildSortQuery();
		$points->buildQuery();
		$points->executeQuery();
		$points->form_reward_list['hidden_arr']	=	array('orderby_field', 'orderby');
		$points->block_displayReward_arr  = $points->displayRewardPoints();

	}

//<<<<<-------------------- Page block templates ends --------------------//
//--------------------Page block templates begins-------------------->>>>>//
//include the header file
$points->includeHeader();
//include the content of the page
setTemplateFolder('admin/');
$smartyObj->display('editRewardPoints.tpl');
$points->includeFooter();
?>

