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

	/**
	 * Allows to override standart permission mapping
	 *
	 */
	function mapPermissions()
	{
		parent::mapPermissions();
		$permissions = Array(
								'OnEntireOrder'	=>	Array('subitem' => 'add|edit'),
						);
		$this->permMapping = array_merge($this->permMapping, $permissions);
	}

	/**
	 * Adds products from selected categories and their sub-categories and directly selected products to discount items with duplicate checking
	 *
	 * @param kEvent $event
	 */
	function OnProcessSelected(&$event)
	{
		$object =& $event->getObject( Array('skip_autoload' => true) );
		$selected_ids = $this->Application->GetVar('selected_ids');

		if ($selected_ids['c'] == $this->Application->GetVar('m_cat_id')) {
			// no categories were selected, so selector returned current in catalog. This is not needed here
			$selected_ids['c'] = '';
		}

		$table_data = $object->getLinkedInfo();

		// in selectors we could select category & item together
		$prefixes = Array('c', 'p');

		foreach ($prefixes as $prefix) {
			$item_ids = $selected_ids[$prefix] ? explode(',', $selected_ids[$prefix]) : Array();
			if (!$item_ids) continue;

			if ($prefix == 'c') {
				// select all products from selected categories and their subcategories
				$sql = 'SELECT DISTINCT p.ResourceId
						FROM '.TABLE_PREFIX.'Category c
						LEFT JOIN '.TABLE_PREFIX.'CategoryItems ci ON c.CategoryId = ci.CategoryId
						LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ResourceId = ci.ItemResourceId
						WHERE (p.ProductId IS NOT NULL) AND (c.ParentPath LIKE "%|'.implode('|%" OR c.ParentPath LIKE "%|', $item_ids).'|%")';
				$resource_ids = $this->Conn->GetCol($sql);
			}
			else {
				// select selected prodcts
				$sql = 'SELECT ResourceId
						FROM '.$this->Application->getUnitOption($prefix, 'TableName').'
						WHERE '.$this->Application->getUnitOption($prefix, 'IDField').' IN ('.implode(',', $item_ids).')';
				$resource_ids = $this->Conn->GetCol($sql);
			}

			if (!$resource_ids) continue;

			$sql = 'SELECT ItemResourceId
					FROM '.$object->TableName.'
					WHERE ('.$table_data['ForeignKey'].' = '.$table_data['ParentId'].') AND (ItemResourceId IN ('.implode(',', $resource_ids).'))';

			// 1. don't insert items, that are already in
			$skip_resource_ids = $this->Conn->GetCol($sql);
			$resource_ids = array_diff($resource_ids, $skip_resource_ids); // process only not already in db resourceids for current discount

			// 2. insert ids, that left
			foreach ($resource_ids as $resource_id) {
				$object->SetDBField($table_data['ForeignKey'], $table_data['ParentId']);
				$object->SetDBField('ItemResourceId', $resource_id);
				$object->SetDBField('ItemType', 1);
				$object->Create();
				$object->setTempID();
			}
		}
		$this->finalizePopup($event);
	}

	/**
	 * Allows to set discount on entire order
	 *
	 * @param kEvent $event
	 * @todo get parent item id through $object->getLinkedInfo()['ParentId']
	 * @access public
	 */
	function OnEntireOrder(&$event)
	{
		$object =& $event->GetObject();
		$sql = 'DELETE FROM '.$object->TableName.' WHERE DiscountId='.$this->Application->GetVar('d_id');
		$this->Conn->Query($sql);

		$object->SetDBField('DiscountId', $this->Application->GetVar('d_id'));
		$object->SetDBField('ItemResourceId', -1);
		$object->SetDBField('ItemType', 0);

		if( $object->Create() )
		{
			if( $object->IsTempTable() ) $object->setTempID();
			$this->customProcessing($event,'after');
			$event->status=erSUCCESS;
			$event->redirect_params = Array('opener' => 's'); //stay!
		}
		else
		{
			$event->status=erFAIL;
			$this->Application->SetVar($event->Prefix_Special.'_SaveEvent','OnCreate');
			$object->setID(0);
		}
	}

	/**
	 * Deletes discount items where hooked item (product) is used
	 *
	 * @param kEvent $event
	 */
	function OnDeleteDiscountedItem(&$event)
	{
		$main_object =& $event->MasterEvent->getObject();
		$resource_id = $main_object->GetDBField('ResourceId');

		$table = $this->Application->getUnitOption($event->Prefix,'TableName');
		$sql = 'DELETE FROM '.$table.' WHERE ItemResourceId = '.$resource_id;
		$this->Conn->Query($sql);
	}

	/**
	 * Makes ItemName calcualted field from primary language
	 *
	 * @param kEvent $event
	 */
	function OnAfterConfigRead(&$event)
	{
		parent::OnAfterConfigRead($event);

		$calculated_fields = $this->Application->getUnitOption($event->Prefix, 'CalculatedFields');

		$language_id = $this->Application->GetVar('m_lang');
		$primary_language_id = $this->Application->GetDefaultLanguageId();

		$calculated_fields['']['ItemName'] = 'COALESCE(p.l' . $language_id . '_Name, p.l' . $primary_language_id . '_Name)';
		$this->Application->setUnitOption($event->Prefix, 'CalculatedFields', $calculated_fields);
	}
}