<?php

require_once dirname(dirname(dirname(__FILE__))) . '/class/core/ActionBase.class.php';
require_once dirname(dirname(dirname(__FILE__))) . '/class/core/Item.class.php';
require_once dirname(dirname(dirname(__FILE__))) . '/class/bean/ItemFieldDetailBean.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/Enum.class.php';

class Xoonips_PolicyQuickSearchAction extends Xoonips_ActionBase {

	protected function doInit(&$request, &$response) {

		// title
		$title = _AM_XOONIPS_POLICY_QUICKSEARCH_LIST_TITLE;

		// breadcrumbs
		$breadcrumbs = $this->setBreadcrumbs(true);
		$token_ticket = $this->createToken($this->modulePrefix('admin_policy_quicksearch_default') );

		$searchBean = Xoonips_BeanFactory::getBean('ItemTypeSearchConditionBean', $this->dirname, $this->trustDirname);

		// get common viewdata
		$viewData = array();

		$viewData['token_ticket'] = $token_ticket;
		$viewData['breadcrumbs'] = $breadcrumbs;
		$viewData['title'] = $title;
		$viewData['quicksearch_list'] = $searchBean->select();
		$viewData['dirname'] = $this->dirname;

		$response->setViewData($viewData);
		$response->setForward('init_success');
		return true;
	}

	protected function doEdit(&$request, &$response) {

		// title
		$title = _AM_XOONIPS_POLICY_QUICKSEARCH_EDIT_TITLE;
		$description = _AM_XOONIPS_POLICY_QUICKSEARCH_EDIT_DESC;

		// breadcrumbs
		$breadcrumbs = $this->setBreadcrumbs(false);

		$op = $request->getParameter('op');
		$mode = $request->getParameter('mode');
		if (is_null($mode)) {
			// mode 1:edit 2:delete
			$mode = 1;
		}
		$cond_id = $request->getParameter('condition_id');
		$cond_name = $request->getParameter('condition_name');

		// get search condition
		$conditionBean = Xoonips_BeanFactory::getBean('ItemTypeSearchConditionBean', $this->dirname, $this->trustDirname);
		$conditions = $conditionBean->select();
		foreach ($conditions as $cond) {
			if ($cond_id == $cond['condition_id']) {
				$cond_name = $cond['title'];
				break;
			}
		}

		// get itemtype block
		$itemtypeBean = Xoonips_BeanFactory::getBean('ItemTypeBean', $this->dirname, $this->trustDirname);
		$itemtypes = $itemtypeBean->getItemTypeList();
		$cond_blocks = array();
		$int = 1;
		foreach ($itemtypes as $itemtype) {
			$block = $this->getSearchConditionBlock($int, $itemtype, $cond_id, $op);
			if ($mode == 1 || $block['checked'] != '') {
				$cond_blocks[] = $block;
			}
			$int++;
		}

		// token ticket
		$token_ticket = $this->createToken($this->modulePrefix('admin_policy_quicksearch_default'));

		// get common viewdata
		$viewData = array();
		$viewData['mode'] = $mode;
		$viewData['condition_id'] = $cond_id;
		$viewData['condition_name'] = $cond_name;
		$viewData['cond_blocks'] = $cond_blocks;
		$viewData['token_ticket'] = $token_ticket;
		$viewData['breadcrumbs'] = $breadcrumbs;
		$viewData['title'] = $title;
		$viewData['description'] = $description;
		$viewData['dirname'] = $this->dirname;

		$response->setViewData($viewData);
		$response->setForward('edit_success');

		return true;
	}

