<?php
/**
 * Manage Group Category
 *
 * PHP version 5.0
 *
 * @category	###Anova###
 * @package		###Manage blog category###
 * @author 		karthiselvam_75ag08
 * @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
 **/
/**
 * configurations
*/
require_once('../../common/configs/config.inc.php');
$CFG['lang']['include_files'][] = 'languages/%s/'.$CFG['admin']['index']['blog_module'].'/admin/manageBlogCategory.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';
$CFG['mods']['include_files'][] = 'common/classes/class_Image.lib.php';
//compulsory
$CFG['site']['is_module_page']='blog';
$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');
//--------------class BlogCategoryFormHandler--------------->>>//
class BlogCategoryFormHandler extends AnovaHandler
	{
		public $category_details_arr;
		public $category_id;

		/**
		 * BlogUpload::setIHObject()
		 *
		 * @param $imObj
		 * @return
		 **/
		public function setIHObject($imObj)
			{
				$this->imageObj = $imObj;
			}

		/**
		 * set the condition
		 *
		 * @access public
		 * @return void
		 **/
		public function buildConditionQuery($condition='')
			{
				$this->sql_condition = $condition;
			}

		/**
		 * To sort the query
		 *
		 * @access public
		 * @return void
		 **/
		public function checkSortQuery($field, $sort='asc')
			{
				if(!($this->sql_sort))
				{
					$this->sql_sort = $field . ' ' . $sort;
				}
			}

		/**
		 * BlogUpload::storeImagesTempServer()
		 *
		 * @param $uploadUrl
		 * @param $extern
		 * @return
		 **/
		public function storeImagesTempServer($uploadUrl, $extern)
			{
				//GET LARGE IMAGE
				@chmod($uploadUrl.'.'.$extern, 0777);
				if($this->CFG['admin']['blogs']['category_height'] or $this->CFG['admin']['blogs']['category_width'])
					{
						$this->imageObj->resize($this->CFG['admin']['blogs']['category_width'], $this->CFG['admin']['blogs']['category_height'], '-');
						$this->imageObj->output_resized($uploadUrl.'.'.$extern, strtoupper($extern));
					}
					else
						{
							$this->imageObj->output_original($uploadUrl.'.'.$extern, strtoupper($extern));
						}
			}

		/**
		 * To check the blog_categroy id is valid or not
		 *
		 * @param $category_id moods id
		 * @param $err_tip error message
		 * @access public
		 * @return void
		 **/
		public function isValidCategoryId($category_id, $err_tip='')
			{
				$sql = 'SELECT blog_category_id, blog_category_description'.
						', blog_category_name, blog_category_status, date_added'.
						' FROM '.$this->CFG['db']['tbl']['blog_category'].
						' WHERE blog_category_id = '.$this->dbObj->Param($this->fields_arr[$category_id]);

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

				if ($this->category_details_arr = $rs->FetchRow())
					{
						return true;
				    }
				$this->setCommonErrorMsg($err_tip);
				return false;
			}

		/**
		 * To check if selected category have blogs
		 *
		 * @access public
		 * @return void
		 **/
		public function chkBlogExists($category_ids)
			{
				$sql = 'SELECT count( g.blog_id ) AS cat_count, blog_category_id'.
						' FROM '.$this->CFG['db']['tbl']['blogs'].' AS g'.
						' WHERE blog_category_id IN ( '.$category_ids.' )'.
						' AND status!=\'Deleted\''.
						' GROUP BY blog_category_id';

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

				if ($rs->PO_RecordCount())
					return true;
				return false;
			}

		/**
		 * To delete the given category id
		 *
		 * @access public
		 * @return void
		 **/
		public function deleteSelectedCategories()
			{
				$category_ids = $this->fields_arr['category_ids'];
				if ($this->chkBlogExists($category_ids))
					{
						Redirect2URL($CFG['site']['relative_url'].'manageBlogCategory.php?&msg=6');
				    }
				$sql = 'DELETE FROM '.$this->CFG['db']['tbl']['blog_category'].
						' WHERE blog_category_id IN ('.$category_ids.') ';

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

				return false;

			}

		/**
		 * To check if the category exists already
		 *
		 * @param string $category
		 * @param string $err_tip
		 * @access public
		 * @return void
		 **/
		public function chkCategoryExits($category, $err_tip='')
			{
				$sql = 'SELECT COUNT(blog_category_id) AS cat_cnt FROM '.$this->CFG['db']['tbl']['blog_category'].
						' WHERE blog_category_name = '.$this->dbObj->Param($this->fields_arr[$category]);
				$fields_value_arr[] = $this->fields_arr[$category];
				if ($this->fields_arr['category_id'])
					{
						$sql .= ' AND blog_category_id != '.$this->dbObj->Param($this->fields_arr['category_id']);
						$fields_value_arr[] = $this->fields_arr['category_id'];
				    }

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

				$row = $rs->FetchRow();
				if(!$row['cat_cnt'])
					{
						return false;
					}
				$this->fields_err_tip_arr['category'] = $err_tip;
				$this->setCommonErrorMsg($err_tip);
				return false;
			}

		/**
		 * To create blog category
		 *
		 * @param $category_table moods_icons table
		 * @access public
		 * @return void
		 **/
		public function createCategory($category_table)
			{
				if ($this->fields_arr['category_id'])
					{
						$sql = 'UPDATE '.$category_table.
								' SET blog_category_name = '.$this->dbObj->Param($this->fields_arr['category']).
								', blog_category_description = '.$this->dbObj->Param($this->fields_arr['category_description']).
								', blog_category_status = '.$this->dbObj->Param($this->fields_arr['status']).
								' WHERE blog_category_id = '.$this->dbObj->Param($this->fields_arr['category_id']);
						$fields_value_arr = array($this->fields_arr['category'],
												$this->fields_arr['category_description'],
												$this->fields_arr['status'],
												$this->fields_arr['category_id']);

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

						$this->category_id = $this->fields_arr['category_id'];
						return true;
				    }
					else
						{
							$sql = 'INSERT INTO '.$category_table.
									' SET blog_category_name = '.$this->dbObj->Param($this->fields_arr['category']).
									', blog_category_description = '.$this->dbObj->Param($this->fields_arr['category_description']).
									', blog_category_status = '.$this->dbObj->Param($this->fields_arr['status']).
									', date_added = NOW()';
							$fields_value_arr = array($this->fields_arr['category'],
														$this->fields_arr['category_description'],
														$this->fields_arr['status']);

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

							$this->category_id = $this->dbObj->Insert_ID();
							return true;
						}
			}

		/**
		 * To get blog count of the category
		 *
		 * @access public
		 * @return void
		 **/
		public function getBlogCount($category_id)
			{
				$sql = 'SELECT COUNT(g.blog_id) AS cat_count'.
						' FROM '.$this->CFG['db']['tbl']['blogs'].' AS g'.
						' WHERE blog_category_id = '.$this->dbObj->Param($category_id);

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

				$row = $rs->FetchRow();
				return $row['cat_count'];
			}

		/**
		 * To display the categories
		 *
		 * @access public
		 * @return void
		 **/
		public function showCategories()
			{
				$this->showCategories_arr	=	array();
				$this->showCategories_arr['RecordCount']	=	1;
				if(!$this->isResultsFound())
					{
						$this->showCategories_arr['RecordCount']	=	0;
						return ;
					}
				$this->showCategories_arr['row']	=	array();
				$inc=0;
				while($row = $this->fetchResultRecord())
					{
						$this->showCategories_arr['row'][$inc]['record']	=	$row;
						$this->showCategories_arr['row'][$inc]['chk']	=	'';
						if((is_array($this->fields_arr['category_ids'])) && (in_array($row['blog_category_id'], $this->fields_arr['category_ids'])))
							$this->showCategories_arr['row'][$inc]['chk']	=	"CHECKED";
						$this->showCategories_arr['row'][$inc]['manageBlogCategory_url']	=	'manageBlogCategory.php?category_id='.$row['blog_category_id'].'&start='.$this->fields_arr['start'];
						$inc++;
					}
				$this->showCategories_arr['RecorgetMultiCheckBoxValuedCount']	=	'if(getMultiCheckBoxValue(\'selFormCategory\', \'check_all\', \''.$this->LANG['blogcategory_err_tip_select_category'].'\')){ if(getAction()) Confirmation(\'selMsgConfirm\', \'msgConfirmform\', Array(\'category_ids\', \'action\', \'confirmMessage\'), Array(multiCheckValue, document.selFormCategory.blog_options.value, \''.$this->LANG['blogcategory_confirm_message'].'\'), Array(\'value\', \'value\', \'innerHTML\'));}';
				return 	$this->showCategories_arr;
			}

		/**
		 * BlogUpload::chkFileNmaeIsNotEmpty()
		 *
		 * @param string $field_name
		 * @param string $err_tip
		 * @return
		 **/
		public function chkFileNmaeIsNotEmpty($field_name, $err_tip = '')
			{
				if(!$_FILES[$field_name]['name'])
					{
						$this->setFormFieldErrorTip($field_name,$err_tip);
						return false;
					}
				return true;
			}

		/**
		 * BlogUpload::chkValidFileType()
		 *
		 * @param $field_name
		 * @param string $err_tip
		 * @return
		 **/
		public function chkValidFileType($field_name, $err_tip = '')
			{
				$extern = strtolower(substr($_FILES[$field_name]['name'], strrpos($_FILES[$field_name]['name'], '.')+1));
				if (!in_array($extern, $this->CFG['admin']['blogs']['category_image_format_arr']))
					{
						$this->fields_err_tip_arr[$field_name] = $err_tip;
						return false;
					}
				return true;
			}

		/**
		 * BlogUpload::chkValideFileSize()
		 *
		 * @param $field_name
		 * @param string $err_tip
		 * @return
		 **/
		public function chkValideFileSize($field_name, $err_tip='')
			{
				$max_size = $this->CFG['admin']['blogs']['category_image_max_size'] * 1024;
				if ($_FILES[$field_name]['size'] > $max_size)
					{
						$this->fields_err_tip_arr[$field_name] = $err_tip;
						return false;
					}
				return true;
			}

		/**
		 * BlogUpload::chkErrorInFile()
		 *
		 * @param $field_name
		 * @param string $err_tip
		 * @return
		 **/
		public function chkErrorInFile($field_name, $err_tip='')
			{
				if($_FILES[$field_name]['error'])
					{
						$this->fields_err_tip_arr[$field_name] = $err_tip;
						return false;
					}
				return true;
			}

		/**
		 * BlogCategoryFormHandler::resetFieldsArray()
		 *
		 * @return
		 */
		public function resetFieldsArray()
			{
				$this->setFormField('category', '');
				$this->setFormField('category_image', '');
				$this->setFormField('category_id', '');
				$this->setFormField('category_description', '');
				$this->setFormField('category_image_ext', '');
				$this->setFormField('status', 'Yes');
				$this->setFormField('category_ids', array());
				$this->setFormField('action', '');
			}

		/**
		 * BlogCategoryFormHandler::chkIsEditMode()
		 *
		 * @return
		 */
		public function chkIsEditMode()
			{
				if($this->fields_arr['category_id'])
					return true;
				return false;
			}

		/**
		 * BlogCategoryFormHandler::changeStatus()
		 *
		 * @param mixed $status
		 * @return
		 */
		public function changeStatus($status)
			{
				$category_ids = $this->fields_arr['category_ids'];
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['blog_category'].' SET'.
						' blog_category_status='.$this->dbObj->Param('blog_category_status').
						' WHERE blog_category_id IN('.$category_ids.')';

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

				return true;
			}
	}
