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

	/**
	 * Returns special of main item for linking with sub-item
	 *
	 * @param kEvent $event
	 * @return string
	 * @access protected
	 */
	protected function getMainSpecial(kEvent $event)
	{
		if ( $event->Special == 'downl' ) {
			return '';
		}

		return parent::getMainSpecial($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();

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

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

		$this->itemChanged($event);
	}

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

		$this->itemChanged($event);

		/** @var kDBItem $object */
		$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'];
		$file_id = $this->Conn->GetOne($sql);

		if ( !$file_id ) {
			$object->SetDBField('IsPrimary', 1);
			$object->SetDBField('Status', 1);
		}

		$object->SetDBField('AddedById', $this->Application->RecallVar('user_id'));
	}

	/**
	 * Occurs before item is changed
	 *
	 * @param kEvent $event
	 */
	function itemChanged($event)
	{
		/** @var kDBItem $object */
		$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'));
		}
	}

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

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

		$object->Load($id);

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

	/**
	 * Don't allow to delete primary product file, when there are no more files
	 *
	 * @param kEvent $event
	 * @param string $type
	 * @return void
	 * @access protected
	 */
	protected function customProcessing(kEvent $event, $type)
	{
		if ( $event->Name == 'OnMassDelete' && $type == 'before' ) {
			$ids = $event->getEventParam('ids');

			/** @var kDBItem $object */
			$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_file_id = $this->Conn->GetOne($sql);

			if ( $primary_file_id ) {
				$file_id_index = array_search($primary_file_id, $ids);

				if ( $file_id_index ) {
					// allow deleting of primary product file, when there is another file to make primary
					$sql = 'SELECT COUNT(*)
							FROM ' . $object->TableName . '
							WHERE IsPrimary = 0 AND ' . $parent_info['ForeignKey'] . ' = ' . $parent_info['ParentId'];
					$non_primary_file_count = $this->Conn->GetOne($sql);

					if ( $non_primary_file_count ) {
						unset($ids[$file_id_index]);
					}
				}
			}

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