<?php
/**
* @version	$Id: product_options_helper.php 15244 2012-03-27 11:48:38Z 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 kProductOptionsHelper extends kHelper {

		function ExplodeOptionValues($option_row)
		{
			$values = getArrayValue($option_row, 'Values');
			if (!$values) return false;

			$values = explode(',', $values);

			$prices = preg_split('/(?<!\\\)\|/', getArrayValue($option_row, 'Prices'));
			foreach ($prices as $a_price) {
				list($id, $price) = preg_split('/(?<!\\\)=/', $a_price);
				$conv_prices[$id] = $price;
			}
			$price_types = preg_split('/(?<!\\\)\|/', getArrayValue($option_row, 'PriceTypes'));
			foreach ($price_types as $a_price_type) {
				list($id, $price_type) = preg_split('/(?<!\\\)=/', $a_price_type);
				$conv_price_types[$id] = $price_type;
			}
			$conv_prices = $this->UnEscape($conv_prices);
			$conv_price_types = $this->UnEscape($conv_price_types);

			return array('Values'=>$values, 'Prices'=>$conv_prices, 'PriceTypes'=>$conv_price_types);
		}

		function UnEscape($data)
		{
			$res = array();
			foreach ($data as $key=>$val)
			{
				$n_key = str_replace('\\|', '|', $key);
				$n_key = str_replace('\\=', '=', $n_key);
				$n_val = str_replace('\\|', '|', $val);
				$n_val = str_replace('\\=', '=', $n_val);
				$res[$n_key] = $n_val;
			}
			return $res;
		}

		function ConvertKey($key, $product_id, $use_temp=0)
		{
			static $mapping = null;

			if (is_null($mapping) || !isset($mapping[$product_id])) {
				$table = TABLE_PREFIX.'ProductOptions';
				if ($use_temp) $table = $this->Application->GetTempName($table, 'prefix:p');
				$sql = 'SELECT * FROM '.$table.' WHERE ProductId = '.$product_id;

				$mapping[$product_id] = $this->Conn->Query($sql, 'ProductOptionId');
			}

			return $mapping[$product_id][$key];
		}

		function OptionsSalt($options, $comb_only=false)
		{
			if ( !is_array($options) ) {
				return 0;
			}
			if ( !$comb_only ) {
				ksort($options);
				return kUtil::crc32(serialize($options));
			}

			$option_keys = array_keys($options);
			if ( !$option_keys ) {
				return '';
			}

			$sql = 'SELECT ProductOptionId
					FROM ' . TABLE_PREFIX . 'ProductOptions
					WHERE ProductOptionId IN (' . join(',', $option_keys) . ') AND OptionType IN (1,3,6)';
			$included = $this->Conn->GetCol($sql);

			foreach ($option_keys as $key) {
				if ( !in_array($key, $included) ) {
					unset($options[$key]);
				}
			}

			return $this->OptionsSalt($options);
		}
	}