//<<<<<<<--------------class BlogCategoryFormHandler---------------//
//--------------------Code begins-------------->>>>>//
$category = new BlogCategoryFormHandler();
$category->left_navigation_div = 'blogBlog';
$category->setPageBlockNames(array('msg_cannot_create', 'form_create_category', 'form_show_category', 'page_nav', 'form_confirm'));
$category->setAllPageBlocksHide();
//default form fields and values...
$category->resetFieldsArray();
$category->setFormField('orderby_field', 'blog_category_name');
$category->setFormField('orderby', 'ASC');
$category->setFormField('msg','');
$category->setFormField('numpg',0);
$category->setFormField('start',0);
$category->setFormField('task','');
$category->setFormField('prev_numpg',0);//To retain the last numpg
/*************Start navigation******/
//fetch number of records show in the result--numpg
$condition = '';
$category->numpg = $CFG['data_tbl']['numpg'];
$category->setFormField('start', 0);
$category->setFormField('numpg', $CFG['data_tbl']['numpg']);
//$category->setFormField('numpg', 2);
$category->setMinRecordSelectLimit($CFG['data_tbl']['min_record_select_limit']);
$category->setMaxRecordSelectLimit($CFG['data_tbl']['max_record_select_limit']);
$category->setNumPerPageListArr($CFG['data_tbl']['numperpage_list_arr']);
//Set tables and fields to return
$category->setTableNames(array());
$category->setReturnColumns(array());
$category->sanitizeFormInputs($_REQUEST);
/*************End navigation******/
if ($category->isFormPOSTed($_POST, 'confirm_action'))
	{
		$category->chkIsNotEmpty('category_ids', $LANG['err_tip_compulsory'])or $category->setCommonErrorMsg($LANG['blogcategory_err_tip_select_category']);
		if($category->isValidFormInputs())
			{
				switch($category->getFormField('action'))
					{
						case 'Delete':
							$category->deleteSelectedCategories();
							Redirect2URL($CFG['site']['relative_url'].'manageBlogCategory.php?&msg=3');
							break;

						case 'Enable':
							$category->changeStatus('Yes');
							Redirect2URL($CFG['site']['relative_url'].'manageBlogCategory.php?&msg=1');
							break;

						case 'Disable':
							$category->changeStatus('No');
							Redirect2URL($CFG['site']['relative_url'].'manageBlogCategory.php?&msg=2');
							break;
					}
			}
		$category->setAllPageBlocksHide();
		if ($category->isValidFormInputs())
			{
				$category->setPageBlockShow('block_msg_form_success');
				$category->resetFieldsArray();
			}
			else
				{
					$category->setPageBlockShow('block_msg_form_error');
				}
	}
