<?php
/**
 * File handling the add manageBanners and manage the advertisment
 *
 *
 * PHP version 5.0
 *
 * @category	###Anova###
 * @package		###Manage banner###
 * @author 		selvaraj_47ag04
 * @copyright	Copyright (c) 2009 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id: manageBanner.php 766 2008-06-26 09:52:00Z selvaraj_47ag04 $
 * @since 		2008-12-23
 */
/**
 * File having common configuration variables required for the entire project
 */
require_once('../common/configs/config.inc.php');
$CFG['lang']['include_files'][] = 'languages/%s/admin/manageBanner.php';
$CFG['html']['header'] = 'admin/html_header.php';
$CFG['html']['footer'] = 'admin/html_footer.php';
$CFG['mods']['include_files'][] = 'languages/%s/lists_array/banner_list_array.inc.php';
$CFG['mods']['include_files'][] = 'common/classes/class_ListRecordsHandler.lib.php';
//compulsory
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
/**
 * To include application top file
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');
/**
 * Add banner
 */
class Add extends ListRecordsHandler
	{
		public $manage_banner_title;
		/**
		 * GroupsFormHandler::buildConditionQuery()
		 *
		 * @return
		 **/
		public function buildConditionQuery()
			{
				$this->sql_condition = '';
				if($this->fields_arr['name'])
					{
						$this->sql_condition .= 'user_id=\''.addslashes($this->getUserDetail('name', $this->fields_arr['name'], 'user_id')).'\' AND ';
					}
				if($this->fields_arr['block_search'])
					$this->sql_condition .= 'block=\''.addslashes($this->fields_arr['block_search']).'\' AND ';
				$this->sql_condition = substr($this->sql_condition, 0, strrpos($this->sql_condition, 'AND'));
			}

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

		/**
		 * Add::insertAdvertisementTable()
		 *
		 * @return
		 **/
		public function insertAdvertisementTable()
			{
				$start_date = $this->fields_arr['start_date'];
				$end_date = $this->fields_arr['end_date'];
				$this->fields_arr['allowed_impressions'] = $this->fields_arr['allowed_impressions']?$this->fields_arr['allowed_impressions']:0;
				$sql = 'INSERT INTO '.$this->CFG['db']['tbl']['advertisement'].' SET'.
						' user_id='.$this->CFG['user']['user_id'].','.
						' block='.$this->dbObj->Param('block').','.
						' post_from=\'Admin\','.
						' about='.$this->dbObj->Param('about').','.
						' source='.$this->dbObj->Param('source').','.
						' start_date='.$this->dbObj->Param('start_date').','.
						' end_date='.$this->dbObj->Param('end_date').','.
						' status='.$this->dbObj->Param('status').','.
						' add_type='.$this->dbObj->Param('add_type').','.
						' allowed_impressions='.$this->dbObj->Param('allowed_impressions').','.
						' date_added=NOW()';
				$array = array($this->fields_arr['block'], $this->fields_arr['about'],
								$this->fields_arr['source'], $start_date,
								$end_date, $this->fields_arr['status'], $this->fields_arr['add_type'],
								$this->fields_arr['allowed_impressions']);

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

				$this->setDefaultValue();
			}

		/**
		 * Add::updateAdvertisementTable()
		 *
		 * @return
		 */
		public function updateAdvertisementTable()
			{
				$start_date = $this->fields_arr['start_date'];
				$end_date = $this->fields_arr['end_date'];
				$this->fields_arr['allowed_impressions'] = $this->fields_arr['allowed_impressions']?$this->fields_arr['allowed_impressions']:0;
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['advertisement'].' SET'.
						' block='.$this->dbObj->Param('block').','.
						' about='.$this->dbObj->Param('about').','.
						' source='.$this->dbObj->Param('source').','.
						' start_date='.$this->dbObj->Param('start_date').','.
						' end_date='.$this->dbObj->Param('end_date').','.
						' status='.$this->dbObj->Param('status').','.
						' add_type='.$this->dbObj->Param('add_type').','.
						' allowed_impressions='.$this->dbObj->Param('allowed_impressions').
						' WHERE add_id='.$this->dbObj->Param('add_id');
				$array = array($this->fields_arr['block'], $this->fields_arr['about'],
								$this->fields_arr['source'], $start_date,
								$end_date, $this->fields_arr['status'], $this->fields_arr['add_type'],
								$this->fields_arr['allowed_impressions'], $this->fields_arr['aid']);

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

				$this->setDefaultValue();
				if($this->dbObj->Affected_Rows())
					return true;
				return false;
			}

		/**
		 * Add::deleteAdvertisementTable()
		 *
		 * @return
		 **/
		public function deleteAdvertisementTable()
			{
				$sql = 'DELETE FROM '.$this->CFG['db']['tbl']['advertisement'].' WHERE'.
						' add_id IN('.$this->fields_arr['aid'].')';

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

				if($this->dbObj->Affected_Rows())
					{
						return true;
					}
				return false;
			}

		/**
		 * Add::updateStatusInAdvertisementTable()
		 *
		 * @param $status
		 * @return
		 **/
		public function updateStatusInAdvertisementTable($status)
			{
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['advertisement'].' SET'.
						' status='.$this->dbObj->Param('status').' WHERE'.
						' add_id IN('.$this->fields_arr['aid'].')';

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

				if($this->dbObj->Affected_Rows())
					{
						return true;
					}
				return false;
			}

		/**
		 * Add::setDefaultValue()
		 *
		 * @return
		 **/
		public function setDefaultValue()
			{
				$this->setFormField('block', '');
				$this->setFormField('about', '');
				$this->setFormField('source', '');
				$this->setFormField('start_date', '');
				$this->setFormField('end_date', '');
				$this->setFormField('status', 'toactivate');
				$this->setFormField('add_type', 'General');
				$this->setFormField('allowed_impressions', '');
			}

		/**
		 * Add::populateAdvertisementValues()
		 *
		 * @return
		 **/
		public function populateAdvertisementValues()
			{
				$sql = 'SELECT block, about, source, start_date, end_date, status, add_type,'.
						' allowed_impressions FROM '.$this->CFG['db']['tbl']['advertisement'].' WHERE'.
						' add_id='.$this->dbObj->Param('add_id');

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

				if ($row = $rs->FetchRow())
				    {
				     	$this->setFormField('block', $row['block']);
						$this->setFormField('about', $row['about']);
						$this->setFormField('source', $row['source']);
						$this->setFormField('start_date', $row['start_date']);
						$this->setFormField('end_date', $row['end_date']);
						$this->setFormField('status', $row['status']);
						$this->setFormField('add_type', $row['add_type']);
						$this->setFormField('allowed_impressions', $row['allowed_impressions']);
						return true;
				    }
				return false;
			}

		/**
		 * Add::showAdd()
		 *
		 * @return
		 **/
		public function populateAdd()
			{
				global $smartyObj;
				$data_arr = array();
				$inc = 0;
				$fields_list = array('name as name');
				while($row = $this->fetchResultRecord())
					{
						if(!($uname_arr = $this->getUserDetail('user_id', $row['user_id'])))
							{
								$uname_arr['first_name'] = 'Admin';
								$uname_arr['last_name'] = 'Admin';
								$uname_arr['name'] = 'Admin';
							}
						$row = $row+$uname_arr;
						$data_arr[$inc] = $row;
						$data_arr[$inc]['name'] = getUserMailName($row);
						$data_arr[$inc]['source'] = htmlentitydecode($row['source']);
						$data_arr[$inc]['profile_link']= getMemberUrl($row['user_id'], $row['name']);
						$data_arr[$inc]['edit_link'] = $this->CFG['site']['url'].'admin/manageBanner.php?act=edt&amp;aid='.$row['add_id'].'&amp;start='.$this->getFormField('start').'&amp;block_search='.$this->getFormField('block_search').'&amp;name='.$this->getFormField('name');
						$data_arr[$inc]['preview_onclick'] = 'return Confirmation(\'selMsgPreviewWindow\', \'previewForm\', Array(\'selPreviewBanner\'), Array($(\'selPreview'.$row['add_id'].'\').innerHTML), Array(\'innerHTML\'));';
						$inc++;
					}
				$smartyObj->assign('populateAdds_arr', $data_arr);
			}

		/**
		 * Add::populatePosition()
		 *
		 * @param array $banner_position
		 * @return
		 */
		public function populatePosition($banner_position = array())
			{
				$banner_key = array_keys($banner_position);
				return implode(', ', $banner_key);
			}

		public function chkIsValidBlock($block, $err_tip='')
			{
				global $LANG_LIST_ARR;
				$banner_key = array_keys($LANG_LIST_ARR['banner_list']);
				if(in_array($this->fields_arr[$block], $banner_key))
					return true;
				else
					$this->setFormFieldErrorTip($block, $err_tip);

			}
	}
