<?php
/**
* @version	$Id: payment_type_event_handler.php 13558 2010-05-12 09:17:46Z 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 PaymentTypeEventHandler extends kDBEventHandler
{
	function mapEvents()
	{
		parent::mapEvents();
		$common_events = Array (
			'OnMassApprove'=>'iterateItems',
			'OnMassDecline'=>'OnMassDecline',
			'OnMassMoveUp'=>'iterateItems',
			'OnMassMoveDown'=>'iterateItems',
		);

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

	/**
	 * Allows to override standart permission mapping
	 *
	 */
	function mapPermissions()
	{
		parent::mapPermissions();
		$permissions = Array(
			'OnItemBuild' => Array('self' => true),
		);

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

	/**
	 * Set's new category as primary for product
	 *
	 * @param kEvent $event
	 */
	function OnSetPrimary(&$event)
	{
		$object =& $event->getObject( Array('skip_autoload' => true) );
		$this->StoreSelectedIDs($event);
		$ids=$this->getSelectedIDs($event);
		if($ids)
		{
			$id = array_shift($ids);
			$table_info = $object->getLinkedInfo();

			$this->Conn->Query('UPDATE '.$object->TableName.' SET IsPrimary = 0 ');
			$this->Conn->Query('UPDATE '.$object->TableName.' SET IsPrimary = 1, Status = 1 WHERE PaymentTypeId = '.$id.' ');
		}
		$event->redirect_params = Array('opener' => 's'); //stay!
	}

	function OnMassDecline(&$event)
	{
		$object =& $event->getObject( Array('skip_autoload' => true) );
		$this->StoreSelectedIDs($event);
		$ids=$this->getSelectedIDs($event);

		if($ids)
		{
			$status_field = array_shift( $this->Application->getUnitOption($event->Prefix,'StatusField') );

			foreach($ids as $id)
			{
				$object->Load($id);

				if (!$object->GetDBField("IsPrimary")){
					$object->SetDBField($status_field, 0);
				}

				if( $object->Update() )
				{
					$event->status=erSUCCESS;
					$event->redirect_params = Array('opener' => 's'); //stay!
				}
				else
				{
					$event->status=erFAIL;
					$event->redirect=false;
					break;
				}
			}
		}
	}

	/**
	 * Occurse before updating item
	 *
	 * @param kEvent $event
	 * @access public
	 */
	function OnBeforeItemUpdate(&$event)
	{
		parent::OnBeforeItemUpdate($event);

		$object = &$event->getObject();

		$status_field = array_shift( $this->Application->getUnitOption($event->Prefix,'StatusField') );

		if($object->GetDBField('IsPrimary')==1 && $object->GetDBField($status_field)==0){
			$object->SetDBField($status_field, 1);
		}

		$this->convertGroups($event);
	}

	/**
	 * Occurse before creating item
	 *
	 * @param kEvent $event
	 * @access public
	 */
	function OnBeforeItemCreate(&$event)
	{
		parent::OnBeforeItemCreate($event);

		$this->convertGroups($event);
	}

	/**
	 * Disable delete on primary payment type
	 *
	 * @param kEvent $event
	 * @access protected
	 */

	function customProcessing(&$event, $when){
		if ($event->Name == 'OnMassDelete' && $when == 'before'){
			$object = &$event->getObject();

			$ids = $event->getEventParam('ids');
			$ids_ok=array();
			foreach ($ids as $key => $id){
				$object->Load($id);
				if ($object->GetDBField('IsPrimary')){
					$this->Application->StoreVar('pt_delete_error', '1');
				}else{
					$ids_ok[]=$id;
				}
			}

			$event->setEventParam('ids', $ids_ok);

		}
	}

	function OnSave(&$event)
	{
		$this->Application->StoreVar('check_unused_currencies', 1);
		parent::OnSave($event);
	}

	/**
	 * Sets default payment type group
	 *
	 * @param kEvent $event
	 */
	function OnAfterConfigRead(&$event)
	{
		parent::OnAfterConfigRead($event);

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

		$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
		$fields['PortalGroups']['default'] = ','.$default_group.',';
		$this->Application->setUnitOption($event->Prefix, 'Fields', $fields);
	}

	/**
	 * Earlier version of group selector control needs such conversion (also used in shipping)
	 *
	 * @param kEvent $event
	 */
	function convertGroups(&$event)
	{
		$object =& $event->getObject();

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

	/**
	 * Returns ID of current item to be edited
	 * by checking ID passed in get/post as prefix_id
	 * or by looking at first from selected ids, stored.
	 * Returned id is also stored in Session in case
	 * it was explicitly passed as get/post
	 *
	 * @param kEvent $event
	 * @return int
	 */
	function getPassedID(&$event)
	{
		if ($event->Special == 'auto-ord') {
			$main_object =& $this->Application->recallObject('ord');
			/* @var $main_object kDBItem */

			return $main_object->GetDBField('PaymentType');
		}

		return parent::getPassedID($event);
	}

	/**
	 * Apply system filter to themes list
	 *
	 * @param kEvent $event
	 */
	function SetCustomQuery(&$event)
	{
		parent::SetCustomQuery($event);

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

		if (in_array($event->Special, Array ('enabled', 'selected', 'available')) || !$this->Application->isAdminUser) {
			// "enabled" special or Front-End
			$object->addFilter('enabled_filter', '%1$s.Status = ' . STATUS_ACTIVE);
		}

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

			$edit_picker_helper->applyFilter($event, 'PaymentTypes');
		}

		// apply domain-based payment type filtering
		$payment_types = $this->Application->siteDomainField('PaymentTypes');

		if (strlen($payment_types)) {
			$payment_types = explode('|', substr($payment_types, 1, -1));
			$object->addFilter('domain_filter', '%1$s.PaymentTypeId IN (' . implode(',', $payment_types) . ')');
		}
	}

}