if ($category->isFormPOSTed($_POST, 'category_submit'))
	{
		$category->chkIsNotEmpty('category', $LANG['err_tip_compulsory'])and
			$category->chkCategoryExits('category', $LANG['blogcategory_err_tip_alreay_exists']);
		$category->chkIsNotEmpty('status', $LANG['err_tip_compulsory']);
		$category->getFormField('category_id')and
			$category->chkIsNotEmpty('category_id', $LANG['err_tip_compulsory'])and
				$category->chkIsNumeric('category_id', $LANG['blogcategory_err_tip_invalid_category_id'])and
					$category->isValidCategoryId('category_id', $LANG['blogcategory_err_tip_invalid_category_id']);
		$category->isValidFormInputs()and
			$category->createCategory($CFG['db']['tbl']['blog_category']);
		if ($category->isValidFormInputs())
			{
				$category->setPageBlockShow('block_msg_form_success');
				if($category->getFormField('category_id'))
					Redirect2URL($CFG['site']['relative_url'].'manageBlogCategory.php?&msg=4');
				else
					Redirect2URL($CFG['site']['relative_url'].'manageBlogCategory.php?&msg=5');

				$category->resetFieldsArray();
			}
			else
				{
					$category->setAllPageBlocksHide();
					$category->setPageBlockShow('block_msg_form_error');
					$category->setFormField('category_id', $category->category_details_arr['blog_category_id']);
				}
	}
