<?php
/**
* @version	$Id: shipping_event_handler.php 12739 2009-10-20 19:38: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 standart permission mapping
	 *
	 */
	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
	 */
	function OnAfterItemLoad(&$event)
	{
		$object =& $event->getObject();

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

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

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

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

	/**
	 * Enter description here...
	 *
	 * @param kEvent $event
	 * @return unknown
	 */
	function OnApplyModifier(&$event)
	{
	//	$event->CallSubEvent('');

		$zones_object =& $this->Application->recallObject('z');
		$cost_object =& $this->Application->recallObject('sc');
		$object = $event->getObject();

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

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

		$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=erSUCCESS;
	}

	function OnSave(&$event)
	{
		$this->OnAfterItemLoad($event);

		parent::OnSave($event);
	}

	function OnAfterItemCreate(&$event)
	{
		$event->CallSubEvent('OnAnyChange');
	}

	function OnAfterItemUpdate(&$event)
	{
		$event->CallSubEvent('OnAnyChange');
	}

	function OnAfterItemDelete(&$event)
	{
		$event->CallSubEvent('OnAnyChange');
	}

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

	function OnPreSaveCreated(&$event){
		parent::OnPreSaveCreated($event);

		$default_group = $this->Application->ConfigValue('User_LoggedInGroup');

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

		$object->SetDBField('PortalGroups', ','.$default_group.',');
	}

	function UpdateGroups(&$event){
		$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);
		}
	}

	function customProcessing(&$event, $when){
		$this->UpdateGroups($event);

	}
}