	protected function doSave(&$request, &$response) {
		if (!$this->validateToken($this->modulePrefix('admin_policy_quicksearch_default'))) {
			$response->setSystemError('Ticket error');
			return false;
		}

		// title
		$title = _AM_XOONIPS_POLICY_QUICKSEARCH_EDIT_TITLE;
		$description = _AM_XOONIPS_POLICY_QUICKSEARCH_EDIT_DESC;

		// breadcrumbs
		$breadcrumbs = $this->setBreadcrumbs(false);

		$request = new Xoonips_Request();
		$op = $request->getParameter('op');
		$cond_id = $request->getParameter('condition_id');
		$cond_name = $request->getParameter('condition_name');

		// get search condition
		$conditionBean = Xoonips_BeanFactory::getBean('ItemTypeSearchConditionBean', $this->dirname, $this->trustDirname);
		$conditions = $conditionBean->select();
		$condlist = array(array('condition_id' => '0', 'title '=> '-------------'));
		foreach ($conditions as $cond) {
			$condition['cond_id'] = $cond['condition_id'];
			$condition['title'] = $cond['title'];
			$condition['selected'] = ($cond['condition_id'] == $cond_id) ? 'selected="selected"' : '';
			$condlist[] = $condition;
		}

		// get itemtype block
		$itemtypeBean = Xoonips_BeanFactory::getBean('ItemTypeBean', $this->dirname, $this->trustDirname);
		$itemtypes = $itemtypeBean->getItemTypeList();
		$cond_blocks = array();
		$int = 1;
		foreach ($itemtypes as $itemtype) {
			$cond_blocks[] = $this->getSearchConditionBlock($int, $itemtype, $cond_id, $op);
			$int++;
		}

		// do check
		$errors = new Xoonips_Errors();
		$parameters = array();
		$parameters[] = _AM_XOONIPS_POLICY_QUICKSEARCH_ITEM;
		if (trim($cond_name) == '') {
			$errors->addError('_AM_XOONIPS_ERROR_REQUIRED', '', $parameters);
		}
		if (strlen($cond_name) > 255) {
			$parameters[] = 255;
			$errors->addError('_AM_XOONIPS_ERROR_MAXLENGTH', '', $parameters);
		}
		// uppdate
		if (!empty($cond_id)) {
			$condInfo = $conditionBean->select($cond_id);
			if (count($condInfo) === 0) {
				$errors->addError('_AM_XOONIPS_ERROR_ALREADY_DELETED', '', $parameters);
			} elseif ($condInfo[0]['title'] != $cond_name && count($conditionBean->selectByTitle($cond_name)) > 0) {
				$errors->addError('_AM_XOONIPS_ERROR_DUPLICATE_MSG', '', $parameters);
			}
		// add
		} else {
			if (count($conditionBean->selectByTitle($cond_name)) > 0) {
				$errors->addError('_AM_XOONIPS_ERROR_DUPLICATE_MSG', '', $parameters);
			}
		}
		if ($errors->hasError()) {
			// token ticket
			$token_ticket = $this->createToken( $this->modulePrefix('admin_policy_quicksearch_default') );

			$viewData['op'] = $op;
			$viewData['mode'] = 1;
			$viewData['condition_id'] = $cond_id;
			$viewData['condition_name'] = $cond_name;
			$viewData['errors'] = $errors->getView($this->dirname);

			$viewData['condlist'] = $condlist;
			$viewData['cond_blocks'] = $cond_blocks;
			$viewData['token_ticket'] = $token_ticket;
			$viewData['breadcrumbs'] = $breadcrumbs;
			$viewData['title'] = $title;
			$viewData['description'] = $description;
			$viewData['dirname'] = $this->dirname;

			$response->setViewData($viewData);
			$response->setForward('edit_success');

			return true;
		} else {
			$ret = $this->saveSearchCondition($cond_id, $cond_name);
			if (!$ret) {
				$complete_msg = _AM_XOONIPS_ERROR_DBUPDATE_FAILED;
			} else {
				$complete_msg = _AM_XOONIPS_MSG_DBUPDATED;
			}

			$viewData['url'] = XOOPS_URL.'/modules/'.$this->dirname.'/admin/policy_quicksearch.php';
			$viewData['redirect_msg'] = $complete_msg;

			$response->setViewData($viewData);
			$response->setForward('save_success');
			return $ret;
		 }
	}