else if($category->isFormPOSTed($_POST, 'category_cancel') || $category->isFormPOSTed($_POST, 'category_add_cancel'))
	{
		Redirect2URL($CFG['site']['relative_url'].'manageBlogCategory.php');
		$category->resetFieldsArray();
	}

if ($category->isFormGETed($_GET, 'category_id'))
	{
		$category->chkIsNotEmpty('category_id', $LANG['err_tip_compulsory'])and
			$category->chkIsNumeric('category_id', $LANG['blogcategory_err_tip_invalid_category_id'])and
				$category->isValidCategoryId('category_id', $LANG['blogcategory_err_tip_invalid_category_id']);
		if ($category->isValidFormInputs())
			{
				$category->setAllPageBlocksHide();
				$category->setFormField('category_id', $category->category_details_arr['blog_category_id']);
				$category->setFormField('category', stripslashes($category->category_details_arr['blog_category_name']));
				$category->setFormField('status', $category->category_details_arr['blog_category_status']);
			}
		else
			{
				$category->setAllPageBlocksHide();
				$category->setFormField('start', 0);
				$category->setPageBlockShow('block_msg_form_error');
			}
	}
if ($category->isFormGETed($_GET, 'msg') and $category->isValidFormInputs())
	{
		switch($category->getFormField('msg'))
			{
				case '1':
					$LANG['blogcategory_success_message'] = $LANG['success_enable_msg'];
					$category->setPageBlockShow('block_msg_form_success');
					$category->setCommonSuccessMsg($LANG['blogcategory_success_message']);
					$category->resetFieldsArray();
					break;

				case '2':
					$LANG['blogcategory_success_message'] = $LANG['success_disable_msg'];
					$category->setPageBlockShow('block_msg_form_success');
					$category->setCommonSuccessMsg($LANG['blogcategory_success_message']);
					$category->resetFieldsArray();
					break;

				case '3':
					$category->setPageBlockShow('block_msg_form_success');
					$category->setCommonSuccessMsg($LANG['blogcategory_success_message']);
					$category->resetFieldsArray();
					break;

				case '4':
					$category->setPageBlockShow('block_msg_form_success');
					$category->setCommonSuccessMsg($LANG['blogcategory_success_edit_message']);
					$category->resetFieldsArray();
					break;

				case '5':
					$LANG['blogcategory_success_message'] = $LANG['blogcategory_success_add_message'];
					$category->setPageBlockShow('block_msg_form_success');
					$category->setCommonSuccessMsg($LANG['blogcategory_success_message']);
					$category->resetFieldsArray();
					break;

			   case '6':
			  		$category->setPageBlockShow('block_msg_form_error');
					$category->setCommonErrorMsg($LANG['blogcategory_err_tip_have_blog']);
					$category->resetFieldsArray();
					break;
			}
	}
