<?php
/**
* @version	$Id: zones_event_handler.php 16516 2017-01-20 14:12:22Z alex $
* @package	In-Commerce
* @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license	Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/

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

class ZonesEventHandler extends kDBEventHandler {

	/**
	 * Allows to override standard permission mapping
	 *
	 * @return void
	 * @access protected
	 * @see kEventHandler::$permMapping
	 */
	protected function mapPermissions()
	{
		parent::mapPermissions();

		$permissions = Array(
			'OnTypeChange'		=>	Array('subitem' => 'add|edit'),
			'OnCountryChange'	=>	Array('subitem' => 'add|edit'),
			'OnLoadZoneForm'	=>	Array('subitem' => 'add|edit'),
		);

		$this->permMapping = array_merge($this->permMapping, $permissions);
	}

	/**
	 * Define alternative event processing method names
	 *
	 * @return void
	 * @see kEventHandler::$eventMethods
	 * @access protected
	 */
	protected function mapEvents()
	{
		parent::mapEvents();	// ensure auto-adding of approve/decline and so on events

		$zones_events = Array(
			'OnAddLocation'		=>	'DestinationAction',
			'OnRemoveLocation'	=>	'DestinationAction',
			'OnLoadZoneForm'	=>	'DestinationAction',
			/*'OnCountryChange'	=>	'DestinationAction',*/
		);

		$this->eventMethods = array_merge($this->eventMethods, $zones_events);
	}

	/**
	 * Apply custom processing to item
	 *
	 * @param kEvent $event
	 * @param string $type
	 * @return void
	 * @access protected
	 */
	protected function customProcessing(kEvent $event, $type)
	{
		/** @var kDBItem $zone_object */
		$zone_object = $event->getObject();

		switch ($type) {
			case 'before':
				if ( $event->Name == 'OnCreate' ) {
					$zone_object->SetDBField('ShippingTypeID', $this->Application->GetVar('s_id'));
				}
				break;

			case 'after':
				/** @var kDBItem $dst_object */
				$dst_object = $this->Application->recallObject('dst');

				if ( $event->Name == 'OnUpdate' ) {
					$sql = 'DELETE FROM ' . $dst_object->TableName . '
							WHERE ShippingZoneId = ' . $zone_object->GetID();
					$this->Conn->Query($sql);
				}
				else {
					$temp = $this->Application->GetVar('dst', Array ());
					foreach ($temp as $key => $value) {
						$temp[$key]['ShippingZoneId'] = $zone_object->GetID();
					}
					$this->Application->SetVar('dst', $temp);
				}

				$this->Application->HandleEvent(new kEvent('dst:OnCreate'));
				break;
		}
	}

	/**
	 * Enter description here...
	 *
	 * @param kEvent $event
	 */
	function OnTypeChange($event)
	{
		$this->Application->DeleteVar('dst');

		$event->CallSubEvent($this->Application->GetVar('z_OriginalSaveEvent'));
		$event->redirect = false;
	}

	/**
	 * Enter description here...
	 *
	 * @param kEvent $event
	 */
	function DestinationAction($event)
	{
		$event->redirect = false;

		$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
		if($items_info)
		{
			foreach($items_info as $item_id => $field_values)
			{
				// this is to receive $item_id
			}
		}

		$object = $event->getObject( Array('skip_autoload' => true) );
		$object->Load($item_id);

		$object->SetFieldsFromHash($field_values);
		$object->SetDBField('ZoneID', $item_id);

		$destination = $this->Application->recallObject('dst');

		switch($event->Name)
		{
			case 'OnAddLocation':
				$new_id = (int)$this->Conn->GetOne('SELECT MIN('.$destination->IDField.') FROM '.$destination->TableName);
				if($new_id > 0) $new_id = 0;
				do
				{
					$new_id--;
				} while ($this->check_array($this->Application->GetVar('dst'), 'ZoneDestId', $new_id));

				switch ($object->GetDBField('Type'))
				{
					case 1:
						$location_id = $this->Application->GetVar('country');
						break;
					case 2:
						$location_id = $this->Application->GetVar('state');
						break;
					default:
						$location_id = '';
				}

				$temp = $this->Application->GetVar('dst');
				$zip = $this->Application->GetVar('zip_input') ? $this->Application->GetVar('zip_input') : $this->Application->GetVar('zip_dropdown');

				if( ($location_id && !$this->check_array($temp, 'StdDestId', $location_id)) ||
						($zip && !$this->check_array($temp, 'DestValue', $zip)) )
				{
					$temp[$new_id]['ZoneDestId'] = $new_id;
					$temp[$new_id]['StdDestId'] = $location_id;
					$temp[$new_id]['DestValue'] = $zip ? $zip : '';

					$this->Application->SetVar('dst', $temp);
				}
				break;

			case 'OnRemoveLocation':

				$temp = $this->Application->GetVar('dst');
				$selected_destinations = explode(',', $this->Application->GetVar('selected_destinations'));
				foreach ($selected_destinations as $dest)
				{
					unset( $temp[$dest] );
				}
				$this->Application->SetVar('dst', $temp);

				break;

			case 'OnLoadZoneForm':

				$sql = 'SELECT * FROM '.$destination->TableName.' WHERE ShippingZoneId='.$item_id;
				$res = $this->Conn->Query($sql);
				$temp = Array();
				foreach ($res as $dest_record)
				{
					$temp[$dest_record['ZoneDestId']]['ZoneDestId'] = $dest_record['ZoneDestId'];
					$temp[$dest_record['ZoneDestId']]['StdDestId'] = $dest_record['StdDestId'];
					$temp[$dest_record['ZoneDestId']]['DestValue'] = $dest_record['DestValue'];
				}
				$this->Application->SetVar('dst', $temp);
				$object = $event->getObject();
				$object->SetDBField('ShippingTypeID', $this->Application->GetVar('s_id'));
				$this->Application->StoreVar('zone_mode'.$this->Application->GetVar('m_wid'), 'edit');

				break;

			/*case 'OnNew':
				$object = $event->getObject();
				$object->SetDBField('ShippingTypeID', $this->Application->GetVar('s_id'));
				break;*/

			case 'OnCountryChange':

				$this->Application->DeleteVar('dst');

				break;

			default:
		}
	}

	function OnCountryChange($event)
	{
		/** @var kDBItem $destinations */
		$destinations = $this->Application->recallObject('dst');

		$queryDel="DELETE FROM ".$destinations->TableName." WHERE ShippingZoneId=".$this->Application->GetVar($event->Prefix.'_id');
		$this->Conn->Query($queryDel);

		$this->Application->DeleteVar('dst');

		$event->CallSubEvent($this->Application->GetVar('z_OriginalSaveEvent'));
		$event->redirect = false;
	}

	/**
	 * Cancels kDBItem Editing/Creation
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnCancel(kEvent $event)
	{
		parent::OnCancel($event);

		/** @var kDBItem $dst_object */
		$dst_object = $this->Application->recallObject('dst');

		$sql = 'DELETE FROM ' . $dst_object->TableName . '
				WHERE ShippingZoneId = 0';
		$this->Conn->Query($sql);

		// if cancelling after create
		if ( $this->Application->RecallVar('zone_mode' . $this->Application->GetVar('m_wid')) == 'create' ) {
			/** @var kDBItem $zone */
			$zone = $event->getObject();

			$zone->Delete();
		}
	}

	/**
	 * Prepares new kDBItem object
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnNew(kEvent $event)
	{
		parent::OnNew($event);

		$this->Application->StoreVar('zone_mode' . $this->Application->GetVar('m_wid'), 'create');
	}

}