//<<<<<-------------- Class GroupsFormHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
$Add = new Add();
$Add->setPageBlockNames(array('block_add_advertisement', 'block_list_advertisement', 'block_edit_advertisement', 'block_search'));
//default form fields and values...
$Add->setFormField('aid', '');
$Add->setFormField('act', '');
$Add->setFormField('block', '');
$Add->setFormField('about', '');
$Add->setFormField('source', '');
$Add->setFormField('start_date', '');
$Add->setFormField('end_date', '');
$Add->setFormField('add_type', 'General');
$Add->setFormField('status', 'toactivate');
$Add->setFormField('allowed_impressions', '');
$Add->setFormField('name', '');
$Add->setFormField('block_search', '');
/*********** Page Navigation Start *********/
$Add->setFormField('orderby_field', 'add_id');
$Add->setFormField('orderby', 'DESC');
$Add->setTableNames(array($Add->CFG['db']['tbl']['advertisement']));
$Add->setReturnColumns(array('add_id', 'block', 'about', 'source', 'DATE_FORMAT(start_date, \''.$CFG['mysql_format']['date_time'].'\') AS start_date', 'DATE_FORMAT(end_date, \''.$CFG['mysql_format']['date_time'].'\') AS end_date', 'IF (status=\'activate\', \'Active\', \'Inactive\') AS status', 'add_type', 'DATE_FORMAT(date_added, \''.$CFG['mysql_format']['date_time'].'\') AS date_added', 'allowed_impressions', 'completed_impressions', 'user_id'));
/************ page Navigation stop *************/
$Add->manage_banner_title = $LANG['manage_banner_page_add_title'];

