<?php
/**
* @version	$Id: affiliate_payment_types_event_handler.php 12962 2009-12-20 13:12:59Z 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 AffiliatePaymentTypesEventHandler extends kDBEventHandler  {

		function SetCustomQuery(&$event)
		{
			if($event->Special == 'active')
			{
				$object =& $event->getObject();
				$object->addFilter('active', '%1$s.Status = 1');
			}
		}

		/**
		 * Enter description here...
		 *
		 * @param kEvent $event
		 */
		function OnSetPrimary(&$event)
		{
			$object =& $event->getObject();
			$object->SetDBField('IsPrimary', 1);
			$object->Update();
		}


		/**
		 * Enter description here...
		 *
		 * @param kEvent $event
		 */
		function OnBeforeItemUpdate(&$event)
		{
			$object =& $event->getObject();

			if ($object->GetDBField('IsPrimary') && $object->Validate()) {
				$table_name = $this->Application->getUnitOption($event->Prefix, 'TableName');
				$sql = 'UPDATE '.$table_name.' SET IsPrimary = 0';
				$this->Conn->Query($sql);

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

		function OnBeforeItemCreate(&$event)
		{
			$this->OnBeforeItemUpdate($event);
		}

		function OnMassDelete($event)
		{
			if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
				$event->status = erFAIL;
				return;
			}

			$this->StoreSelectedIDs($event);
			$event->setEventParam('ids', $this->getSelectedIDs($event) );
			$ids = $event->getEventParam('ids');

			$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');

			$sql = 'SELECT AffiliatePlanId FROM '.$this->Application->getUnitOption('ap', 'TableName').'
					WHERE IsPrimary = 1';
			$primary_id = $this->Conn->GetOne($sql);
			$ids = array_diff($ids, Array($primary_id));

			if($ids)
			{
				$temp->DeleteItems($event->Prefix, $event->Special, $ids);
			}
			$this->clearSelectedIDs($event);
		}
	}