	protected function doDelete(&$request, &$response) {
		if (!$this->validateToken($this->modulePrefix('admin_policy_quicksearch_default'))) {
			$response->setSystemError('Ticket error');
			return false;
		}

		$op = $request->getParameter('op');
		$cond_id = $request->getParameter('condition_id');
		$cond_name = $request->getParameter('condition_name');

		if (!$this->deleteSearchCondition($cond_id)) {
			$complete_msg = _AM_XOONIPS_ERROR_DBDELETED_FAILED;
		} else {
			$complete_msg = _AM_XOONIPS_MSG_DBDELETED;
		}

		$viewData['op'] = $op;
		$viewData['condition_id'] = $cond_id;
		$viewData['condition_name'] = $cond_name;
		$viewData['url'] = XOOPS_URL.'/modules/'.$this->dirname.'/admin/policy_quicksearch.php';
		$viewData['redirect_msg'] = $complete_msg;

		$response->setViewData($viewData);
		$response->setForward('delete_success');

		return true;

	}

	// get search condition block
	function getSearchConditionBlock($int, $itemtype, $cond_id, $op){
		$itemtype_id =  $itemtype['item_type_id'];
		$itemtype_name = $itemtype['name'];
		$block = array();
		$checked = '';

		$item = new Xoonips_Item($itemtype_id, $this->dirname, $this->trustDirname);
		if ($op == "save") {
			$item->setDataFromPost($_POST);
			$request = new Xoonips_Request();
			$checkValue = $request->getParameter($itemtype_name);
			if ($checkValue == 'on') {
				$checked = 'checked="checked"';
			}
		} else {
			$cond = $this->getSearchConditionDetail($cond_id, $itemtype_id);
			if (count($cond) > 0) {
				$checked = 'checked="checked"';
			}
			$item->setData($cond);
		}

		$block['int'] = $int;
		$block['itemtype_name'] = $itemtype_name;
		$block['cond_block'] = $itemtype_name."_cond_block";
		$block['checked'] = $checked;
		if ($checked != '') {
			$block['display'] = 'display:block';
		} else {
			$block['display'] = 'display:none';
		}
		$block['simpleSearchView'] = $item->getSimpleSearchView();
		return $block;
	}

	// get search condition detail
	function getSearchConditionDetail($cond_id, $itemtype_id) {
		$detailBean = Xoonips_BeanFactory::getBean('ItemFieldDetailBean', $this->dirname, $this->trustDirname);
		$condBean = Xoonips_BeanFactory::getBean('ItemTypeSearchConditionDetailBean', $this->dirname, $this->trustDirname);
		$condObj = $condBean->selectByItemtypeId($cond_id, $itemtype_id);
		$ret = array();
		foreach($condObj as $cond){
			$groupId = $cond['group_id'];

			$detailId = $cond['item_field_detail_id'];
			$itemtypeId = $cond['item_type_id'];
			$key = $groupId . Xoonips_Enum::ITEM_ID_SEPARATOR . $itemtypeId . Xoonips_Enum::ITEM_ID_SEPARATOR . $detailId;
			$ret[$key] = "1";
		}
		return $ret;
	}

	// delete
	function deleteSearchCondition($cond_id){
		// transaction
		$transaction = Xoonips_Transaction::getInstance();
		$transaction->start();
		// xoonips_item_type_search_condition
		$condBean = Xoonips_BeanFactory::getBean('ItemTypeSearchConditionBean', $this->dirname, $this->trustDirname);
		if (!$condBean->delete($cond_id)) {
			$transaction->rollback();
			return false;
		}
		// xoonips_item_type_search_condition_detail
		$condDetailBean = Xoonips_BeanFactory::getBean('ItemTypeSearchConditionDetailBean', $this->dirname, $this->trustDirname);
		//$condDetailBean->delete($cond_name)
		if (!$condDetailBean->delete($cond_id)) {
			$transaction->rollback();
			return false;
		}
		// success
		$transaction->commit();
		return true;
	}