if ($Add->isFormGETed($_GET, 'act'))
	{
		$Add->setPageBlockShow('block_add_advertisement');
	}
	else
	{
		$Add->setPageBlockShow('block_list_advertisement');
		$Add->setPageBlockShow('block_search');
	}

$Add->sanitizeFormInputs($_REQUEST);
if(isDemoSite() AND ($Add->isFormPOSTed($_POST, 'add_submit') OR $Add->isFormPOSTed($_POST, 'update_submit')))
	{
		$Add->setCommonErrorMsg($LANG['no_permission_for_demo_user']);
		$Add->setPageBlockShow('block_msg_form_error');
	}
elseif($Add->isFormPOSTed($_POST, 'add_submit'))
	{
		$Add->chkIsNotEmpty('block', $Add->LANG['err_tip_compulsory']) and $Add->chkIsValidBlock('block', $Add->LANG['err_tip_invalid']);
		$Add->chkIsNotEmpty('source', $Add->LANG['err_tip_compulsory']);
		$Add->chkIsNotEmpty('about', $Add->LANG['err_tip_compulsory']);
		$Add->chkIsNotEmpty('start_date', $Add->LANG['err_tip_compulsory']) and
			$Add->chkIsDateLesserThanNow('start_date', $Add->LANG['manage_banner_err_tip_invalid_date']);
		$Add->chkIsNotEmpty('end_date', $Add->LANG['err_tip_compulsory']) and
			$Add->chkIsDateLesserThanNow('end_date', $Add->LANG['manage_banner_err_tip_invalid_date']);
		(!($Add->getFormFieldErrorTip('start_date') or $Add->getFormFieldErrorTip('end_date')))?($Add->chkIsDateDiff('start_date', 'end_date', $Add->LANG['manage_banner_err_tip_invalid_date_diff'])):('');
		$Add->getFormField('allowed_impressions') and
			$Add->chkIsNumeric('allowed_impressions', $Add->LANG['common_err_tip_numeric']);
		if($Add->isValidFormInputs())
			{
				$Add->insertAdvertisementTable();
				$Add->setAllPageBlocksHide();
				$Add->setPageBlockShow('block_msg_form_success');
				$Add->setCommonSuccessMsg($Add->LANG['manage_banner_success_added']);
				$Add->setPageBlockShow('block_list_advertisement');
				$Add->setPageBlockShow('block_search');
			}
		else
			{
				$Add->setPageBlockShow('block_msg_form_error');
				$Add->setCommonErrorMsg($Add->LANG['common_msg_error_sorry']);
			}
	}
