<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  @licence GPL 2005-2011  The osCSS developers - osCSS Open Source E-commerce
  @portion code Copyright (c) 2002 osCommerce
  @package osCSS-2 <www http://www.oscss.org>
  @version 2.1.0
  @date  11/05/11, 18:03
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class productUtility
*/
class productUtility {

  /**
    @package oscss
    @author  OscssTeam
    Calcul des id de product, avec option
  */
  public static function get_uprid($prid, $params) {
    $uprid = $prid;
    if ( (is_array($params)) && (!strstr($prid, '{')) ) {
      while (list($option, $value) = each($params)) {
	$uprid = $uprid . '{' . $option . '}' . $value;
      }
    }

    return $uprid;
  }

  /**
    @package oscss
    @author  OscssTeam
    Calcul des id de product, avec option
  */
  public static function get_prid($uprid) {
    $pieces = explode('{', $uprid);

    return $pieces[0];
  }

  /**
      Function de construction du tableau des produits online
      Fournis tous les produits , sauf inactif ou categorie inactif

    @package oscss-Rv
    @author oscim <mail a@oscim.fr /><web http://www.oscim.fr />
    @param
      @a array liste des id produits exlus
    @return array

  */
  public static function get_product_list($exclude = ''){
    global $currencies, $languages_id;
    $prod=array();
    if ($exclude == '') $exclude = array();
    $products_query = tep_db_query("select p.products_id, pd.products_name, p.products_price from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd , " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c,  " . TABLE_CATEGORIES . "  c  where p.products_status='1' and p.products_id = pd.products_id and pd.language_id = '" . (int)$languages_id . "' and p2c.products_id=p.products_id and c.categories_id=p2c.categories_id and c.categories_status='1'  order by products_name");
    while ($products = tep_db_fetch_array($products_query)){
      if (!in_array($products['products_id'], $exclude)){
	$products_tax_query = tep_db_query("select  t.tax_class_id, t.tax_class_title from " . TABLE_PRODUCTS . " p, " . TABLE_TAX_CLASS . " t where p.products_id ='".$products['products_id']."' and p.products_tax_class_id=t.tax_class_id ");
	$products_tax = tep_db_fetch_array($products_tax_query);
	$prod[$products['products_id']]=array_merge((array)$products, (array)$products_tax);
      }
    }
    return $prod;
  }


  /**
    Return a product's special price (returns nothing if there is no offer)
    TABLES: products
    @package oscss
    @author  OscssTeam
  */
  public static function get_products_special_price($product_id) {
    $product_query = tep_db_query("select specials_new_products_price from " . TABLE_SPECIALS . " where products_id = '" . (int)$product_id . "' and status");
    $product = tep_db_fetch_array($product_query);
    return $product['specials_new_products_price'];
  }

  /**
    @package oscss
    @author  OscssTeam
  */
  public static function get_products_name($product_id, $language_id = 0) {
    global $languages_id;

    if ($language_id == 0) $language_id = $languages_id;
    $product_query = tep_db_query("select products_name from " . TABLE_PRODUCTS_DESCRIPTION . " where products_id = '" . (int)$product_id . "' and language_id = '" . (int)$language_id . "'");
    $product = tep_db_fetch_array($product_query);

    return $product['products_name'];
  }

  /**
    @page qtpro_function.php
  */
  public static function options_name($options_id) {
    global $languages_id;
    $options = tep_db_query("select products_options_name from " . TABLE_PRODUCTS_OPTIONS . " where products_options_id = '" . (int)$options_id . "' and language_id = '" . (int)$languages_id . "'");
    $options_values = tep_db_fetch_array($options);
    return $options_values['products_options_name'];
  }

  /**
    @page attributeManager.php
    @page stock.central.php
    @page stats_low_attrib.php
  */
  public static function values_name($values_id) {
    global $languages_id;

    $values = tep_db_query("select products_options_values_name from " . TABLE_PRODUCTS_OPTIONS_VALUES . " where products_options_values_id = '" . (int)$values_id . "' and language_id = '" . (int)$languages_id . "'");
    $values_values = tep_db_fetch_array($values);

    return $values_values['products_options_values_name'];
  }

  /**
    @brief Recuperation price pour attribute
  */
  public static function get_product_attribut_price($products_id, $attributes=array(), $price=0){
    $uprid=tep_get_uprid($products_id, $attributes);

    if (is_array($attributes) && count($attributes)>0) {
      reset($attributes);
      while (list($option, $value) = each($attributes)) {
	$attribute_price_query = tep_db_query("select options_values_price, price_prefix from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . (int)$products_id . "' and options_id = '" . (int)$option . "' and options_values_id = '" . (int)$value . "'");
	$attribute_price = tep_db_fetch_array($attribute_price_query);
	if ($attribute_price['price_prefix'] == '+') {
	  $price += $attribute_price['options_values_price'];
	} else {
	  $price -= $attribute_price['options_values_price'];
	}
      }
    }

    return $price;
  }

  /**
    Generation des value de product extra value
    Si langue , table TABLE_PRODUCTS_DESCRIPTION sinon table TABLE_PRODUCTS_TO_PRODUCTS_EXTRA_FIELDS
    @package extra_fields_products
    @author oscim <mail oscim@oscss.org> <www http://www.oscim.fr>
    @param
      @a int/string id epf ou key epf
  */
  public static function get_product_extra_value($epf_id, $product_id, $language_id) {

    if(is_int($epf_id)|| (int)$epf_id ==$epf_id)
      $epf_query = tep_db_query("select e.epf_id, e.epf_uses_value_list, l.epf_active_for_language from " . TABLE_PRODUCTS_EXTRA_FIELDS . " e join " . TABLE_PRODUCTS_EXTRA_FIELDS_LABELS . " l ON e.epf_id = l.epf_id  where e.epf_id = '" . (int)$epf_id."'");
    else
      $epf_query = tep_db_query("select e.epf_id, e.epf_uses_value_list, l.epf_active_for_language from " . TABLE_PRODUCTS_EXTRA_FIELDS . " e join " . TABLE_PRODUCTS_EXTRA_FIELDS_LABELS . " l ON e.epf_id = l.epf_id  where e.epf_key = '" . $epf_id."'");

    $e = tep_db_fetch_array($epf_query);
    if($e['epf_active_for_language']==1) {
      $field = "extra_value" . ($e['epf_uses_value_list'] ? '_id' : '') . $e['epf_id'];
      $product_query = tep_db_query("select " . $field . " from " . TABLE_PRODUCTS_DESCRIPTION . " where products_id = '" . (int)$product_id . "' and language_id = '" . (int)$language_id . "'");
      $product = tep_db_fetch_array($product_query);
      return $product[$field];
    } else {
      $product_query = tep_db_query("select products_extra_fields_value from " . TABLE_PRODUCTS_TO_PRODUCTS_EXTRA_FIELDS . " where products_id = '" . (int)$product_id . "' and products_extra_fields_id = '" . (int)$e['epf_id'] . "'");
      $product = tep_db_fetch_array($product_query);
      return $product['products_extra_fields_value'];
    }
  }

  /**
    Generation des proudct extra value
    @package extra_fields_products
  */
  public static function get_extra_field_list_value($value_id, $show_chain = false) {
    $sql = tep_db_query("select epf_value, parent_id from " . TABLE_PRODUCTS_EXTRA_FIELDS_VALUES . " where value_id = " . (int)$value_id);
    $value = tep_db_fetch_array($sql);
    if ($show_chain && ($value['parent_id'] > 0)) {
      return tep_get_extra_field_list_value($value['parent_id'], true) . ' | ' . $value['epf_value'];
    } else {
      return $value['epf_value'];
    }
  }

  /**
    Generation des proudct extra value
    @package extra_fields_products
  */
  public static function list_epf_children($parent_id) {
    $sql = tep_db_query("select value_id from " . TABLE_PRODUCTS_EXTRA_FIELDS_VALUES . " where parent_id = " . (int)$parent_id);
    $list = '';
    while ($i = tep_db_fetch_array($sql)) {
      $list .= ', ' . $i['value_id'] . tep_list_epf_children($i['value_id']);
    }
    return $list;
  }

  /**
    Generation des proudct extra value
    @package extra_fields_products
  */
  public static function build_epf_pulldown($epf_id, $languages_id, $value_array = '', $parent_id = 0, $indent = '') {
    if (!is_array($value_array)) $value_array = array();
    $sql = tep_db_query("select epf_value, value_id from " . TABLE_PRODUCTS_EXTRA_FIELDS_VALUES . " where epf_id = " . (int)$epf_id . " and languages_id = " . (int)$languages_id . " and parent_id = " . (int)$parent_id . " order by sort_order, epf_value");
    while ($v = tep_db_fetch_array($sql)) {
      $value_array[] = array('id' => $v['value_id'], 'text' => $indent . $v['epf_value']);
      $value_array = tep_build_epf_pulldown($epf_id, $languages_id, $value_array, $v['value_id'], $indent . '&middot;');
    }
    return $value_array;
  }


  /**
   * \fn get_product_attribut_info($pID)
   * \brief Retourn tableau asso des element de pId precisé ou false
   * @param  $pID int l'id du produits
   * @return array/false
  */
  public static function get_product_attribut_info($pID){
    global  $languages_id;

    $language_id=$languages_id;

    $products_attributes_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_ATTRIBUTES . " patrib where patrib.products_id='" . (int)$pID . "' and patrib.options_id = popt.products_options_id and popt.language_id = '" . (int) $language_id. "'");
    $products_attributes = tep_db_fetch_array($products_attributes_query);
    $products_attributes=  ($products_attributes['total'] > 0)? $products_attributes['total'] : 0 ;

    return  $products_attributes;
  }

  /**
   * \brief Calcul des stock avec attribut , pour un  jeu d'attribut
   * @param [in] $products_id int
   * @param [in] $attributes tableau attribute id array
   * @return int  quantity
  */
  public static function get_products_attribute_stock($products_id, $attributes=array()){
    global  $languages_id;



    $DB=Database::getInstance();
    if (is_array($attributes) && count($attributes)>0) {
      $attr_list='';
      $options_list=implode(",",array_keys($attributes));
      $sql="select products_options_id, products_options_track_stock from " . TABLE_PRODUCTS_OPTIONS . " where products_options_id in ($options_list) and language_id= '" . (int)$languages_id . "' order by products_options_id";
      $track_stock_query=$DB->query($sql);
      while($track_stock_array=$track_stock_query->fetchAssoc())
        if ($track_stock_array['products_options_track_stock'])
          $attr_list.=$track_stock_array['products_options_id'] . '-' . $attributes[$track_stock_array['products_options_id']] . ',';

      $attr_list=substr($attr_list,0,strlen($attr_list)-1);
      unset($track_stock_query);


      $stock_query=$DB->query($sql="select products_stock_quantity as quantity from " . TABLE_PRODUCTS_STOCK . " where products_id='". (int)$products_id . "' and products_stock_attributes='$attr_list'");
      $stock=$stock_query->fetchAssoc();
      unset($attr_list);


      return $stock['quantity'];
    }
    return  0;
  }

  /**
    Sets the status of a product
      @package oscss
      @author  OscssTeam
  */
  public static function set_product_status($products_id, $status) {
    if ($status == '1') {
      return tep_db_query("update " . TABLE_PRODUCTS . " set products_status = '1', products_last_modified = now() where products_id = '" . (int)$products_id . "'");
    } elseif ($status == '0') {
      return tep_db_query("update " . TABLE_PRODUCTS . " set products_status = '0', products_last_modified = now() where products_id = '" . (int)$products_id . "'");
    } else {
      return -1;
    }
  }

  /**
    @package oscss-codev
    @author oscim - OscssTeam
    @version 5.1
    @note  suppression de produits
      Prend en charge Qtpro + ACA
    @p products.php,manufactureds.php
  */
  public static function remove_product($product_id) {
    global $products_modules;

    $product_image_query = tep_db_query("select products_image from " . TABLE_PRODUCTS . " where products_id = '" . (int)$product_id . "'");
    $product_image = tep_db_fetch_array($product_image_query);

    $duplicate_image_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS . " where products_image = '" . tep_db_input($product_image['products_image']) . "'");
    $duplicate_image = tep_db_fetch_array($duplicate_image_query);

    if ($duplicate_image['total'] < 2) {
      if (file_exists(DIR_FS_CATALOG_IMAGES . $product_image['products_image'])) @unlink(DIR_FS_CATALOG_IMAGES . $product_image['products_image']);
    }

    tep_db_query("delete from " . TABLE_SPECIALS . " where products_id = '" . (int)$product_id . "'");
    tep_db_query("delete from " . TABLE_PRODUCTS . " where products_id = '" . (int)$product_id . "'");
    tep_db_query("delete from " . TABLE_PRODUCTS_GROUPS . " where products_id = '" . (int)$product_id . "'");
    tep_db_query("delete from " . TABLE_PRODUCTS_TO_CATEGORIES . " where products_id = '" . (int)$product_id . "'");
    tep_db_query("delete from " . TABLE_PRODUCTS_DESCRIPTION . " where products_id = '" . (int)$product_id . "'");
    tep_db_query("delete from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . (int)$product_id . "'");
    tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET . " where products_id = '" . (int)$product_id . "'");
    tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " where products_id = '" . (int)$product_id . "'");

