<?php
/**
* @version	$Id: shipping_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 ShippingEventHandler extends kDBEventHandler {

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

		$permissions = Array (
			'OnFlip'			=>	Array ('self' => 'add|edit'),
			'OnApplyModifier'	=>	Array ('self' => 'add|edit'),
		);

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

	/**
	 * Presets shipping cost object based on shipping fields
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnAfterItemLoad(kEvent $event)
	{
		parent::OnAfterItemLoad($event);

		if ( !$this->Application->isAdminUser ) {
			return;
		}

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

		$format = '%01.' . $object->GetDBField('PrecisionAfterSep') . 'f'; // %01.2f
		$zero_if_empty = $object->GetDBField('ZeroIfEmpty');

		/** @var kDBItem $sc_object */
		$sc_object = $this->Application->recallObject('sc', null, Array ('raise_warnings' => 0));

		// change default shipping cost values ("Costs" tab on shipping editing) based on field from "Shipping Type"
		$flat_options = $sc_object->GetFieldOptions('Flat');
		$flat_options['format'] = $format;
		$flat_options['default'] = $zero_if_empty ? 0 : null;
		$sc_object->SetFieldOptions('Flat', $flat_options);

		$per_unit_options = $sc_object->GetFieldOptions('PerUnit');
		$per_unit_options['format'] = $format;
		$per_unit_options['default'] = $zero_if_empty ? 0 : null;
		$sc_object->SetFieldOptions('PerUnit', $per_unit_options);
	}

	/**
	 * Enter description here...
	 *
	 * @param kEvent $event
	 * @return unknown
	 */
	function OnApplyModifier($event)
	{
		/** @var kDBItem $cost_object */
		$cost_object = $this->Application->recallObject('sc');

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

		$operation = $this->Application->GetVar('operation');

		/** @var kFormatter $formatter */
		$formatter = $this->Application->recallObject('kFormatter');

		$modify_by = $formatter->TypeCast($this->Application->GetVar('modify_by'), array('type'=>'float'));
		$cost_type = $object->GetDBField('CostType');

		$brackets = $this->Application->GetVar('br');
		$zones = $this->Application->GetVar('z');
		$conditions = Array();

		if( is_array($zones) ) {
			$conditions['zones'] = 'ZoneID IN ('.implode( ',', array_keys($zones) ).')';
		}

		if( is_array($brackets) ) {
			$conditions['brackets'] = 'BracketId IN ('.implode( ',', array_keys($brackets) ).')';
		}

		$conditions = implode(' OR ', $conditions);

		if ( !$conditions ) {
			$this->finalizePopup($event);
			return ;
		}

		$sql = 'SELECT ShippingCostId FROM '.$cost_object->TableName.' WHERE '.$conditions;
		$res = $this->Conn->GetCol($sql);

		switch ( $cost_type ) {
			case 1:
				$affected_fields = Array (0 => 'Flat');
				break;

			case 2:
				$affected_fields = Array (0 => 'PerUnit');
				break;

			default:
				$affected_fields = Array (0 => 'PerUnit', 1 => 'Flat');
		}

		foreach ($affected_fields as $field) {
			if ( $operation == '/' && $modify_by == 0 ) {
				break;
			}

			$sql = 'UPDATE ' . $cost_object->TableName . '
					SET ' . $field . '=' . $field . $operation . $modify_by . '
					WHERE ShippingCostId IN (' . implode(',', $res) . ')
					AND NOT(' . $field . ' IS NULL)
					AND ' . $field . $operation . $modify_by . '>=0';
			$this->Conn->Query($sql);
		}

		$this->finalizePopup($event);
	}

	function OnFlip($event)
	{
		$object = $event->getObject();
		$aligment = $this->Application->GetLinkedVar('CostsTableAligment');
		$new_align = $aligment ? 0 : 1;
		$this->Application->SetVar('CostsTableAligment', $new_align);
		$this->Application->LinkVar('CostsTableAligment');

		$this->OnPreSave($event);

		$event->status=kEvent::erSUCCESS;
	}

	/**
	 * Saves content of temp table into live and
	 * redirects to event' default redirect (normally grid template)
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnSave(kEvent $event)
	{
		$this->OnAfterItemLoad($event);

		parent::OnSave($event);
	}

	/**
	 * Occurs after creating item
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnAfterItemCreate(kEvent $event)
	{
		parent::OnAfterItemCreate($event);

		$event->CallSubEvent('OnAnyChange');
	}

	/**
	 * Occurs after updating item
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnAfterItemUpdate(kEvent $event)
	{
		parent::OnAfterItemUpdate($event);

		$event->CallSubEvent('OnAnyChange');
	}

	/**
	 * Occurs after deleting item, id of deleted item
	 * is stored as 'id' param of event
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnAfterItemDelete(kEvent $event)
	{
		parent::OnAfterItemDelete($event);

		$event->CallSubEvent('OnAnyChange');
	}

	function OnAnyChange($event)
	{
		$sql = 'DELETE FROM ' . TABLE_PREFIX . 'SystemCache
				WHERE VarName LIKE "ShippingQuotes%"';
		$this->Conn->Query($sql);
	}

	/**
	 * Creates a new item in temp table and
	 * stores item id in App vars and Session on success
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnPreSaveCreated(kEvent $event)
	{
		parent::OnPreSaveCreated($event);

		/** @var kDBItem $object */
		$object = $event->getObject( Array ('skip_autoload' => true) );

		$object->SetDBField('PortalGroups', ',' . $this->Application->ConfigValue('User_LoggedInGroup') . ',');
	}

	function UpdateGroups($event)
	{
		/** @var kDBItem $object */
		$object = $event->getObject();

		if ( $event->Name == 'OnPreSaveCreated' ) {
			$default_group = $this->Application->ConfigValue('User_LoggedInGroup');
			$selected_groups = $default_group;
		}
		else {
			$selected_groups = $object->GetDBField('PortalGroups');
		}

		if ( $selected_groups && $selected_groups != '' ) {
			$selected_groups = str_replace('|', ',', $selected_groups);
			$selected_groups = ',' . trim($selected_groups, ',') . ',';
			$object->SetDBField('PortalGroups', $selected_groups);
		}
	}

	/**
	 * Apply custom processing to item
	 *
	 * @param kEvent $event
	 * @param string $type
	 * @return void
	 * @access protected
	 */
	protected function customProcessing(kEvent $event, $type)
	{
		$this->UpdateGroups($event);
	}
}