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

	/**
	 * Get's special of main item for linking with subitem
	 *
	 * @param kEvent $event
	 * @return string
	 */
	function getMainSpecial(&$event)
	{
		if ($event->Special == 'downl') {
			return '';
		}

		return parent::getMainSpecial($event);
	}


	function SetCustomQuery(&$event)
	{
		$object =& $event->getObject();
		switch ($event->Special)
		{
			case 'downl':
				$object->addFilter('is_active', '%1$s.Status = 1');
				break;
		}
	}

	function prepareObject(&$object, &$event)
	{
		if($this->Application->GetVar('file_event') == 'OnNew' || $this->Application->GetVar('file_event') == 'OnCreate')
		{
			$options = $object->getFieldOptions('RealPath');
			$options['required'] = 1;
			$object->setFieldOptions('RealPath', $options);
		}
	}

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

		if($object->GetDBField('IsPrimary'))
		{
			$parent_info = $object->getLinkedInfo($event->Special);
			$sql = 'UPDATE '.$object->TableName.'
					SET IsPrimary = 0
					WHERE '.$parent_info['ForeignKey'].' = '.$parent_info['ParentId'];
			$this->Conn->Query($sql);
			$object->SetDBField('Status', 1);
		}

		if($object->GetDBField('Name') == '')
		{
			$object->SetDBField('Name', $object->GetDBField('FilePath'));
		}
	}

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

		$object =& $event->getObject();
		$parent_info = $object->getLinkedInfo($event->Special);
		$sql = 'SELECT FileId FROM '.$object->TableName.' WHERE IsPrimary = 1 AND '.$parent_info['ForeignKey'].' = '.$parent_info['ParentId'];
		if( !$this->Conn->GetOne($sql) )
		{
			$object->SetDBField('IsPrimary', 1);
			$object->SetDBField('Status', 1);
		}
		$object->SetDBField('AddedById', $this->Application->RecallVar('user_id'));
	}

	/**
	 * Enter description here...
	 *
	 * @param kEvent $event
	 */
	function OnSetPrimary(&$event)
	{
		$ids = $this->StoreSelectedIDs($event);
		$id = array_shift($ids);

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

		$object->SetDBField('IsPrimary', 1);
		$object->Update();
	}

	/**
	 * Deletes all selected items.
	 * Automatically recurse into sub-items using temp handler, and deletes sub-items
	 * by calling its Delete method if sub-item has AutoDelete set to true in its config file
	 *
	 * @param kEvent $event
	 */
	function OnMassDelete(&$event)
	{
		$event->status=erSUCCESS;

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

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

		$event->setEventParam('ids', $ids);
		$this->customProcessing($event, 'before');
		$ids = $event->getEventParam('ids');

		$object =& $event->getObject();
		$parent_info = $object->getLinkedInfo($event->Special);

		$sql = 'SELECT FileId FROM '.$object->TableName.' WHERE IsPrimary = 1 AND '.$parent_info['ForeignKey'].' = '.$parent_info['ParentId'];
		$primary = $this->Conn->GetOne($sql);
		if( $primary && ($key = array_search($primary, $ids)) )
		{
			$sql = 'SELECT FileId FROM '.$object->TableName.' WHERE IsPrimary = 0 AND '.$parent_info['ForeignKey'].' = '.$parent_info['ParentId'];
			$res = $this->Conn->Query($sql);
			if($res)
			{
				unset($ids[$key]);
			}
		}

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

}