<?php
include_once('../includes/classes/creAttributes.php');

class Product {

  public static function addProduct($data) {
	$languages = tep_get_languages();

	$products_date_available = isset($data['products_date_available'])? tep_db_prepare_input($data['products_date_available']):null;
	$products_quantity = isset($data['products_quantity'])? tep_db_prepare_input($data['products_quantity']):0;
	$products_model = isset($data['products_model'])? tep_db_prepare_input(tep_db_encoder($data['products_model'])):'';
	$products_sku = isset($data['products_sku'])? tep_db_prepare_input(tep_db_encoder($data['products_sku'])):'';
	$products_price = isset($data['products_price'])? tep_db_prepare_input($data['products_price']):0;
	$products_weight = isset($data['products_weight']) ? tep_db_prepare_input($data['products_weight']) : 0;
	$products_map = isset($data['products_map']) ? tep_db_prepare_input($data['products_map']) : 0;

	$products_status = isset($data['products_status']) ? tep_db_prepare_input($data['products_status']) : 'off';
	if ($products_status == 'on') $products_status = 1;
	if ($products_status == 'off') $products_status = 0;
	$featured = isset($_POST['featured']) ? tep_db_prepare_input($_POST['featured']) : 'off';
	$featured = ($featured == 'on')?1:0;

	$products_tax_class_id = isset($data['products_tax_class_id']) ? tep_db_prepare_input($data['products_tax_class_id']) : 0;
	$manufacturers_id = isset($data['manufacturers_id']) ? tep_db_prepare_input($data['manufacturers_id']) : 0;
	$sql_data_array = array('products_date_available' => $products_date_available,
						  'products_quantity' => $products_quantity,
						  'products_model' => $products_model,
						  'products_sku' => $products_sku,
						  'products_price' => $products_price,
						  'products_weight' => $products_weight,
						  'products_status' => $products_status,
						  'products_tax_class_id' => $products_tax_class_id,
						  'manufacturers_id' => $manufacturers_id,
						  'featured' => $featured,
						  'products_map' => $products_map
						 );
	$sql_data_array['products_date_added'] = 'now()';
	if(isset($data['products_parent_id'])) {
		$products_parent_id = (int) $data['products_parent_id'];
		$sql_data_array['products_parent_id'] = $products_parent_id;
	}
	tep_db_perform(TABLE_PRODUCTS, $sql_data_array);
	$products_id = tep_db_insert_id();

	if($products_id > 0)
	{
		// process the products description table data
		for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
			$language_id = $languages[$i]['id'];
			//dont insert if name/permalink are blank
			if($data['products_name'][$language_id] != '' && $data['permalink_name'][$language_id] != ''){
				$data['products_url'][$language_id] = urldecode($data['products_url'][$language_id]);
				if (substr($data['products_url'][$language_id], 0, 7) == 'http://') $data['products_url'][$language_id] = substr($data['products_url'][$language_id], 7);
				$sql_data_array = array('products_name' => tep_db_prepare_input(tep_db_encoder($data['products_name'][$language_id])),
									  'products_description' => tep_db_prepare_input(tep_db_encoder($data['products_description'][$language_id])),
									  'products_url' => tep_db_prepare_input($data['products_url'][$language_id]),
									  'products_head_title_tag' => tep_db_prepare_input(tep_db_encoder($data['products_head_title_tag'][$language_id])),
									  'products_head_desc_tag' => tep_db_prepare_input(tep_db_encoder($data['products_head_desc_tag'][$language_id])),
									  'products_head_keywords_tag' => tep_db_prepare_input(tep_db_encoder($data['products_head_keywords_tag'][$language_id])),
									  'products_id' => $products_id,
									  'language_id' => $language_id
									 );

				tep_db_perform(TABLE_PRODUCTS_DESCRIPTION, $sql_data_array);

				//checking existing same permalink name
				$permalink_name = tep_db_prepare_input(tep_db_encoder($data['permalink_name'][$language_id]));
				$checking_existing_permalink = check_permalink($permalink_name, $language_id);
				if($checking_existing_permalink > 0)
				 $permalink_name = tep_db_prepare_input(tep_db_encoder($data['permalink_name'][$language_id])).'-'.rand(1,20);
				 $permalink_name = check_dup_permalink('products_id', $products_id, $permalink_name, 1);
				 if($data['permalink_name'][$language_id] == ''){
					 $permalink_name =  sanitize($data['products_name'][$language_id]);
					 $permalink_name = check_dup_permalink('products_id', $products_id, $permalink_name, 1);
					 if (is_numeric($permalink_name)){
						$permalink_name = 'pr-'.$permalink_name;
					 }
				 }
				 $insert_permalink_data = array('products_id' => $products_id,
									 'language_id' => $language_id,
									 'route' => 'core/product_info',
									 'permalink_type' => 'product',
									 'permalink_name' => $permalink_name);
				 tep_db_perform(TABLE_PERMALINK, $insert_permalink_data);
				 //update product permalink in product table
				 tep_db_query("UPDATE ".TABLE_PRODUCTS_DESCRIPTION." SET permalink_name = '".$permalink_name."' WHERE products_id = '".$products_id."'");
			}
		}

	    //update multi categories Start
		  $productsxcategories = $_POST['productsxcategories'];
		  if(count($productsxcategories) > 0 && $productsxcategories != ''){
		  	$delete = tep_db_query("DELETE from products_to_categories where products_id = '".(int)$products_id."' ");
		  	foreach($productsxcategories AS $indvcategories_id){
				$sql_data_array = array('products_id' => $products_id, 'categories_id' => $indvcategories_id );
				tep_db_perform('products_to_categories', $sql_data_array);
		  	}
		  }
	    //update multi categories End

	}
	return $products_id;

  }

  public static function updateProduct($products_id=0, $data, $products_old=array(), $products_description_old=array()) {

	if($products_id > 0 && count($data) > 2) {
      $languages = tep_get_languages();

	  // get the current product data so we can compare it later to see what has changed
	  $products_old_query = tep_db_query("SELECT * FROM " . TABLE_PRODUCTS . " WHERE products_id = " . $products_id);
	  $products_old = tep_db_fetch_array($products_old_query);
	  $products_description_old_query = tep_db_query("SELECT language_id, products_name, products_description, products_url, products_viewed,
															 products_head_title_tag, products_head_desc_tag, products_head_keywords_tag
													  FROM " . TABLE_PRODUCTS_DESCRIPTION . "
													  WHERE products_id = " . $products_id);
	  $products_description_old = array();
	  while ($description_old = tep_db_fetch_array($products_description_old_query)) {
		$products_description_old[$description_old['language_id']] = array('products_name' => $description_old['products_name'],
																		   'products_description' => $description_old['products_description'],
																		   'products_url' => $description_old['products_url'],
																		   'products_viewed' => $description_old['products_viewed'],
																		   'products_head_title_tag' => $description_old['products_head_title_tag'],
																		   'products_head_desc_tag' => $description_old['products_head_desc_tag'],
																		   'products_head_keywords_tag' => $description_old['products_head_keywords_tag']
																		  );
	  }

	  //echo $products_special_price_old;exit;
	  unset($products_old_query);
	  unset($products_description_old_query);
	  unset($description_old);

      $sql_data_array = array(); //declare the array and add to it anything changed
      $products_date_available = tep_db_prepare_input($data['products_date_available']);

      // convert to datetime
      $products_date_available = date('Y-m-d H:i:s', strtotime($products_date_available));              // returns Saturday, January 30 10 02:06:34

      if ($products_date_available != $products_old['products_date_available']) $sql_data_array['products_date_available'] = $products_date_available;
      $products_quantity = tep_db_prepare_input($data['products_quantity']);
      if ($products_quantity != $products_old['products_quantity']) $sql_data_array['products_quantity'] = $products_quantity;
      $products_model = tep_db_prepare_input(tep_db_encoder($data['products_model']));
      if ($products_model != $products_old['products_model']) $sql_data_array['products_model'] = $products_model;
      $products_sku = tep_db_prepare_input(tep_db_encoder($data['products_sku']));
      if ($products_sku != $products_old['products_sku']) $sql_data_array['products_sku'] = $products_sku;
      $products_price = tep_db_prepare_input($data['products_price']);
      if ($products_price != $products_old['products_price']) $sql_data_array['products_price'] = $products_price;
      $products_weight = isset($data['products_weight']) ? tep_db_prepare_input($data['products_weight']) : 0;
      if ($products_weight != $products_old['products_weight']) $sql_data_array['products_weight'] = $products_weight;
      $products_map = isset($data['products_map']) ? tep_db_prepare_input($data['products_map']) : 0;
      if ($products_map != $products_old['products_map']) $sql_data_array['products_map'] = $products_map;

      $products_status = isset($data['products_status']) ? tep_db_prepare_input($data['products_status']) : 'off';
      if ($products_status == 'on') $products_status = 1;
      if ($products_status == 'off') $products_status = 0;
      if ($products_status != $products_old['products_status']) $sql_data_array['products_status'] = $products_status;

      $products_tax_class_id = isset($data['products_tax_class_id']) ? tep_db_prepare_input($data['products_tax_class_id']) : 0;
      if ($products_tax_class_id != $products_old['products_tax_class_id']) $sql_data_array['products_tax_class_id'] = $products_tax_class_id;
      $manufacturers_id = isset($data['manufacturers_id']) ? tep_db_prepare_input($data['manufacturers_id']) : 0;
      if ($manufacturers_id != $products_old['manufacturers_id']) $sql_data_array['manufacturers_id'] = $manufacturers_id;

	  $featured = isset($_POST['featured']) ? tep_db_prepare_input($_POST['featured']) : 'off';
	  $featured = ($featured == 'on')?1:0;
      if ($featured != $products_old['featured']) $sql_data_array['featured'] = $featured;

      // check to see if there is anything to actually update in the products table
      if (count($sql_data_array) > 0 ) {
        $sql_data_array['products_last_modified'] = 'now()';
        tep_db_perform(TABLE_PRODUCTS, $sql_data_array, 'update', 'products_id = ' . (int)$products_id);
      }


      // process the products description table data
      $products_description_parent = array(); // save the name and description for later use in processing sub products
      for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
        $language_id = $languages[$i]['id'];
        $products_description_parent[$language_id] = array('products_name' => tep_db_prepare_input(tep_db_encoder($data['products_name'][$language_id])),
                                                           'products_description' => tep_db_prepare_input(tep_db_encoder($data['products_description'][$language_id]))
                                                           );
        if (!isset($products_description_old[$language_id])) {
          $data['products_url'][$language_id] = urldecode($data['products_url'][$language_id]);
          if (substr($data['products_url'][$language_id], 0, 7) == 'http://') $data['products_url'][$language_id] = substr($data['products_url'][$language_id], 7);
          $sql_data_array = array('products_name' => tep_db_prepare_input(tep_db_encoder($data['products_name'][$language_id])),
                                  'products_description' => tep_db_prepare_input(tep_db_encoder($data['products_description'][$language_id])),
                                  'products_url' => tep_db_prepare_input($data['products_url'][$language_id]),
                                  'products_head_title_tag' => tep_db_prepare_input(tep_db_encoder($data['products_head_title_tag'][$language_id])),
                                  'products_head_desc_tag' => tep_db_prepare_input(tep_db_encoder($data['products_head_desc_tag'][$language_id])),
                                  'products_head_keywords_tag' => tep_db_prepare_input(tep_db_encoder($data['products_head_keywords_tag'][$language_id]))
                                 );
        } else {
          $sql_data_array = array(); //declare the array and add to it anything changed
          $products_name = tep_db_prepare_input(tep_db_encoder($data['products_name'][$language_id]));
          if ($products_description_old[$language_id]['products_name'] != $products_name) {
            $sql_data_array['products_name'] = tep_db_encoder($products_name);
          }
          $products_description = tep_db_prepare_input(tep_db_encoder($data['products_description'][$language_id]));
          if ($products_description_old[$language_id]['products_description'] != $products_description) $sql_data_array['products_description'] = tep_db_encoder($products_description);
          $data['products_url'][$language_id] = urldecode($data['products_url'][$language_id]);
          if (substr($data['products_url'][$language_id], 0, 7) == 'http://') $data['products_url'][$language_id] = substr($data['products_url'][$language_id], 7);
          $products_url = tep_db_prepare_input($data['products_url'][$language_id]);
          if ($products_description_old[$language_id]['products_url'] != $products_url) $sql_data_array['products_url'] = $products_url;
          $products_head_title_tag = tep_db_prepare_input(tep_db_encoder($data['products_head_title_tag'][$language_id]));
          if ($products_description_old[$language_id]['products_head_title_tag'] != $products_head_title_tag) $sql_data_array['products_head_title_tag'] = $products_head_title_tag;
          $products_head_desc_tag = tep_db_prepare_input(tep_db_encoder($data['products_head_desc_tag'][$language_id]));
          if ($products_description_old[$language_id]['products_head_desc_tag'] != $products_head_desc_tag) $sql_data_array['products_head_desc_tag'] = $products_head_desc_tag;
          $products_head_keywords_tag = tep_db_prepare_input(tep_db_encoder($data['products_head_keywords_tag'][$language_id]));
          if ($products_description_old[$language_id]['products_head_keywords_tag'] != $products_head_keywords_tag) $sql_data_array['products_head_keywords_tag'] = $products_head_keywords_tag;
        }

        // check to see if there is anything to actually update in the products table
        if (count($sql_data_array) > 0 ) {
          tep_db_perform(TABLE_PRODUCTS_DESCRIPTION, $sql_data_array, 'update', 'products_id = ' . (int)$products_id . ' and language_id = ' . (int)$language_id);
        }

		//checking permalink table
		$default_product_name = tep_db_prepare_input(tep_db_encoder($data['products_name'][$language_id]));
		$perma_query = tep_db_query("SELECT * FROM ". TABLE_PERMALINK ." WHERE  products_id = '$products_id' and language_id = '$language_id'");
		if(tep_db_num_rows($perma_query) > 0) {
			 $permalink_name = tep_db_prepare_input(tep_db_encoder($data['permalink_name'][$language_id]));
			 $permalink_name = sanitize($permalink_name);
			 if($permalink_name == ''){
				$permalink_name = sanitize($default_product_name).'-'.$products_id;
			 }
			 $update_permalink_data = array('permalink_type' => 'product','route' => 'core/product_info','permalink_name' => $permalink_name);
			 tep_db_perform(TABLE_PERMALINK, $update_permalink_data, 'update', 'products_id = ' . (int)$products_id . ' and language_id = ' . (int)$language_id);
			 tep_db_query("UPDATE ".TABLE_PRODUCTS_DESCRIPTION." SET permalink_name = '".$permalink_name."' WHERE products_id = '".$products_id."'");
		}else{
			 if($data['permalink_name'][$language_id] == ''){
				 $slug = sanitize($default_product_name).'-'.$products_id;
			 }else{
				$slug = sanitize($data['permalink_name'][$language_id]);
			 }
			 $insert_permalink_data = array('products_id' => $products_id,
								 'language_id' => $language_id,
								 'route' => 'core/product_info',
								 'permalink_type' => 'product',
								 'permalink_name' => $slug);
			tep_db_perform(TABLE_PERMALINK, $insert_permalink_data);

		}
      }

	  //update multi categories Start
		  $productsxcategories = $_POST['productsxcategories'];
		  if(count($productsxcategories) > 0 && $productsxcategories != ''){
		  	$delete = tep_db_query("DELETE from products_to_categories where products_id = '".(int)$products_id."' ");
		  	foreach($productsxcategories AS $indvcategories_id){
				$sql_data_array = array('products_id' => $products_id, 'categories_id' => $indvcategories_id );
				tep_db_perform(TABLE_PRODUCTS_TO_CATEGORIES, $sql_data_array);
		  	}
		  }
	  //update multi categories End

	}
  }

  public static function linkProductCategory($products_id=0, $categories_id=0) {
  	if($products_id > 0) {
		$check_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_TO_CATEGORIES . " where products_id = '" . (int)$products_id . "' and categories_id = '" . (int)$categories_id . "'");
		$check = tep_db_fetch_array($check_query);
		if ($check['total'] <= 0 ) {
		  tep_db_query("insert into " . TABLE_PRODUCTS_TO_CATEGORIES . " (products_id, categories_id) values ('" . (int)$products_id . "', '" . (int)$categories_id . "')");
		}
  	}
  }

  public static function uploadProductImage($products_id=0) {
	if($products_id > 0) {
	  $products_old_query = tep_db_query("SELECT * FROM " . TABLE_PRODUCTS . " WHERE products_id = " . $products_id);
	  $products_old = tep_db_fetch_array($products_old_query);

      $sql_data_array = array(); //declare the array and add to it anything changed
      if(ENABLE_ALLOW_ALL_SIZE == 'True'){
	      $images = array(array('table' => 'products_image', 'delete' => 'delete_image', 'unlink' => 'unlink_image', 'dir' => 'products_image_destination'),
			      array('table' => 'products_image_med', 'delete' => 'delete_image_med', 'unlink' => 'unlink_image_med', 'dir' => 'products_image_med_destination'),
			      array('table' => 'products_image_lrg', 'delete' => 'delete_image_lrg', 'unlink' => 'unlink_image_lrg', 'dir' => 'products_image_lrg_destination'),
			      array('table' => 'products_image_sm_1', 'delete' => 'delete_image_sm_1', 'unlink' => 'unlink_image_sm_1', 'dir' => 'products_image_sm_1_destination'),
			      array('table' => 'products_image_xl_1', 'delete' => 'delete_image_xl_1', 'unlink' => 'unlink_image_xl_1', 'dir' => 'products_image_xl_1_destination'),
			      array('table' => 'products_image_sm_2', 'delete' => 'delete_image_sm_2', 'unlink' => 'unlink_image_sm_2', 'dir' => 'products_image_sm_2_destination'),
			      array('table' => 'products_image_xl_2', 'delete' => 'delete_image_xl_2', 'unlink' => 'unlink_image_xl_2', 'dir' => 'products_image_xl_2_destination'),
			      array('table' => 'products_image_sm_3', 'delete' => 'delete_image_sm_3', 'unlink' => 'unlink_image_sm_3', 'dir' => 'products_image_sm_3_destination'),
			      array('table' => 'products_image_xl_3', 'delete' => 'delete_image_xl_3', 'unlink' => 'unlink_image_xl_3', 'dir' => 'products_image_xl_3_destination'),
			      array('table' => 'products_image_sm_4', 'delete' => 'delete_image_sm_4', 'unlink' => 'unlink_image_sm_4', 'dir' => 'products_image_sm_4_destination'),
			      array('table' => 'products_image_xl_4', 'delete' => 'delete_image_xl_4', 'unlink' => 'unlink_image_xl_4', 'dir' => 'products_image_xl_4_destination'),
			      array('table' => 'products_image_sm_5', 'delete' => 'delete_image_sm_5', 'unlink' => 'unlink_image_sm_5', 'dir' => 'products_image_sm_5_destination'),
			      array('table' => 'products_image_xl_5', 'delete' => 'delete_image_xl_5', 'unlink' => 'unlink_image_xl_5', 'dir' => 'products_image_xl_5_destination'),
			      array('table' => 'products_image_sm_6', 'delete' => 'delete_image_sm_6', 'unlink' => 'unlink_image_sm_6', 'dir' => 'products_image_sm_6_destination'),
			      array('table' => 'products_image_xl_6', 'delete' => 'delete_image_xl_6', 'unlink' => 'unlink_image_xl_6', 'dir' => 'products_image_xl_6_destination')
			     );
      }else{
	      $images = array(array('table' => 'products_image', 'delete' => 'delete_image', 'unlink' => 'unlink_image', 'dir' => 'products_image_destination'),
			      array('table' => 'products_image_sm_1', 'delete' => 'delete_image_sm_1', 'unlink' => 'unlink_image_sm_1', 'dir' => 'products_image_sm_1_destination'),
			      array('table' => 'products_image_sm_2', 'delete' => 'delete_image_sm_2', 'unlink' => 'unlink_image_sm_2', 'dir' => 'products_image_sm_2_destination'),
			      array('table' => 'products_image_sm_3', 'delete' => 'delete_image_sm_3', 'unlink' => 'unlink_image_sm_3', 'dir' => 'products_image_sm_3_destination'),
			      array('table' => 'products_image_sm_4', 'delete' => 'delete_image_sm_4', 'unlink' => 'unlink_image_sm_4', 'dir' => 'products_image_sm_4_destination'),
			      array('table' => 'products_image_sm_5', 'delete' => 'delete_image_sm_5', 'unlink' => 'unlink_image_sm_5', 'dir' => 'products_image_sm_5_destination'),
			      array('table' => 'products_image_sm_6', 'delete' => 'delete_image_sm_6', 'unlink' => 'unlink_image_sm_6', 'dir' => 'products_image_sm_6_destination'),
			     );

     }
      foreach ($images as $image) {
        if (isset($_POST[$image['delete']]) && $_POST[$image['delete']] == 'on' && (isset($products_old[$image['table']]) && $products_old[$image['table']] != '')) {
          if(file_exists(DIR_FS_CATALOG_PRODUCTS . $products_old[$image['table']]))
          	unlink(DIR_FS_CATALOG_PRODUCTS . $products_old[$image['table']]);
          $sql_data_array[$image['table']] = '';
          if(ENABLE_ALLOW_ALL_SIZE == 'False'){//removing from all field as it is only one image upload
		  if($image['table'] == 'products_image'){
		       $sql_data_array['products_image_med'] = '';$sql_data_array['products_image_lrg'] = '';
		  }
		  if($image['table'] == 'products_image_sm_1'){ $sql_data_array['products_image_xl_1'] = '';}
		  if($image['table'] == 'products_image_sm_2'){ $sql_data_array['products_image_xl_2'] = '';}
		  if($image['table'] == 'products_image_sm_3'){ $sql_data_array['products_image_xl_3'] = '';}
		  if($image['table'] == 'products_image_sm_4'){ $sql_data_array['products_image_xl_4'] = '';}
		  if($image['table'] == 'products_image_sm_5'){ $sql_data_array['products_image_xl_5'] = '';}
		  if($image['table'] == 'products_image_sm_6'){ $sql_data_array['products_image_xl_6'] = '';}
          }
       } elseif (isset($_POST[$image['unlink']]) && $_POST[$image['unlink']] == 'on' && (isset($products_old[$image['table']]) && $products_old[$image['table']] != '')) {
          $sql_data_array[$image['table']] = '';
        } elseif (isset($_FILES[$image['table']]) && tep_not_null($_FILES[$image['table']]['name'])) {
          if (strtolower($_FILES[$image['table']]['name']) != 'none') {
            $uploadFile = DIR_FS_CATALOG_PRODUCTS . urldecode($_POST[$image['dir']]) . $_FILES[$image['table']]['name'];

		   $uploaded_product_image_name = '';
		   if ($uploaded_product_image = new upload($image['table'], DIR_FS_CATALOG_PRODUCTS)) {
			 $uploaded_product_image_name = $uploaded_product_image->filename;
		   }

            if ($uploaded_product_image_name != $products_old[$image['table']]){
               $sql_data_array[$image['table']] = tep_db_prepare_input($uploaded_product_image_name);
			  if(ENABLE_ALLOW_ALL_SIZE == 'False'){//Inserting in associated field of that upload field
				  if($image['table'] == 'products_image'){
					   $sql_data_array['products_image_med'] = tep_db_prepare_input($uploaded_product_image_name);
					   $sql_data_array['products_image_lrg'] = tep_db_prepare_input($uploaded_product_image_name);
				  }
				  if($image['table'] == 'products_image_sm_1'){ $sql_data_array['products_image_xl_1'] = $uploaded_product_image_name;}
				  if($image['table'] == 'products_image_sm_2'){ $sql_data_array['products_image_xl_2'] = $uploaded_product_image_name;}
				  if($image['table'] == 'products_image_sm_3'){ $sql_data_array['products_image_xl_3'] = $uploaded_product_image_name;}
				  if($image['table'] == 'products_image_sm_4'){ $sql_data_array['products_image_xl_4'] = $uploaded_product_image_name;}
				  if($image['table'] == 'products_image_sm_5'){ $sql_data_array['products_image_xl_5'] = $uploaded_product_image_name;}
				  if($image['table'] == 'products_image_sm_6'){ $sql_data_array['products_image_xl_6'] = $uploaded_product_image_name;}
			  }
            }
          } elseif ((isset($products_old[$image['table']]) && $products_old[$image['table']] != '')) {
          	  $sql_data_array[$image['table']] = '';
		  	if(ENABLE_ALLOW_ALL_SIZE == 'False'){//removing from all field as it is only one image upload
			  if($image['table'] == 'products_image'){
			       $sql_data_array['products_image_med'] = '';$sql_data_array['products_image_lrg'] = '';
			  }
			  if($image['table'] == 'products_image_sm_1'){ $sql_data_array['products_image_xl_1'] = '';}
			  if($image['table'] == 'products_image_sm_2'){ $sql_data_array['products_image_xl_2'] = '';}
			  if($image['table'] == 'products_image_sm_3'){ $sql_data_array['products_image_xl_3'] = '';}
			  if($image['table'] == 'products_image_sm_4'){ $sql_data_array['products_image_xl_4'] = '';}
			  if($image['table'] == 'products_image_sm_5'){ $sql_data_array['products_image_xl_5'] = '';}
			  if($image['table'] == 'products_image_sm_6'){ $sql_data_array['products_image_xl_6'] = '';}
		  	}
          }
        } elseif (isset($_POST[$image['table']]) && tep_not_null($_POST[$image['table']])) {
          if (strtolower($_POST[$image['table']]) != 'none') {
            if ($_POST[$image['table']] != $products_old[$image['table']]){
               $sql_data_array[$image['table']] = tep_db_prepare_input($_POST[$image['table']]);
		  if(ENABLE_ALLOW_ALL_SIZE == 'False'){//removing from all field as it is only one image upload
			  if($image['table'] == 'products_image'){
			       $sql_data_array['products_image_med'] = tep_db_prepare_input($_POST[$image['table']]);
			       $sql_data_array['products_image_lrg'] = tep_db_prepare_input($_POST[$image['table']]);
			  }
			  if($image['table'] == 'products_image_sm_1'){ $sql_data_array['products_image_xl_1'] = tep_db_prepare_input($_POST[$image['table']]);}
			  if($image['table'] == 'products_image_sm_2'){ $sql_data_array['products_image_xl_2'] = tep_db_prepare_input($_POST[$image['table']]);}
			  if($image['table'] == 'products_image_sm_3'){ $sql_data_array['products_image_xl_3'] = tep_db_prepare_input($_POST[$image['table']]);}
			  if($image['table'] == 'products_image_sm_4'){ $sql_data_array['products_image_xl_4'] = tep_db_prepare_input($_POST[$image['table']]);}
			  if($image['table'] == 'products_image_sm_5'){ $sql_data_array['products_image_xl_5'] = tep_db_prepare_input($_POST[$image['table']]);}
			  if($image['table'] == 'products_image_sm_6'){ $sql_data_array['products_image_xl_6'] = tep_db_prepare_input($_POST[$image['table']]);}
		  }
            }

          } elseif ($products_old[$image['table']] != '') {
            	$sql_data_array[$image['table']] = '';
		  if(ENABLE_ALLOW_ALL_SIZE == 'False'){//removing from all field as it is only one image upload
			  if($image['table'] == 'products_image'){
			       $sql_data_array['products_image_med'] = '';$sql_data_array['products_image_lrg'] = '';
			  }
			  if($image['table'] == 'products_image_sm_1'){ $sql_data_array['products_image_xl_1'] = '';}
			  if($image['table'] == 'products_image_sm_2'){ $sql_data_array['products_image_xl_2'] = '';}
			  if($image['table'] == 'products_image_sm_3'){ $sql_data_array['products_image_xl_3'] = '';}
			  if($image['table'] == 'products_image_sm_4'){ $sql_data_array['products_image_xl_4'] = '';}
			  if($image['table'] == 'products_image_sm_5'){ $sql_data_array['products_image_xl_5'] = '';}
			  if($image['table'] == 'products_image_sm_6'){ $sql_data_array['products_image_xl_6'] = '';}
		  }
          }
        }
      }

      // check to see if there is anything to actually update in the products table
      if (count($sql_data_array) > 0 ) {
        $sql_data_array['products_last_modified'] = 'now()';
        tep_db_perform(TABLE_PRODUCTS, $sql_data_array, 'update', 'products_id = ' . (int)$products_id);
      }
	}
  }

  public static function linkProduct($products_id=0, $data=array()) {
	$categories_id = isset($data['categories_id'])?(int)$data['categories_id']:0;
	if($products_id > 0 && $categories_id > 0) {
		$check_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_TO_CATEGORIES . " where products_id = '" . (int)$products_id . "' and categories_id = '" . (int)$categories_id . "'");
		$check = tep_db_fetch_array($check_query);
		if ($check['total'] <= 0 ) {
		  tep_db_query("insert into " . TABLE_PRODUCTS_TO_CATEGORIES . " (products_id, categories_id) values ('" . (int)$products_id . "', '" . (int)$categories_id . "')");
		}
		$sub_products_query = tep_db_query("select products_id from " . TABLE_PRODUCTS . " where products_parent_id = '" . (int)$products_id . "'");
		while ($sub_products = tep_db_fetch_array($sub_products_query)) {
		  $check_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_TO_CATEGORIES . " where products_id = '" . (int)$sub_products['products_id'] . "' and categories_id = '" . (int)$categories_id . "'");
		  $check = tep_db_fetch_array($check_query);
		  if ($check['total'] <= 0) {
			tep_db_query("insert into " . TABLE_PRODUCTS_TO_CATEGORIES . " (products_id, categories_id) values ('" . (int)$sub_products['products_id'] . "', '" . (int)$categories_id . "')");
		  }
		}
	 }
  }
  public static function duplicateProduct($products_id=0, $data=array()) {
	$products_id = (int) $products_id;
	if($products_id <= 0) {
		return false;
	}
	$product_query = tep_db_query("SELECT * from " . TABLE_PRODUCTS . " where products_id = '" . (int)$products_id . "'");
	$product = tep_db_fetch_array($product_query);
	$product['products_model'] = $product['products_model'].'_COPY_'.time();

	unset($product['products_id']);
	$sql_data_array = array();
	foreach($product as $pKey=>$pVal) {
		$sql_data_array[$pKey] = $pVal;
	}

	$dup_products_id = 0;
	if(count($sql_data_array) > 0) {
		tep_db_perform(TABLE_PRODUCTS, $sql_data_array);
		$dup_products_id = tep_db_insert_id();
	}
	if($dup_products_id <= 0) {
		return false;
	}

	//Insert the product description
	$description_query = tep_db_query("select * from " . TABLE_PRODUCTS_DESCRIPTION . " where products_id = '" . (int)$products_id . "'");
	while ($description = tep_db_fetch_array($description_query)) {
		unset($description['products_id']);
		$slug = $description['permalink_name'].'-COPY-'.time();
		$description['products_id'] = $dup_products_id;
		$description['permalink_name'] = $slug;
		$language_id = $description['language_id'];

		$sql_data_array = array();
		foreach($description as $pdKey=>$pdVal) {
			$sql_data_array[$pdKey] = $pdVal;
		}
		tep_db_perform(TABLE_PRODUCTS_DESCRIPTION, $sql_data_array);

		$insert_permalink_data = array('products_id' => $dup_products_id,
							 'language_id' => $language_id,
							 'route' => 'core/product_info',
							 'permalink_type' => 'product',
							 'permalink_name' => $slug);
		tep_db_perform(TABLE_PERMALINK, $insert_permalink_data);
	}

	//Insert the Category
	$categories_id = isset($data['categories_id'])?$data['categories_id']:0;
	tep_db_query("insert into " . TABLE_PRODUCTS_TO_CATEGORIES . " (products_id, categories_id) values ('" . (int)$dup_products_id . "', '" . (int)$categories_id . "')");

	//Copy Attribues
	$products_id_from=tep_db_input($products_id);
	$products_id_to= $dup_products_id;
	$products_id = $dup_products_id;
	if ( (isset($data['copy_attributes']) && $data['copy_attributes']=='copy_attributes_yes') && (isset($data['copy_as']) && $data['copy_as'] == 'duplicate') ) {
		$params = array();
		$params['copy_attributes_delete_first'] = 1;
		$params['copy_attributes_duplicates_skipped'] = 1;
		$params['copy_attributes_duplicates_overwrite'] = 0;
		if (DOWNLOAD_ENABLED == 'true') {
		  $params['copy_attributes_include_downloads'] = 1;
		  $params['copy_attributes_include_filename'] = 1;
		} else {
		  $params['copy_attributes_include_downloads'] = 0;
		  $params['copy_attributes_include_filename'] = 0;
		}
		tep_copy_products_attributes($products_id_from, $products_id_to, $params);
	}

	//Copy Sub Products
	$sub_products_query = tep_db_query("select * from " . TABLE_PRODUCTS . " where products_parent_id = '" . (int)$products_id . "'");
	while ($sub_products = tep_db_fetch_array($sub_products_query)) {

		$sub_products_id = $sub_products['products_id'];
		unset($sub_products['products_id']);
		unset($sub_products['products_parent_id']);
		$sql_data_array = array();
		foreach($sub_products as $spKey=>$spVal) {
			$sql_data_array[$spKey] = $spVal;
		}
		$sql_data_array['products_parent_id'] = $dup_products_id;

		$dup_sub_products_id = 0;
		if(count($sql_data_array) > 0) {
			tep_db_perform(TABLE_PRODUCTS, $sql_data_array);
			$dup_sub_products_id = tep_db_insert_id();
		}
		if($dup_sub_products_id > 0) {
			//Insert the products Description
			$sub_description_query = tep_db_query("SELECT * FROM " . TABLE_PRODUCTS_DESCRIPTION . " WHERE products_id = '" . (int)$sub_products_id . "'");
			while ($sub_description = tep_db_fetch_array($sub_description_query)) {
				unset($sub_description['products_id']);
				$slug = $sub_description['permalink_name'].'-COPY-'.time();
				$sub_description['products_id'] = $dup_sub_products_id;
				$sub_description['permalink_name'] = $slug;
				$language_id = $sub_description['language_id'];

				$sql_data_array = array();
				foreach($sub_description as $pdKey=>$pdVal) {
					$sql_data_array[$pdKey] = $pdVal;
				}
				tep_db_perform(TABLE_PRODUCTS_DESCRIPTION, $sql_data_array);

				$products_id_from=tep_db_input($sub_products_id);
				$products_id_to= $dup_sub_products_id;
				$params = array();
				if ( $data['copy_attributes']=='copy_attributes_yes' and $data['copy_as'] == 'duplicate' ) {
				  $params['copy_attributes_delete_first'] = 1;
				  $params['copy_attributes_duplicates_skipped'] = 0;
				  $params['copy_attributes_duplicates_overwrite'] = 0;
				  if (DOWNLOAD_ENABLED == 'true') {
					$params['copy_attributes_include_downloads'] = 1;
					$params['copy_attributes_include_filename'] = 1;
				  } else {
					$params['copy_attributes_include_downloads'] = 0;
					$params['copy_attributes_include_filename'] = 0;
				  }
				  self::tep_copy_products_attributes($products_id_from,$products_id_to, $params);
				}
			}
		}
	 }
  }

  public static function delete_product_confirm($products_id) {
  }


  public static function copy_products_attributes($products_id_from, $products_id_to, $data=array()) {

	  $copy_attributes_delete_first = isset($data['copy_attributes_delete_first'])?$data['copy_attributes_delete_first']:0;
	  $copy_attributes_duplicates_skipped = isset($data['copy_attributes_duplicates_skipped'])?$data['copy_attributes_duplicates_skipped']:0;
	  $copy_attributes_duplicates_overwrite = isset($data['copy_attributes_duplicates_overwrite'])?$data['copy_attributes_duplicates_overwrite']:0;
	  $copy_attributes_include_downloads = isset($data['copy_attributes_include_downloads'])?$data['copy_attributes_include_downloads']:0;
	  $copy_attributes_include_filename = isset($data['copy_attributes_include_filename'])?$data['copy_attributes_include_filename']:0;


	  // $products_id_to= $copy_to_products_id;
	  // $products_id_from = $pID;
	  $products_copy_to_query= tep_db_query("select products_id from " . TABLE_PRODUCTS . " where products_id='" . $products_id_to . "'");
	  $products_copy_to_check_query= tep_db_query("select products_id from " . TABLE_PRODUCTS . " where products_id='" . $products_id_to . "'");
	  $products_copy_from_query= tep_db_query("select * from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id='" . $products_id_from . "'");
	  $products_copy_from_check_query= tep_db_query("select * from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id='" . $products_id_from . "'");

	// Check for errors in copy request
	  if (!$products_copy_from_check=tep_db_fetch_array($products_copy_from_check_query) or !$products_copy_to_check=tep_db_fetch_array($products_copy_to_check_query) or $products_id_to == $products_id_from ) {
		$error = array();
		if ($products_id_to == $products_id_from) {
		  // same products_id
		  $error = array('code'=>1, 'text'=> CANNOT_COPY_PRODUCT_ERROR_1 . $products_id_from . CANNOT_COPY_PRODUCT_ERROR_2 . $products_id_to . CANNOT_COPY_PRODUCT_ERROR_3 );

		} else {
		  if (!$products_copy_from_check) {
			// no attributes found to copy
			$error = array('code'=>1, 'text'=> NO_ATTRIBUTES_COPY_ERROR_1 . $products_id_from . NO_ATTRIBUTES_COPY_ERROR_2 . tep_get_products_name($products_id_from) . NO_ATTRIBUTES_COPY_ERROR_3);
		  } else {
			// invalid products_id
			$error = array('code'=>1, 'text'=> NO_PRODUCT_ERROR_1 . $products_id_to . NO_PRODUCT_ERROR_2);
		  }
		}
		return $error;
	  } else {

		if ($copy_attributes_delete_first=='1') {
		  // delete all attributes and downloads first
			$products_delete_from_query= tep_db_query("select pa.products_id, pad.products_attributes_id from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad  where pa.products_id='" . $products_id_to . "' and pad.products_attributes_id= pa.products_attributes_id");
			while ( $products_delete_from=tep_db_fetch_array($products_delete_from_query) ) {
			  tep_db_query("delete from " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " where products_attributes_id = '" . $products_delete_from['products_attributes_id'] . "'");
			}
			tep_db_query("delete from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . $products_copy_to_check['products_id'] . "'");
		}
		if(!(isset($rows)) ){
			$rows = '';
		}

		while ( $products_copy_from=tep_db_fetch_array($products_copy_from_query)) {
		  $rows++;
		// This must match the structure of your products_attributes table
		// Current Field Order: products_attributes_id, options_values_price, price_prefix, products_options_sort_order, product_attributes_one_time, products_attributes_weight, products_attributes_weight_prefix, products_attributes_units, products_attributes_units_price
		// First test for existing attribute already being there
		  $check_attribute_query= tep_db_query("select products_id, products_attributes_id, options_id, options_values_id from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id='" . $products_id_to . "' and options_id='" . $products_copy_from['options_id'] . "' and options_values_id ='" . $products_copy_from['options_values_id'] . "'");
		  $check_attribute= tep_db_fetch_array($check_attribute_query);
	// Check if there is a download with this attribute
		  $check_attributes_download_query= tep_db_query("select * from " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " where products_attributes_id ='" . $products_copy_from['products_attributes_id'] . "'");
		  $check_attributes_download=tep_db_fetch_array($check_attributes_download_query);

	// Process Attribute
		  $skip_it=false;
		  switch (true) {
			case ($check_attribute and $copy_attributes_duplicates_skipped):
			  // skip duplicate attributes
	//          echo 'DUPLICATE ' . ' Option ' . $products_copy_from['options_id'] . ' Value ' . $products_copy_from['options_values_id'] . ' Price ' . $products_copy_from['options_values_price'] . ' SKIPPED<br>';
			  $skip_it=true;
			  break;
			case (!$copy_attributes_include_downloads and $check_attributes_download['products_attributes_id']):
			  // skip download attributes
	//          echo 'Download - ' . ' Attribute ID ' . $check_attributes_download['products_attributes_id'] . ' do not copy it<br>';
			  $skip_it=true;
			  break;
			default:
	//          echo '$check_attributes_download ' . $check_attributes_download['products_attributes_id'] . '<br>';
			  if ($check_attributes_download['products_attributes_id']) {
				if (DOWNLOAD_ENABLED=='false' or !$copy_attributes_include_downloads) {
				  // do not copy this download
	//              echo 'This is a download not to be copied <br>';
				  $skip_it=true;
				} else {
				  // copy this download
	//              echo 'This is a download to be copied <br>';
				}
			  }

	// skip anything when $skip_it
			  if (!$skip_it) {
				if ($check_attribute['products_id']) {
				  // Duplicate attribute - update it
	//              echo 'Duplicate - Update ' . $check_attribute['products_id'] . ' Option ' . $check_attribute['options_id'] . ' Value ' . $check_attribute['options_values_id'] . ' Price ' . $products_copy_from['options_values_price'] . '<br>';
				  // tep_db_query("update set " . TABLE_PRODUCTS_ATTRIBUTES . ' ' . options_id=$products_copy_from['options_id'] . "', '" . options_values_id=$products_copy_from['options_values_id'] . "', '" . options_values_price=$products_copy_from['options_values_price'] . "', '" . price_prefix=$products_copy_from['price_prefix'] . "', '" . products_options_sort_order=$products_copy_from['products_options_sort_order'] . "', '" . product_attributes_one_time=$products_copy_from['product_attributes_one_time'] . "', '" . products_attributes_weight=$products_copy_from['products_attributes_weight'] . "', '" . products_attributes_weight_prefix=$products_copy_from['products_attributes_weight_prefix'] . "', '" . products_attributes_units=$products_copy_from['products_attributes_units'] . "', '" . products_attributes_units_price=$products_copy_from['products_attributes_units_price'] . " where products_id='" . $products_id_to . "' and products_attributes_id='" . $check_attribute['products_attributes_id'] . "'");

				  $sql_data_array = array(
					'options_id' => tep_db_prepare_input($products_copy_from['options_id']),
					'options_values_id' => tep_db_prepare_input($products_copy_from['options_values_id']),
					'options_values_price' => tep_db_prepare_input($products_copy_from['options_values_price']),
					'price_prefix' => tep_db_prepare_input($products_copy_from['price_prefix']),
					'products_options_sort_order' => tep_db_prepare_input($products_copy_from['products_options_sort_order']),
				  );

				  $cur_attributes_id = $check_attribute['products_attributes_id'];
				  tep_db_perform(TABLE_PRODUCTS_ATTRIBUTES, $sql_data_array, 'update', 'products_id = \'' . tep_db_input($products_id_to) . '\' and products_attributes_id=\'' . tep_db_input($cur_attributes_id) . '\'');
				} else {
				  // New attribute - insert it
	//              echo 'New - Insert ' . 'Option ' . $products_copy_from['options_id'] . ' Value ' . $products_copy_from['options_values_id']  . ' Price ' . $products_copy_from['options_values_price'] . '<br>';
				  tep_db_query("insert into " . TABLE_PRODUCTS_ATTRIBUTES . " values ('', '" . $products_id_to . "', '" . $products_copy_from['options_id'] . "', '" . $products_copy_from['options_values_id'] . "', '" . $products_copy_from['options_values_price'] . "', '" . $products_copy_from['price_prefix'] . "', '" . $products_copy_from['products_options_sort_order'] . "') ");
				}

	// Manage download attribtues
				if (DOWNLOAD_ENABLED == 'true') {
				  if ($check_attributes_download and $copy_attributes_include_downloads) {
					// copy download attributes
	//                echo 'Download - ' . ' Attribute ID ' . $check_attributes_download['products_attributes_id'] . ' ' . $check_attributes_download['products_attributes_filename'] . ' copy it<br>';
					$new_attribute_query= tep_db_query("select * from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id='" . $products_id_to . "' and options_id='" . $products_copy_from['options_id'] . "' and options_values_id ='" . $products_copy_from['options_values_id'] . "'");
					$new_attribute= tep_db_fetch_array($new_attribute_query);

					$sql_data_array = array(
					  'products_attributes_id' => tep_db_prepare_input($new_attribute['products_attributes_id']),
					  'products_attributes_filename' => tep_db_prepare_input($check_attributes_download['products_attributes_filename']),
					  'products_attributes_maxdays' => tep_db_prepare_input($check_attributes_download['products_attributes_maxdays']),
					  'products_attributes_maxcount' => tep_db_prepare_input($check_attributes_download['products_attributes_maxcount'])
					);

					$cur_attributes_id = $check_attribute['products_attributes_id'];
					tep_db_perform(TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD, $sql_data_array);
				  }
				}
			  } // $skip_it
		  } // end of switch
		} // end of product attributes while loop
	  } // end of no attributes or other errors
	return true;
  }

  public static function getProductInfo($products_id, $adj) {
    global $currencies, $languages_id;

    $product_query = tep_db_query("SELECT p.products_id, pd.products_name, p.products_quantity, p.products_image, p.products_price,
                                          p.products_date_added, p.products_last_modified, p.products_date_available, p.products_status,
                                          p.products_model, p.products_sku, p.products_tax_class_id
                                    FROM " . TABLE_PRODUCTS . " p,
                                         " . TABLE_PRODUCTS_DESCRIPTION . " pd
                                    WHERE p.products_id = pd.products_id
                                      and p.products_id = " . (int)$products_id . "
                                      and pd.language_id = " . (int)$languages_id);

    $product = tep_db_fetch_array($product_query);

    $product['products_base_price'] = $product['products_price'];
    $product['products_base_price_formatted'] = $currencies->format($product['products_base_price'], 2);

    // price override adjustment
    if ($adj != '0') {
      $product['products_price'] = $product['products_price'] + (float)$adj;
    }

    $product['products_has_attributes'] = self::hasProductAttributes($products_id);
    $product['products_attributes'] = array();
    if (self::hasProductAttributes($products_id)) {
      $product['products_attributes'] = self::getProductAttributesHtml($products_id);
    }

    $product['products_tax_rate'] = tep_get_tax_rate($product['products_tax_class_id']);
    $product['products_tax'] = tep_calculate_tax($product['products_price'], $product['products_tax_rate']);
    $product['products_price_fixed'] = number_format($product['products_price'], 2);
    $product['products_price_formatted'] = $currencies->format($product['products_price'], 2);
    $product['products_price_tax_formatted'] = $currencies->format(($product['products_price'] + $product['products_tax']), 2);

    return $product;
  }

  public static function getProductParameters() {
    $parameters = array('products_name' => '',
                   'products_description' => '',
                   'products_url' => '',
                   'products_id' => '',
                   'products_quantity' => '',
                   'products_model' => '',
                   'products_sku' => '',
                   'products_image' => '',
                   'products_image_med' => '',
                   'products_image_lrg' => '',
                   'products_image_sm_1' => '',
                   'products_image_xl_1' => '',
                   'products_image_sm_2' => '',
                   'products_image_xl_2' => '',
                   'products_image_sm_3' => '',
                   'products_image_xl_3' => '',
                   'products_image_sm_4' => '',
                   'products_image_xl_4' => '',
                   'products_image_sm_5' => '',
                   'products_image_xl_5' => '',
                   'products_image_sm_6' => '',
                   'products_image_xl_6' => '',
                   'products_price' => '',
                   'products_weight' => '',
                   'products_date_added' => '',
                   'products_last_modified' => '',
                   'products_date_available' => date('Y-m-d'),
                   'products_status' => '',
                   'products_tax_class_id' => '',
                   'manufacturers_id' => '');

    return $parameters;
  }

  public static function getImageUploadDirOptions() {

    $manage_image = new DirSelect($ImageLocations);
    $image_dir = $manage_image->getDirs();
    $file_dir = '<option value="">/</option>';
    foreach($image_dir as $relative => $fullpath) {
      if (substr($relative, -1) == '/'){
        $relative = substr($relative, 1);
        $file_dir .= '<option value="' . rawurlencode($relative) . '">' . $relative . '</option>';
      }
    }
    unset($image_dir, $manage_image, $relative, $fullpath);

    return $file_dir;
  }

  public static function copyProductAttributes($products_id_from, $products_id_to) {
    global $languages_id, $messageStack;

    $copy_attributes_delete_first = (isset($_POST['copy_attributes_delete_first']) && $_POST['copy_attributes_delete_first'] == 'on') ? '1' : '0';
    $copy_attributes_duplicates_overwrite = (isset($_POST['copy_attributes_duplicates_overwrite']) && $_POST['copy_attributes_duplicates_overwrite'] == 'on') ? '1' : '0';
    $copy_attributes_duplicates_skipped = (isset($_POST['copy_attributes_duplicates_skipped']) && $_POST['copy_attributes_duplicates_skipped'] == 'on') ? '1' : '0';
    $copy_attributes_include_downloads = (isset($_POST['copy_attributes_include_downloads']) && $_POST['copy_attributes_include_downloads'] == 'on') ? '1' : '0';

    $products_copy_to_query = tep_db_query("select products_id from " . TABLE_PRODUCTS . " where products_id='" . $products_id_to . "'");
    $products_copy_to_check_query = tep_db_query("select products_id from " . TABLE_PRODUCTS . " where products_id='" . $products_id_to . "'");
    $products_copy_from_query = tep_db_query("select * from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id='" . $products_id_from . "'");
    $products_copy_from_check_query = tep_db_query("select * from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id='" . $products_id_from . "'");

    // Check for errors in copy request
    $error = false;
    if ( (!$products_copy_from_check = tep_db_fetch_array($products_copy_from_check_query)) ||
         (!$products_copy_to_check = tep_db_fetch_array($products_copy_to_check_query)) ||
         ($products_id_to == $products_id_from) ) {

      if ($products_id_to == $products_id_from) {
        // same products_id
        $error = true;
        $messageStack->add_session('categories', sprintf(WARNING_CANNOT_COPY_TO_SAME_PRODUCT, Product::getProductName($products_id_from, $languages_id), Product::getProductName($products_id_to, $languages_id)), 'warning');
      } else {
        if (!$products_copy_from_check) {
          // no attributes found to copy
          $error = true;
          $messageStack->add_session('categories', sprintf(WARNING_NO_ATTRIBUTES_FOUND, Product::getProductName($products_id_from, $languages_id), Product::getProductName($products_id_to, $languages_id)), 'error');
        } else {
          // invalid products_id
          $error = true;
          $messageStack->add_session('categories', sprintf(WARNING_TARGET_DOES_NOT_EXIST, Product::getProductName($products_id_from, $languages_id), Product::getProductName($products_id_to, $languages_id)), 'error');
        }
      }

      return $error;

    } else {

      if (false) { // Used for testing
      echo $products_id_from . 'x' . $products_id_to . '<br>';
      echo $copy_attributes_delete_first;
      echo $copy_attributes_duplicates_skipped;
      echo $copy_attributes_duplicates_overwrite;
      echo $copy_attributes_include_downloads;
      echo $copy_attributes_include_filename . '<br>';
      } // true for testing

      if ($copy_attributes_delete_first == '1') {
        // delete all attributes and downloads first
        $products_delete_from_query= tep_db_query("select pa.products_id, pad.products_attributes_id from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad  where pa.products_id='" . $products_id_to . "' and pad.products_attributes_id= pa.products_attributes_id");
        while ( $products_delete_from=tep_db_fetch_array($products_delete_from_query) ) {
          tep_db_query("delete from " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " where products_attributes_id = '" . $products_delete_from['products_attributes_id'] . "'");
        }
        tep_db_query("delete from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . $products_copy_to_check['products_id'] . "'");
      }
      if (!(isset($rows))) {
        $rows = 0;
      }

      while ($products_copy_from = tep_db_fetch_array($products_copy_from_query)) {
        $rows++;
        // This must match the structure of your products_attributes table
        // Current Field Order: products_attributes_id, options_values_price, price_prefix, products_options_sort_order, product_attributes_one_time, products_attributes_weight, products_attributes_weight_prefix, products_attributes_units, products_attributes_units_price
        // First test for existing attribute already being there
        $check_attribute_query= tep_db_query("select products_id, products_attributes_id, options_id, options_values_id from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id='" . $products_id_to . "' and options_id='" . $products_copy_from['options_id'] . "' and options_values_id ='" . $products_copy_from['options_values_id'] . "'");
        $check_attribute= tep_db_fetch_array($check_attribute_query);
        // Check if there is a download with this attribute
        $check_attributes_download_query= tep_db_query("select * from " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " where products_attributes_id ='" . $products_copy_from['products_attributes_id'] . "'");
        $check_attributes_download=tep_db_fetch_array($check_attributes_download_query);

        // Process Attribute
        $skip_it = false;
        switch (true) {
          case ($check_attribute and $copy_attributes_duplicates_skipped):
            // skip duplicate attributes
            //echo 'DUPLICATE ' . ' Option ' . $products_copy_from['options_id'] . ' Value ' . $products_copy_from['options_values_id'] . ' Price ' . $products_copy_from['options_values_price'] . ' SKIPPED<br>';
            $skip_it=true;
            break;
          case (!$copy_attributes_include_downloads and $check_attributes_download['products_attributes_id']):
            // skip download attributes
            //echo 'Download - ' . ' Attribute ID ' . $check_attributes_download['products_attributes_id'] . ' do not copy it<br>';
            $skip_it=true;
            break;
          default:
            //echo '$check_attributes_download ' . $check_attributes_download['products_attributes_id'] . '<br>';
            if ($check_attributes_download['products_attributes_id']) {
              if (DOWNLOAD_ENABLED=='false' or !$copy_attributes_include_downloads) {
                // do not copy this download
                //echo 'This is a download not to be copied <br>';
                $skip_it=true;
              } else {
                // copy this download
                //echo 'This is a download to be copied <br>';
              }
            }

            // skip anything when $skip_it
            if (!$skip_it) {
              if ($check_attribute['products_id']) {
                // Duplicate attribute - update it
                //echo 'Duplicate - Update ' . $check_attribute['products_id'] . ' Option ' . $check_attribute['options_id'] . ' Value ' . $check_attribute['options_values_id'] . ' Price ' . $products_copy_from['options_values_price'] . '<br>';
                // tep_db_query("update set " . TABLE_PRODUCTS_ATTRIBUTES . ' ' . options_id=$products_copy_from['options_id'] . "', '" . options_values_id=$products_copy_from['options_values_id'] . "', '" . options_values_price=$products_copy_from['options_values_price'] . "', '" . price_prefix=$products_copy_from['price_prefix'] . "', '" . products_options_sort_order=$products_copy_from['products_options_sort_order'] . "', '" . product_attributes_one_time=$products_copy_from['product_attributes_one_time'] . "', '" . products_attributes_weight=$products_copy_from['products_attributes_weight'] . "', '" . products_attributes_weight_prefix=$products_copy_from['products_attributes_weight_prefix'] . "', '" . products_attributes_units=$products_copy_from['products_attributes_units'] . "', '" . products_attributes_units_price=$products_copy_from['products_attributes_units_price'] . " where products_id='" . $products_id_to . "' and products_attributes_id='" . $check_attribute['products_attributes_id'] . "'");

                $sql_data_array = array(
                  'options_id' => tep_db_prepare_input($products_copy_from['options_id']),
                  'options_values_id' => tep_db_prepare_input($products_copy_from['options_values_id']),
                  'options_values_price' => tep_db_prepare_input($products_copy_from['options_values_price']),
                  'price_prefix' => tep_db_prepare_input($products_copy_from['price_prefix']),
                  'products_options_sort_order' => tep_db_prepare_input($products_copy_from['products_options_sort_order']),
                );

                $cur_attributes_id = $check_attribute['products_attributes_id'];
                tep_db_perform(TABLE_PRODUCTS_ATTRIBUTES, $sql_data_array, 'update', 'products_id = \'' . tep_db_input($products_id_to) . '\' and products_attributes_id=\'' . tep_db_input($cur_attributes_id) . '\'');
              } else {
                // New attribute - insert it
                //echo 'New - Insert ' . 'Option ' . $products_copy_from['options_id'] . ' Value ' . $products_copy_from['options_values_id']  . ' Price ' . $products_copy_from['options_values_price'] . '<br>';
                tep_db_query("insert into " . TABLE_PRODUCTS_ATTRIBUTES . " values ('', '" . $products_id_to . "', '" . $products_copy_from['options_id'] . "', '" . $products_copy_from['options_values_id'] . "', '" . $products_copy_from['options_values_price'] . "', '" . $products_copy_from['price_prefix'] . "', '" . $products_copy_from['products_options_sort_order'] . "') ");
              }

              // Manage download attribtues
              if (DOWNLOAD_ENABLED == 'true') {
                if ($check_attributes_download and $copy_attributes_include_downloads) {
                  // copy download attributes
                  //echo 'Download - ' . ' Attribute ID ' . $check_attributes_download['products_attributes_id'] . ' ' . $check_attributes_download['products_attributes_filename'] . ' copy it<br>';
                  $new_attribute_query= tep_db_query("select * from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id='" . $products_id_to . "' and options_id='" . $products_copy_from['options_id'] . "' and options_values_id ='" . $products_copy_from['options_values_id'] . "'");
                  $new_attribute= tep_db_fetch_array($new_attribute_query);

                  $sql_data_array = array(
                    'products_attributes_id' => tep_db_prepare_input($new_attribute['products_attributes_id']),
                    'products_attributes_filename' => tep_db_prepare_input($check_attributes_download['products_attributes_filename']),
                    'products_attributes_maxdays' => tep_db_prepare_input($check_attributes_download['products_attributes_maxdays']),
                    'products_attributes_maxcount' => tep_db_prepare_input($check_attributes_download['products_attributes_maxcount'])
                  );

                  $cur_attributes_id = $check_attribute['products_attributes_id'];
                  tep_db_perform(TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD, $sql_data_array);
                }
              }
            } // $skip_it
        } // end of switch
      } // end of product attributes while loop

      $messageStack->add_session('categories', sprintf(SUCCESS_ATTRIBUTES_COPIED, Product::getProductName($products_id_from, $languages_id), Product::getProductName($products_id_to, $languages_id)), 'success');
    } // end of no attributes or other errors
  }

  public static function hasProductAttributes($products_id) {
    global $languages_id;

    $products_attributes = tep_db_query("select poptt.products_options_name from " . TABLE_PRODUCTS_OPTIONS . " popt,  " . TABLE_PRODUCTS_OPTIONS_TEXT  . " poptt, " . TABLE_PRODUCTS_ATTRIBUTES . " patrib where patrib.products_id='" . $products_id . "' and patrib.options_id = popt.products_options_id and poptt.language_id = '" . $languages_id . "'");

    $result = (tep_db_num_rows($products_attributes)) ? true : false;

    return $result;
  }

  public static function getProductAttributesHtml($products_id) {
    global $languages_id;

    $result = array();
    $attributes = new creAttributes();
    if ($attributes->load($products_id)) {
      $options_HTML = $attributes->get_HTML();
      if (count($options_HTML) > 0) {
        foreach ($options_HTML as $op_data) {
          $result[] = array('label' => $op_data['label'], 'html' => $op_data['HTML']);
        } //end of foreach
      }  // end of count
    } // end of new attributes

    return $result;
  }

  public static function getProductAttributes($products_id) {
    global $languages_id;

    $result = array();
    $attributes = new creAttributes();
    if ($attributes->load($products_id)) {
      $result['options'] = $attributes->get_options();
      $result['values'] = $attributes->get_values();
    } // end of new attributes

    return $result;
  }

  public static function getProductName($products_id, $language_id) {
    $product_query = tep_db_query("SELECT products_name FROM " . TABLE_PRODUCTS_DESCRIPTION . " WHERE products_id = '" . $products_id . "' AND language_id = '" . $language_id . "'");
    $product = tep_db_fetch_array($product_query);

    return $product['products_name'];
  }
}
?>