<?php

	require_once(dirname(__FILE__).'/class.adminview.php');
	require_once(dirname(__FILE__).'/../../../lib/api/class.customfields.php');

	class AKB_CUSTOMFIELDS extends AdminView
	{
		var $defaultTableSort = "lastupdated";

		/**
		* AKB_CUSTOMFIELDS
		* Constructor for the class
		*
		* @return void
		*/
		function AKB_CUSTOMFIELDS() {

		}
		
		function HandlePage() {
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('question', 'edit')
			&& !$_SESSION['user']->verify('question', 'delete')
			&& !$_SESSION['user']->verify('question', 'approve')
			&& !$_SESSION['user']->verify('question', 'review')) {
				$this->NoPermission();
				return;			
			}

			if (isset($_GET['ToDo'])) {
				switch ($_GET['ToDo']) {
					case "viewCustomFields":
						$this->ShowCustomFieldList();

						break;
						
					case "createCustomField":
					case "editCustomField":
						$cfid = (isset($_GET['cfid'])) ? $cfid = (int)$_GET['cfid'] : 0;
						
						$this->createEditCustomField($cfid);
						break;
					
					case "saveCustomField":
						$cfid = (isset($_POST['cfid'])) ? $cfid = (int)$_POST['cfid'] : 0;
						
						$message = "";
						if (!$this->saveCustomField($cfid)) {
							$message = GetLang('CustomFieldSavedNotOK');
							$type = MSG_WARNING;
						} else {
							$message = GetLang('CustomFieldSavedOK');
							$type = MSG_SUCCESS;
						}
						
						$this->ShowCustomFieldList($message,$type);
						
						break;
						
					case "deleteCustomField":
						$cfid = (isset($_GET['cfid'])) ? $cfid = (int)$_GET['cfid'] : 0;					
						
						$message = "";
						if ($cfid > 0) {
							if (!$this->deleteCustomField($cfid)) {
								$message = GetLang('CustomFieldDeleteNotOK');
								$type = MSG_WARNING;
							} else {
								$message = GetLang('CustomFieldDeleteOK');
								$type = MSG_SUCCESS;
							}
						}
						
						$this->ShowCustomFieldList($message,$type);

						break;
						

					default:
						if (isset($_POST['bulkaction'])) {
							$this->BulkAction();
						}

						$this->ShowCustomFieldList();
				}

			}
		}
		
		function createEditCustomField($cfId=0) {
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('question', 'edit')
			&& !$_SESSION['user']->verify('question', 'delete')
			&& !$_SESSION['user']->verify('question', 'approve')) {
				$this->NoPermission();
				return;
			}
			
			//Set the header.
			if ((int)$cfId > 0) {
				$GLOBALS['CustomFieldHeading'] = GetLang("EditCF");
			} else {
				$GLOBALS['CustomFieldHeading'] = GetLang("CreateCF");
			}
			
			//Set the breadcrumbs.
			$GLOBALS['BreadcrumEntries'] = array(GetLang("Home") => "index.php", GetLang("ManageCustomFields") => "index.php?ToDo=viewCustomFields", $GLOBALS['CustomFieldHeading'] => "");
			
			//Create the object
			$cfObj = new API_CUSTOMFIELD($cfId,true);
			
			//Set the data
			$GLOBALS['CustomFieldName'] = $cfObj->name;
			$GLOBALS['cfid'] = $cfObj->customfieldid;
			
			//We need to populate some extra fields if its of type 'multi_check'
			if ($cfObj->type == CF_TYPE__MULTI_CHECK) {
				$GLOBALS['multicheck_checked'] = "checked=\"checked\"";
				
				$existingCFDataStr = "";
				foreach ($cfObj->customFieldDataArray as $cfDataObj) {
					$GLOBALS['cfdid'] = $cfDataObj->customfield_dataid;
					$GLOBALS['cfdata'] = $cfDataObj->data;
					
					$existingCFDataStr .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet("CustomFieldsExisting");
				}
				
				$GLOBALS['NoCFData'] = "";
				if ($existingCFDataStr != "") {
					$GLOBALS['NoCFData'] = "<br />".GetLang('AddNewCFData')."<br />";
				}
				
				$GLOBALS['ExistingCFData'] = $existingCFDataStr;
			}
			
			//Show the template
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('customfields.form');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}
		
		function saveCustomField($cfid) {
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('question', 'edit')
			&& !$_SESSION['user']->verify('question', 'delete')
			&& !$_SESSION['user']->verify('question', 'approve')) {
				$this->NoPermission();
				return;
			}
			
			$name = $_POST['name'];
			$type = $_POST['type'];
			
			$customfield_string = "";
			if ($type == CF_TYPE__MULTI_CHECK) {
				$customfield_string = $_POST['addMultiCFCheck'];
			}
			
			if ((int)$cfid > 0) {
				return custom_fields_helper::update_custom_field($cfid,$name,$type,$customfield_string,@$_POST['cfdataArray'],@$_POST['deletedArray']);				
			} else {
				return custom_fields_helper::create_custom_field($name,$type,$customfield_string);
			}
		}
		
		function deleteCustomField($cfid) {
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('question', 'edit')
			&& !$_SESSION['user']->verify('question', 'delete')
			&& !$_SESSION['user']->verify('question', 'approve')) {
				$this->NoPermission();
				return;
			}
			
			return custom_fields_helper::delete_custom_field($cfid);
		}
		
		function ShowCustomFieldList($message="",$messageType=MSG_SUCCESS) {
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('question', 'edit')
			&& !$_SESSION['user']->verify('question', 'delete')
			&& !$_SESSION['user']->verify('question', 'approve')) {
				$this->NoPermission();
				return;
			}
			
			$GLOBALS['BreadcrumEntries'] = array(GetLang("Home") => "index.php", GetLang("ManageCustomFields") => "");
			
			if (trim($message) != "") {
				$GLOBALS['Message'] .= MessageBox($message, $messageType);
			}
			
			
			$page = 1;
			$countQuery = API_CUSTOMFIELD::readForManageTableCountQuery();
			$this->SetupPagination($countQuery,$page,AKB_QUESTION_PER_PAGE);
			
			if ($this->numRecords == 0) {
				$GLOBALS['Message'] .= MessageBox(sprintf(GetLang('NoCustomFields'), GetLang('CreateCustomField')), MSG_SUCCESS);
			}
			
			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('customfields.manage');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}
		
		function ShowCustomFieldsListRemote() {
			//Set pagination variables.
			$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;

			$sortVars = array("customfieldid","name","type");
			$sortArray = $this->SetupSortingParams($sortVars,"ShowCustomFieldsListRemote",$page);

			//Setup pagination
			$field = "lastupdated";
			if (isset($_GET['field'])) {
				$field = $_GET['field'];
			}

			$direction = "d";
			if (isset($_GET['direction'])) {
				$direction = $_GET['direction'];
			}

			$countQuery = API_CUSTOMFIELD::readForManageTableCountQuery();
			
			$this->SetupPaginationLink("ShowCustomFieldsListRemote",$direction,$field);
			$this->SetupPagination($countQuery,$page,AKB_QUESTION_PER_PAGE);

			if ($this->numRecords == 0) {
				die();
			}

			//Setup the table object.
			$adminTable = new CFManage_Table();
			$adminTable->rsData = API_CUSTOMFIELD::readForManageTable($this->paginationRowStart,AKB_QUESTION_PER_PAGE,$field,$direction);
			$adminTable->sortArray = $sortArray;

			echo $adminTable->ReturnTable();
			die();
		}
	}
	
	class CFManage_Table extends AKB_AdminTable {
		function CFManage_Table() {
			parent::AKB_AdminTable();
		
			$GLOBALS['TableIconImagePath'] = "images/customfield.gif";
			
			//Set the prepend data snippets
			$this->prependDataTemplate['CHECKBOX'] 	= "admintable.cell.selector.check";
			$this->prependDataTemplate['ICON'] 		= "admintable.cell.selector.icon";			
			
			//Setup the headings
			$this->headingArray['customfieldid']	= GetLang("CustomFieldID");
			$this->headingArray['name']				= GetLang("CustomFieldName");
			$this->headingArray['type']				= GetLang("Type");
			$this->headingArray['data_concat']		= GetLang("PredefinedData");
			$this->headingArray['action']			= GetLang("Action");
			
			$this->prependDataID = "customfieldid";
			$this->tableIdent = "ShowCustomFieldsListRemote";
			
			//Add specific callbacks to manipulate these fields
			$this->addCallback("type",array($this,"ReturnTypeCell"),array("__type__"));
			$this->addCallback("data_concat",array($this,"ReturnDataCell"),array("__data_concat__"));
			$this->addCallback("action",array($this,"ReturnActionCell"),array("__customfieldid__"));
		}
		
		function ReturnTable() {
			return parent::ReturnTable();
		}
		
		function ReturnTypeCell($type) {
			return GetLang($type);
		}
		
		function ReturnDataCell($data) {
			return (trim($data)) ? $data: GetLang("NA");
		}		

		function ReturnActionCell($customFieldID) {
			return "<a href=\"index.php?ToDo=editCustomField&cfid=".(int)$customFieldID."\">".GetLang("Edit")."</a>&nbsp;&nbsp;<a href=\"#\" onclick=\"javascript: deleteConfirm(".(int)$customFieldID.");\">".GetLang("Delete")."</a>";
		}
	}

?>