<?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 selected detail
		$selected = array();
		if (!is_null($cond_id)) {
			$condBean = Xoonips_BeanFactory::getBean('ItemTypeSearchConditionDetailBean', $this->dirname, $this->trustDirname);
			$selected = $condBean->selectByItemtypeId($cond_id, 0);
		}

		// get details for select
		$itemfields = $this->getDetailsForSelect($selected);

		// 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['itemfields'] = $itemfields;
		$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) {

		// token ticket
		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 fields info
		$selected = array();
		$itemfieldBean = Xoonips_BeanFactory::getBean('ItemFieldDetailBean', $this->dirname, $this->trustDirname);
		$count = $itemfieldBean->countItemfields();
		$itemfields_objs = $itemfieldBean->getItemfieldlist($count, 0);

		foreach ($itemfields_objs as $itemfield) {
			$itemfieldid = $itemfield['item_field_detail_id'];
			if ($request->getParameter('checkbox_'.$itemfieldid)) {
				$selected[] = $itemfieldid;
			}
		}

		// do check
		$conditionBean = Xoonips_BeanFactory::getBean('ItemTypeSearchConditionBean', $this->dirname, $this->trustDirname);
		$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') );

			// get details for select
			$itemfields = $this->getDetailsForSelect($selected);

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

			$viewData['itemfields'] = $itemfields;
			$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, $selected);
			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;

	}

	// 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, $selected){
		// 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
		$condDtetail = array();
		$condDtetail['condition_id'] = $newConditinId;
		if ($action_flg=="upd"){
			// delete old condition detail
			if (!$condDetailBean->deleteByDetailId($cond_id)) {
				$transaction->rollback();
				return false;
			}
		}

		foreach($selected as $key => $detailid){
			$condDtetail['item_type_id'] = 0;
			$condDtetail['item_field_detail_id'] = $detailid;
			if (!$condDetailBean->insert($condDtetail)){
				$transaction->rollback();
				return false;
			}
		}
		// success
		$transaction->commit();
		return true;
	}

	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;
	}

	// get details for select
	private function getDetailsForSelect($selected=array()) {
		$itemfields = array();

		$detailBean = Xoonips_BeanFactory::getBean('ItemFieldDetailBean', $this->dirname, $this->trustDirname);
		$count = $detailBean->countItemfields();
		$itemfields_objs = $detailBean->getItemfieldlist($count, 0);

		foreach ($itemfields_objs as $itemfield) {
			if ($itemfield['released'] == 0) {
				continue;
			}
			$itemfieldid = $itemfield['item_field_detail_id'];
			$name = $itemfield['name'];
			$xml = $itemfield['xml'];
			$preselect = $itemfield['preselect'];
			$select = 0;
			foreach ($selected as $sel) {
				if ($sel['item_field_detail_id'] == $itemfieldid){
					$select = 1;
				}
			}

			$itemfields[] = array(
			    'itemfieldid' => $itemfieldid,
			    'name' => $name,
			    'xml' => $xml,
				'select' => $select,
			);
		}

		return $itemfields;
	}

}
?>
