<?php
/**
* @version	$Id: payment_type_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 PaymentTypeEventHandler extends kDBEventHandler
{
	/**
	 * Define alternative event processing method names
	 *
	 * @return void
	 * @see kEventHandler::$eventMethods
	 * @access protected
	 */
	protected 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 standard permission mapping
	 *
	 * @return void
	 * @access protected
	 * @see kEventHandler::$permMapping
	 */
	protected 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->SetRedirectParam('opener', 's');
	}

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

		$this->StoreSelectedIDs($event);
		$ids = $this->getSelectedIDs($event);

		if ( $ids ) {
			$status_field = $object->getStatusField();

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

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

				if ( $object->Update() ) {
					$event->status = kEvent::erSUCCESS;
					$event->SetRedirectParam('opener', 's');
				}
				else {
					$event->status = kEvent::erFAIL;
					$event->redirect = false;
					break;
				}
			}
		}
	}

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

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

		$status_field = $object->getStatusField();

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

		$this->convertGroups($event);
	}

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

		$this->convertGroups($event);
	}

	/**
	 * Disable delete on primary payment type
	 *
	 * @param kEvent $event
	 * @param string $type
	 * @return void
	 * @access protected
	 */
	protected function customProcessing(kEvent $event, $type)
	{
		if ( $event->Name == 'OnMassDelete' && $type == 'before' ) {
			/** @var kDBItem $object */
			$object = $event->getObject();

			$ids_ok = Array ();
			$ids = $event->getEventParam('ids');

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

				if ( $object->GetDBField('IsPrimary') ) {
					$this->Application->StoreVar('pt_delete_error', '1');
				}
				else {
					$ids_ok[] = $id;
				}
			}

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

	/**
	 * 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->Application->StoreVar('check_unused_currencies', 1);

		parent::OnSave($event);
	}

	/**
	 * Sets default payment type group
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 */
	protected function OnAfterConfigRead(kEvent $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
	 * @access public
	 */
	public function getPassedID(kEvent $event)
	{
		if ( $event->Special == 'auto-ord' ) {
			/** @var kDBItem $main_object */
			$main_object = $this->Application->recallObject('ord');

			return $main_object->GetDBField('PaymentType');
		}
		elseif ( substr($event->Special, 0, 3) == 'gw-' ) {
			// returns first matched enabled payment type
			return Array (
				'Status' => STATUS_ACTIVE,
				TABLE_PREFIX . 'Gateways.Name' => $event->getEventParam('gateway')
			);
		}

		return parent::getPassedID($event);
	}

	/**
	 * Apply any custom changes to list's sql query
	 *
	 * @param kEvent $event
	 * @return void
	 * @access protected
	 * @see kDBEventHandler::OnListBuild()
	 */
	protected function SetCustomQuery(kEvent $event)
	{
		parent::SetCustomQuery($event);

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

		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' ) {
			/** @var EditPickerHelper $edit_picker_helper */
			$edit_picker_helper = $this->Application->recallObject('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) . ')');
		}
	}

}