elseif($Add->isFormPOSTed($_POST, 'update_submit'))
	{
		$Add->chkIsNotEmpty('block', $Add->LANG['err_tip_compulsory']) and $Add->chkIsValidBlock('block', $Add->LANG['err_tip_invalid']);
		$Add->chkIsNotEmpty('source', $Add->LANG['err_tip_compulsory']);
		$Add->chkIsNotEmpty('about', $Add->LANG['err_tip_compulsory']);
		$Add->chkIsNotEmpty('start_date', $Add->LANG['err_tip_compulsory']) and
			$Add->chkIsValidDate('start_date', $Add->LANG['manage_banner_err_tip_invalid_date']);
		$Add->chkIsNotEmpty('end_date', $Add->LANG['err_tip_compulsory']) and
			$Add->chkIsValidDate('end_date', $Add->LANG['manage_banner_err_tip_invalid_date']);
		(!($Add->getFormFieldErrorTip('start_date') or $Add->getFormFieldErrorTip('end_date')))?($Add->chkIsDateDiff('start_date', 'end_date', $Add->LANG['manage_banner_err_tip_invalid_date_diff'])):('');
		if($Add->isValidFormInputs())
			{
				if($Add->updateAdvertisementTable())
					{
						$Add->setAllPageBlocksHide();
						$Add->setPageBlockShow('block_msg_form_success');
						$Add->setCommonSuccessMsg($Add->LANG['manage_banner_success_updated']);
						$Add->setPageBlockShow('block_list_advertisement');
						$Add->setPageBlockShow('block_search');
					}
				else
					{
						$Add->setPageBlockShow('block_msg_form_success');
						$Add->setCommonSuccessMsg($Add->LANG['manage_banner_no_changes']);
					}
			}
		else
			{
				$Add->setPageBlockShow('block_msg_form_error');
				$Add->setCommonErrorMsg($Add->LANG['common_msg_error_sorry']);
				$Add->setPageBlockShow('block_edit_advertisement');
				$Add->manage_banner_title = $LANG['manage_banner_page_edit_title'];
			}
	}
else if($Add->isFormPOSTed($_POST, 'cancel_submit'))
	{
		$Add->setDefaultValue();
	}
else if($Add->isFormPOSTed($_POST, 'reset_submit'))
	{
		$Add->setFormField('name', '');
		$Add->setFormField('block_search', '');
			Redirect2URL($CFG['site']['relative_url'].'manageBanner.php#search_banner');
	}
if ($Add->isFormGETed($_GET, 'act'))
    {
     	if($Add->getFormField('act')=='edt')
			{
				if($Add->populateAdvertisementValues())
					{
						$Add->manage_banner_title = $LANG['manage_banner_page_edit_title'];
						$Add->setPageBlockShow('block_edit_advertisement');
					}
			}
    }
if(isDemoSite() AND $Add->isFormPOSTed($_POST, 'act'))
	{
		$Add->setCommonErrorMsg($LANG['no_permission_for_demo_user']);
		$Add->setPageBlockShow('block_msg_form_error');
	}
elseif($Add->isFormPOSTed($_POST, 'act'))
	{
		if($Add->getFormField('act')=='delete')
			{
				if($Add->deleteAdvertisementTable())
					{
						$Add->setPageBlockShow('block_msg_form_success');
						$Add->setCommonSuccessMsg($Add->LANG['manage_banner_success_deleted']);
					}
				else
					{
						$Add->setPageBlockShow('block_msg_form_success');
						$Add->setCommonSuccessMsg($Add->LANG['manage_banner_no_changes']);
					}
			}
		else if($Add->getFormField('act')=='activate')
			{
				if($Add->updateStatusInAdvertisementTable('activate'))
					{
						$Add->setPageBlockShow('block_msg_form_success');
						$Add->setCommonSuccessMsg($Add->LANG['manage_banner_success_activated']);
					}
				else
					{
						$Add->setPageBlockShow('block_msg_form_success');
						$Add->setCommonSuccessMsg($Add->LANG['manage_banner_no_changes']);
					}
			}
		if($Add->getFormField('act')=='toactivate')
			{
				if($Add->updateStatusInAdvertisementTable('toactivate'))
					{
						$Add->setPageBlockShow('block_msg_form_success');
						$Add->setCommonSuccessMsg($Add->LANG['manage_banner_success_toactivated']);
					}
				else
					{
						$Add->setPageBlockShow('block_msg_form_success');
						$Add->setCommonSuccessMsg($Add->LANG['manage_banner_no_changes']);
					}
			}
	}
