<?php
/**
* @version	$Id: country_state_eh.php 13470 2010-04-28 15:21:51Z alex $
* @package	In-Portal
* @copyright	Copyright (C) 1997 - 2010 Intechnic. All rights reserved.
* @license      GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/

	defined('FULL_PATH') or die('restricted access!');

	class CountryStateEventHandler extends kDBEventHandler {

		/**
		 * Applies edit picker filters
		 *
		 * @param kEvent $event
		 */
		function SetCustomQuery(&$event)
		{
			parent::SetCustomQuery($event);

			$object =& $event->getObject();
			/* @var $object kDBList */

			if (($event->Special == 'selected') || ($event->Special == 'available')) {
				$edit_picker_helper =& $this->Application->recallObject('EditPickerHelper');
				/* @var $edit_picker_helper EditPickerHelper */

				$edit_picker_helper->applyFilter($event, 'Countries');

				// only countries
				$object->addFilter('type_filter', '%1$s.Type = ' . DESTINATION_TYPE_COUNTRY);
			}
		}

		/**
		 * Makes sure, that state country is always specified
		 *
		 * @param kEvent $event
		 */
		function OnBeforeItemCreate(&$event)
		{
			parent::OnBeforeItemCreate($event);

			$this->_setRequired($event);
		}

		/**
		 * Makes sure, that state country is always specified
		 *
		 * @param kEvent $event
		 */
		function OnBeforeItemUpdate(&$event)
		{
			parent::OnBeforeItemUpdate($event);

			$this->_setRequired($event);
		}

		/**
		 * Makes sure, that state country is always specified
		 *
		 * @param kEvent $event
		 */
		function _setRequired(&$event)
		{
			$object =& $event->getObject();
			/* @var $object kDBItem */

			$field_options = $object->GetFieldOptions('IsoCode');

			if ($object->GetDBField('Type') == DESTINATION_TYPE_STATE) {
				$object->setRequired('StateCountryId');
				$field_options['unique'] = Array ('Type', 'StateCountryId');
			}
			else {
				$object->setRequired('StateCountryId', false);
				$field_options['unique'] = Array ('Type');
			}

			$object->SetFieldOptions('IsoCode', $field_options);
		}

		/**
		 * Don't allow to delete countries, that have states
		 *
		 * @param kEvent $event
		 */
		function OnBeforeItemDelete(&$event)
		{
			parent::OnBeforeItemDelete($event);

			$object =& $event->getObject();
			/* @var $object kDBItem */

			$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
			/* @var $cs_helper kCountryStatesHelper */

			if ($cs_helper->CountryHasStates( $object->GetDBField('IsoCode') )) {
				$event->status = erFAIL;
				return ;
			}
		}
	}
