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

		function SetCustomQuery(&$event)
		{
			parent::SetCustomQuery($event);

			$object =& $event->getObject();
			$selectable_only = $event->getEventParam('selectable_only');
			if ($selectable_only) {
				$object->addFilter('types_filter', 'OptionType IN (1,3,6)');
			}

		}

		/**
		 * Updates temp_id to live_id in options combinations
		 *
		 * !Not called when "po" doesn't have subitems (temp handler problem)
		 *
		 * @param kEvent $event
		 */
		function OnAfterCopyToLive(&$event)
		{
			$id = $event->getEventParam('id');
			$temp_id = $event->getEventParam('temp_id');

			if ($id == $temp_id) return;

			$poc_table = $this->Application->GetTempName(TABLE_PREFIX.'ProductOptionCombinations', 'prefix:p');
			$query = 'SELECT * FROM '.$poc_table;
			$combs = $this->Conn->Query($query);
			foreach ($combs as $a_comb) {
				$comb_data = unserialize($a_comb['Combination']);
				$n_combs = array();
				foreach ($comb_data as $key => $val)
				{
					$n_key = $key == $temp_id ? $id : $key;
					$n_combs[$n_key] = $val;
				}
				ksort($n_combs);
				$n_combs = serialize($n_combs);
				$n_crc = crc32($n_combs);
				$query = 'UPDATE '.$poc_table.' SET
									Combination = '.$this->Conn->qstr($n_combs).', CombinationCRC = '.$n_crc.' WHERE CombinationId = '.$a_comb['CombinationId'];
				$this->Conn->Query($query);
			}
		}

		function OnAfterClone(&$event)
		{
			$id = $event->getEventParam('id');
			$org_id = $event->getEventParam('original_id');

			// storing original to new ids mapping to use in poc:OnBeforeClone
			$options_mapping = $this->Application->GetVar('poc_mapping');
			if (!$options_mapping) $options_mapping = array();
			$options_mapping[$org_id] = $id;
			$this->Application->SetVar('poc_mapping', $options_mapping);
		}

	}