if($Add->isShowPageBlock('block_list_advertisement'))
	{
		/****** navigtion continue*********/
		$Add->buildSelectQuery();
		$Add->buildConditionQuery();
		$Add->buildSortQuery();
		$Add->buildQuery();
		$Add->executeQuery();

		if(!$Add->isResultsFound())
			{
				$Add->setPageBlockShow('block_msg_form_alert');
				$Add->setPageBlockHide('block_list_advertisement');
				$Add->setCommonAlertMsg($LANG['common_no_records_found']);
			}
	}
//<<<<<-------------------- Code ends----------------------//
//-------------------- Page block templates begins -------------------->>>>>//
$smartyObj->assign('LANG_LIST_ARR', $LANG_LIST_ARR);
$smartyObj->assign('strating_year', date('Y'));
$smartyObj->assign('ending_year', date('Y')+30);
$Add->deleteForm_hidden_arr = array('start', 'aid', 'act');
$Add->selAddAdvertisementForm_hidden_arr = array('start', 'orderby_field', 'orderby');
$Add->selAddAdvertisementForm_hidden_arr1 = array('aid', 'name', 'block_search');
$Add->confrimation_preview_onclick = 'return showPreview();return false';
if ($Add->isShowPageBlock('block_list_advertisement'))
	{
		$Add->populateAdd();
		$smartyObj->assign('smarty_paging_list', $Add->populatePageLinksGET($Add->getFormField('start'), array('name', 'block_search', 'orderby_field', 'orderby')));
		$smartyObj->assign('delete_submit_onclick', 'if(getMultiCheckBoxValue(\'selListAdvertisementForm\', \'check_all\', \''.$LANG['manage_banner_check_atleast_one'].'\')){Confirmation(\'selMsgConfirm\', \'deleteForm\', Array(\'aid\', \'act\', \'confirmation_msg\'), Array(multiCheckValue, \'delete\', \''.nl2br($LANG['manage_banner_delete_confirmation']).'\'), Array(\'value\', \'value\', \'innerHTML\'));}');
		$smartyObj->assign('activate_submit_onclick', 'if(getMultiCheckBoxValue(\'selListAdvertisementForm\', \'check_all\', \''.$LANG['manage_banner_check_atleast_one'].'\')){Confirmation(\'selMsgConfirm\', \'deleteForm\', Array(\'aid\', \'act\', \'confirmation_msg\'), Array(multiCheckValue, \'activate\', \''.nl2br($LANG['manage_banner_activate_confirmation']).'\'), Array(\'value\', \'value\', \'innerHTML\'));}');
		$smartyObj->assign('inactivate_submit_onclick', 'if(getMultiCheckBoxValue(\'selListAdvertisementForm\', \'check_all\', \''.$LANG['manage_banner_check_atleast_one'].'\')){Confirmation(\'selMsgConfirm\', \'deleteForm\', Array(\'aid\', \'act\', \'confirmation_msg\'), Array(multiCheckValue, \'toactivate\', \''.nl2br($LANG['manage_banner_toactivate_confirmation']).'\'), Array(\'value\', \'value\', \'innerHTML\'));}');
	}
//include the header file
$Add->includeHeader();
//include the content of the page
setTemplateFolder('admin/');
$smartyObj->display('manageBanner.tpl');
?>
<script type="text/javascript" language="javascript">
	var block_arr= new Array('selMsgConfirm', 'selCodeForm', 'selMsgPreviewWindow');
	function populateCode(block){
		var codeDetail = "<div><?php echo '{php}getAdvertisement(\'{block}\'){/php}';?></div>";//"
		var codeTitle = "<?php echo $Add->LANG['manage_banner_code_title'];?>";
		var cd = codeDetail.replace('{block}', block);
		var ct = codeTitle.replace('{block}', block);
		Confirmation('selCodeForm', 'codeForm', Array('codeTitle', 'addCode'), Array(ct, cd), Array('innerHTML', 'value'));
		return false;
	}
	var popupWindow = function(){
		var additional = '';
		if(arguments[1])
			{
				additional += ',width='+arguments[1];
			}

		if(arguments[2])
			{
				additional += ',height='+arguments[2];
			}

		window.open (arguments[0], "","status=0,toolbar=0,resizable=0,scrollbars=1"+additional);
		return false;
	}
	var showPreview = function(){

          var sourceBanner = $('source').value;
          if(sourceBanner == '')
               sourceBanner = '<?php echo $LANG['manage_banner_no_source'];?>';

          Confirmation('selMsgPreviewWindow', 'previewForm', Array('selPreviewBanner'), Array(sourceBanner), Array('innerHTML'));
	}
</script>
<?php
//<<<<<-------------------- Page block templates ends -------------------//
$Add->includeFooter();
?>