/*************Start navigation******/
$category->setTableNames(array($CFG['db']['tbl']['blog_category'].' AS gc'));
$category->setReturnColumns(array('gc.blog_category_id', 'gc.blog_category_description', 'gc.blog_category_name', 'IF(gc.blog_category_status=\'Yes\', \''.$LANG['common_yes_option'].'\', \''.$LANG['common_no_option'].'\') AS blog_category_status', 'DATE_FORMAT(gc.date_added, \''.$CFG['format']['date'].'\') as date_added'));
//Condition of the query
$condition = '';
$category->buildSelectQuery();
$category->buildConditionQuery($condition);
$category->buildSortQuery();
$category->checkSortQuery($category->getFormField('orderby_field'), $category->getFormField('orderby'));
$category->buildQuery();
//$category->printQuery();
$category->executeQuery();
if ($category->isResultsFound())
	{
		$category->setPageBlockShow('page_nav');
	}
/*************End navigation******/
$category->setPageBlockShow('form_show_category');
if($category->getFormField('task')== 'add' || $category->getFormField('category_id'))
	{
		$category->setAllPageBlocksHide();
		$category->LANG['blogcategory_title'] = $LANG['blogcategory_add'];
		if ($category->getFormField('category_id'))
			$category->LANG['blogcategory_title'] = $LANG['blogcategory_edit'];
		$category->setPageBlockShow('form_create_category');
	}
//<<<<--------------------Code Ends----------------------//
//--------------------Page block templates begins-------------------->>>>>//
if ($category->isShowPageBlock('form_show_category'))
	{
		$category->form_show_category['msgConfirmForm_hidden_arr']	=	array('start', 'orderby_field', 'orderby');
		$smartyObj->assign('smarty_paging_list', $category->populatePageLinksGET($category->getFormField('start')));
		$category->populateHidden(array('start'));
		$category->form_show_category['showCategories']	=	$category->showCategories();
	}
//include the header file
$category->includeHeader();
//include the content of the page
setTemplateFolder('admin/', $CFG['admin']['index']['blog_module']);
$smartyObj->display('manageBlogCategory.tpl');
//includ the footer of the page
?>
<script language="javascript" type="text/javascript">
	var block_arr= new Array('selMsgConfirm');
	var replace_url = '<?php echo $CFG['site']['url'];?>login.php';
	var please_select_action = '<?php echo $LANG['select_the_action'];?>';
	function getAction()
		{
			var act_value = document.selFormCategory.blog_options.value;
			if(act_value)
				{
					return true;
				}
			else{
					alert_manual(please_select_action);
					return false;
				}
		}
</script>
<?php
//<<<<<<--------------------Page block templates Ends--------------------//
$category->includeFooter();
?>