	// save
	function saveSearchCondition($cond_id, $cond_name){
		// transaction
		$transaction = Xoonips_Transaction::getInstance();
		$transaction->start();

		$condBean = Xoonips_BeanFactory::getBean('ItemTypeSearchConditionBean', $this->dirname, $this->trustDirname);
		$condDetailBean = Xoonips_BeanFactory::getBean('ItemTypeSearchConditionDetailBean', $this->dirname, $this->trustDirname);

		$action_flg = 'ins';
		if (!empty($cond_id)) {
			$condObj = $condBean->select($cond_id);
			if (!$condObj) return false;
			$title = $condObj[0]['title'];
			$action_flg = 'upd';
		}

		// insert xoonips_item_type_search_condition
		$newConditinId = $cond_id;
		if ($action_flg == 'ins') {
			$cond = array();
			$cond['title'] = $cond_name;
			if (!$condBean->insert($cond, $newConditinId)) {
				$transaction->rollback();
				return false;
			}
		} else {
			if (!$condBean->update($cond_id, $cond_name)) {
				$transaction->rollback();
				return false;
			}
		}

		// insert xoonips_item_type_search_condition_detail
		$checked_detail = $this->getCheckedDetail();
		$condDtetail = array();
		$condDtetail['condition_id'] = $newConditinId;
		foreach($checked_detail as $key=>$itemtype){
			if ($action_flg=="upd"){
				// delete old condition detail
				if (!$condDetailBean->deleteByItemtypeId($cond_id, $key)) {
					$transaction->rollback();
					return false;
				}
			}
			$condDtetail['item_type_id'] = $key;
			foreach($itemtype as $val){
				$condDtetail['item_field_detail_id'] = $val;
				if (!$condDetailBean->insert($condDtetail)){
					$transaction->rollback();
					return false;
				}
			}
		}
		// success
		$transaction->commit();
		return true;
	}

	// get checked detail
	function getCheckedDetail(){
		$post_data = $_POST;
		$checkedItemtype = $this->getCheckedItemtype();
		$checked_var = array();
		foreach($checkedItemtype as $key=>$value){
			if ($value === true)
			$checked_var[$key] = array();
		}
		foreach($post_data as $key=>$value){
			$idArray = explode(Xoonips_Enum::ITEM_ID_SEPARATOR, $key);
			if (count($idArray) == 3) {
				if ($checkedItemtype[$idArray[1]] === true){
					if ($value=='1'){
						$checked_var[$idArray[1]][] = $idArray[2];
					}
				}
			}
		}
		return $checked_var;
	}

	// get checked itemtype
	function getCheckedItemtype(){
		$checked = array();
		$request = new Xoonips_Request();
		$itemTypeBean = Xoonips_BeanFactory::getBean('ItemTypeBean', $this->dirname, $this->trustDirname);
		$itemtypes = $itemTypeBean->getItemTypeList();
		if (!$itemtypes) return $checked;
		foreach ($itemtypes as $itemtype) {
			$itemtypeId = $itemtype['item_type_id'];
			$modleName = $itemtype['name'];
			$checkValue = $request->getParameter($modleName);
			if ($checkValue == 'on') {
				$checked[$itemtypeId] = true;
			} else {
				$checked[$itemtypeId] = false;
			}
		}
		return $checked;
	}

	private function setBreadcrumbs($isTop) {
		$breadcrumbs = array(
			array(
		        'name' => _AM_XOONIPS_TITLE,
		        'url' => XOOPS_URL.'/modules/'.$this->dirname.'/admin/index.php',
			),
			array(
		        'name' => _AM_XOONIPS_POLICY_TITLE,
		        'url' => XOOPS_URL.'/modules/'.$this->dirname.'/admin/policy.php',
			),
			array(
		        'name' => _AM_XOONIPS_POLICY_ITEM_TITLE,
		        'url' => XOOPS_URL.'/modules/'.$this->dirname.'/admin/policy_item.php',
			),
		);
		if (!$isTop) {
			$breadcrumbs[] = array(
		        'name' =>_AM_XOONIPS_POLICY_QUICKSEARCH_LIST_TITLE,
		        'url' => XOOPS_URL.'/modules/'.$this->dirname.'/admin/policy_quicksearch.php',
			);
			$breadcrumbs[] = array(
    	        'name' =>_AM_XOONIPS_POLICY_QUICKSEARCH_EDIT_TITLE,
			);
		} else {
			$breadcrumbs[] = array(
    	        'name' =>_AM_XOONIPS_POLICY_QUICKSEARCH_LIST_TITLE,
			);
		}
		return $breadcrumbs;
	}
}
?>