    /* Element modulaire aca */
    if (!is_object($products_modules))  {

      require_once (DIR_WS_MODULES.'pages/products.php');
      $products_modules = new productsACA();
    }
    // ACA START DELETE PRODUCT
    $products_modules->delete_product($product_id);


    osCSS_Cache::clear('categoriesBox');
    osCSS_Cache::clear('category_tree');
    osCSS_Cache::clear('also_purchased');

    qtpro_doctor_amputate_all_from_product($product_id);
  }

  /**
    Restock des produits lors suppression commande et/ou suppression du montant ht de product_to_customer (oscss-major)
    Prend en charge  ACA
    @package oscss-major
    @author oscim- OscssTeam
    @version 6.1
    @page held_orders.php,orders.php,return.php
  */
  public static function products_restock($order_id, $customers_id=''){
    error_reporting(E_ALL);
    global $products_modules;
    $order_query = tep_db_query("select products_id, products_quantity, products_stock_attributes, final_price  from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . (int)$order_id . "'");
    while ($order = tep_db_fetch_array($order_query)) {
      $product_stock_adjust = 0;
      if (tep_not_null($order['products_stock_attributes'])) {
	if ($order['products_stock_attributes'] != '$$DOWNLOAD$$') {
	  $attributes_stock_query = tep_db_query("SELECT products_stock_quantity
	      FROM " . TABLE_PRODUCTS_STOCK . "
	      WHERE products_stock_attributes = '" . $order['products_stock_attributes'] . "'
	      AND products_id = '" . (int)$order['products_id'] . "'");
	  if (tep_db_num_rows($attributes_stock_query) > 0) {
	    $attributes_stock_values = tep_db_fetch_array($attributes_stock_query);
	    tep_db_query("UPDATE " . TABLE_PRODUCTS_STOCK . "
		SET products_stock_quantity = products_stock_quantity + '" . (int)$order['products_quantity'] . "'
		WHERE products_stock_attributes = '" . $order['products_stock_attributes'] . "'
		AND products_id = '" . (int)$order['products_id'] . "'");
	    $product_stock_adjust = min($order['products_quantity'],  $order['products_quantity']+$attributes_stock_values['products_stock_quantity']);
	  } else {
	    tep_db_query("INSERT into " . TABLE_PRODUCTS_STOCK . "
		(products_id, products_stock_attributes, products_stock_quantity)
		VALUES ('" . (int)$order['products_id'] . "', '" . $order['products_stock_attributes'] . "', '" . (int)$order['products_quantity'] . "')");
	    $product_stock_adjust = $order['products_quantity'];
	  }
	}
      } else {
	$product_stock_adjust = $order['products_quantity'];
      }

      tep_db_query("UPDATE " . TABLE_PRODUCTS . "
	  SET products_quantity = products_quantity + " . $product_stock_adjust . ", products_ordered = products_ordered - " . (int)$order['products_quantity'] . "
	  WHERE products_id = '" . (int)$order['products_id'] . "'");

    //! Supp table specifique oscss-major
      if (!empty($customers_id)){
	/* Element modulaire aca */
	if (!is_object($products_modules))  {
	    require_once (DIR_WS_MODULES.'pages/products.php');
	    $products_modules = new productsACA();
	}
	$products_modules->products_restock($order['products_id'],$customers_id,$order['products_quantity'],($order['products_quantity'] *$order['final_price'] ) );
      }
    }
  }

}
?>
