<?php

class IMWB_Zonpress_module_ebay {

   var $module_name = "ebay";
   var $options = Array();
   var $currency_symbols = Array();
   var $ebay_siteid_currency = array("0" => '$',"3" => '£',"2" => '$',"210" => '$',"15" => '$',"16" => '€',"123" => '€',"23" => '€',"223" => '￥',"71" => '€',"77" => '€',"201" => 'HK$',"100" => '$',"203" => '₨',"205" => '€',"101" => '€',"146" => '€',"186" => '€',"193" => 'CHF',"196" => 'TW$'); 
   
   /**
    * The constructor is executed when the class is instatiated and the plugin gets loaded.
    * @return void
    */
   function IMWB_Zonpress_module_ebay($options, $currency_symbols) {
      $this->options = $options; 
      $this->currency_symbols = $currency_symbols;
   }

   
   function search($keyword, $numPosts = 0, $startItem = 0) {
      global $wpdb;
    
      $existingProducts = false;
      $numCreated = 0;
      $keyword = str_replace('"', '', trim($keyword));

      // Loop through the result pages until we create enough posts
      $page = 0;
      do {
      
         $params = '&QueryKeywords='.urlencode($keyword);
         $params.= '&MaxEntries=100';

         $resultxml = $this->ebay_request('FindPopularItems', $this->options['ebayappid'], $this->options['ebaysiteid'], $params, $this->options['ebayid']);

         if(!empty($resultxml["error"])) {return $resultxml;}
         
         if (isset($resultxml->Errors)) {
            $return["error"]["module"] = "eBay";
            $errorCode = (string)$resultxml->Errors->ErrorCode;
         	
         	if($errorCode == "10.20") {
         	   if($existingProducts)
         	      $message = __('Sorry, there are no more products for that search term. Please try using a different keyword or phrase to find more products.', 'imwb_zonpress' );
         	   else
         	      $message = __('Sorry, we couldn\'t find any products for that search term. Please try using a different keyword or phrase', 'imwb_zonpress' );
         	}
         	else {
         		$message = 'There was a problem with your ebay API request: <i><b>'.$resultxml->Errors->ErrorCode.':</b> '.$resultxml->Errors->LongMessage.'</i>';	
         	}
         	
         	$return["error"]["reason"] = "API fail";
         	$return["error"]["message"] = $message;	
         	return $return;
         }
                  
         foreach($resultxml->ItemArray->Item as $item) {	
             
            $page++;
            if($startItem > $page)
               continue;
             
            // Get the unique ID
            $post_id = trim($item->ItemID);

            // Get the title
            $post_title = (string)$item->Title;
            
            // Check for exisintg post         
   			$results = $wpdb->get_row( $wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s", 'imwb_cc_ebay_itemid', $post_id) );
   			
   			if(count($results) > 0) {
   				$existingProducts = true;
   			   continue;			   
   			}
   			         
            // Get the description
            $post_desc = "N/A";
   			   			            
            // Get the image
            $post_image = $item->GalleryURL;
           
            // Get the price
            $post_price = (string)$item->ConvertedCurrentPrice;
            if(is_numeric($post_price)) {
               $post_price = number_format((float)$post_price,2);
               $post_price = $this->ebay_siteid_currency[$this->options['ebaysiteid']].$post_price;
            }

           // echo "Title: $post_title<br>Content: $post_content<br>CatId:$post_category<br>AuthorId:$post_author<br><br>";

            $return["results"][$post_id] = Array('network' => 'eBay', 'title' => $post_title, 'desc' => $post_desc, 'image' => $post_image, 'price' => $post_price, 'sourceUrl' => $item->ViewItemURLForNaturalSearch);
            
            $numCreated++;
                 
            if( $numCreated == $numPosts)
               break;
         }

         // Page Loop
         if( $numCreated == $numPosts)
            break; 
            
         $page+=100;        
                     
      } while($page <= 100);   
      
       $return["num_posts"] = $numCreated;
       $return["next_page"] = $page < 100 ? $page : 0;
      
      return $return;
   }
   
   function import_items($itemids, $poststatus, $postcat) {
   
      $errors = Array();
      foreach ($itemids as $itemId) {
         $result = $this->import_item($itemId, $poststatus, $postcat);
         if(is_array($result)) {
            $errors[] = $result["error"]["module"].": ".$result["error"]["message"]."<br>";  
         }
      }
      
      return $errors;
   
   }
   
   function import_item($itemId, $poststatus, $postcat) {
      global $wpdb;

      $params = '&ItemID='.$itemId;
      $params.= '&IncludeSelector=Details,TextDescription';

      $resultxml = $this->ebay_request('GetSingleItem', $this->options['ebayappid'], $this->options['ebaysiteid'], $params, $this->options['ebayid']);
   
      if(!empty($resultxml["error"])) {return $resultxml;}
         
      if (isset($resultxml->Error)) {
      	$message = 'There was a problem with your eBay API request: <i><b>'.$resultxml->Error->Code.':</b> '.$resultxml->Error->Message.'</i>';	
      	$return["error"]["module"] = "eBay";
      	$return["error"]["reason"] = "API fail";
      	$return["error"]["message"] = $message;	
      	return $return;
      }
      
      if (isset($resultxml->Items->Error)) {
      	$message = 'There was a problem with your eBay API request: <i><b>'.$resultxml->Items->Error->Code.':</b> '.$resultxml->Items->Error->Message.'</i>';	
      	$return["error"]["module"] = "eBay";
      	$return["error"]["reason"] = "API fail";
      	$return["error"]["message"] = $message;	
      	return $return;
      }
      
      if (isset($resultxml->Items->Request->Errors)) {
      	$message = 'There was a problem with your eBay API request: <i><b>'.$resultxml->Items->Request->Errors->Error->Code.':</b> '.$resultxml->Items->Request->Errors->Error->Message.'</i>';	
      	$return["error"]["module"] = "eBay";
      	$return["error"]["reason"] = "API fail";
      	$return["error"]["message"] = $message;	
      	return $return;
      }
         
      $item = $resultxml->Item;
      
      $post_itemid = trim($item->ItemID);
      
      // Get the title
      $post_title = (string)$item->Title;
      
      // Check for exisintg post         
		$results = $wpdb->get_row( $wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s", 'imwb_cc_ebay_itemid', $post_itemid) );
		
		if(count($results) > 0) 
		   return true;
		   
	   $post_link = trim((string)$item->ViewItemURLForNaturalSearch);
      
      // Get the description
      $desc = (string)$item->Description;
		   			
      // set category
      $post_category = $postcat;
      
      // Get the price
      $post_price = (string)$item->CurrentPrice;
      if(is_numeric($post_price)) 
         $post_price = number_format((float)$post_price,2);

      $post_currency = $this->ebay_siteid_currency[$this->options['ebaysiteid']];
      
      // Get The Tags
      $post_tags = array();	
      if($this->options['createtags'] == 'Y') {
         $post_tags = imwb_zonpress_theme_products_get_tags($post_title, $this->options['badtags']);
      }

      // Save Post
      $post_content = wpautop($desc);
      $post_type = "post";
      $post_date = current_time('mysql');
      $post_date_gmt = current_time('mysql', 1);
      $post_author = 1;
      $post_status =  $poststatus;

//     echo "Title: $post_title<br>Content: $post_content<br>CatId:$post_category<br>AuthorId:$post_author<br>Post Price:$post_price<br>Post Currency:$post_currency<br>";

     	$post_data = compact('post_content','post_title','post_date','post_date_gmt','post_author','post_category', 'post_status', 'post_type');		
      $post_data['tags_input'] = implode(',', $post_tags);
      $post_data = add_magic_quotes($post_data);
      $postId = wp_insert_post($post_data);
      if (is_wp_error($postId)) {
         $return["error"]["module"] = "eBay ($keyword)";
         $return["error"]["reason"] = "Error Inserting Post";
         $return["error"]["message"] = $postId->get_error_message();	
         return $return;
      }
      
      // Store the product ID so we don't post duplicates
      update_post_meta( $postId , 'imwb_cc_ebay_itemid', $post_itemid );
      
      // Update Featured image
      $post_image = $item->PictureURL;
      if($post_image != "") 
         imwb_zonpress_theme_products_set_featured_image($postId, $post_image);
      
      // Set CSB Metadata fields
      update_post_meta( $postId, 'imwb_zonpress_post_producturl', $post_link);
      update_post_meta( $postId, 'imwb_zonpress_post_price', $post_price);
      update_post_meta( $postId, 'imwb_zonpress_post_currency', $post_currency);
      update_post_meta( $postId, '_imwb_zonpress_post_imp', 0 );
      update_post_meta( $postId, '_imwb_zonpress_post_clicks', 0);
      update_post_meta( $postId, '_imwb_zonpress_post_ctr', 0);
      
      // Set other IMWB plugins/themes metadata
      update_post_meta( $postId, 'imwb_interest_post_link_url', $post_link);
      update_post_meta( $postId, 'imwb_interest_post_link_text', 'From eBay');
            
      return true;
   }
      
   function ebay_request($callRef, $appid, $siteid, $params, $campaignid) {
   	libxml_use_internal_errors(true);
   	
   	$requestURL = "http://open.api.ebay.com/shopping?callname=$callRef&responseencoding=XML&appid=$appid&siteid=$siteid&version=713$params";
   	   	
//  echo $requestURL."<br><br>";
   	$user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2; rv:10.0.1) Gecko/20100101 Firefox/10.0.1";
   	$headers = array( 'X-EBAY-API-TRACKING-ID' => $campaignid, 'X-EBAY-API-TRACKING-PARTNER-CODE' => 9 );   	
   	$request = new WP_Http;
   	$response = $request->request( $requestURL , array( 'method' => 'GET', 'headers' => $headers ) );
   	
      if( is_wp_error( $response ) ) {
  	      $return["error"]["module"] = "eBay";
  	      $return["error"]["reason"] = "Error Connecting to eBay API";
  	      $return["error"]["message"] = $response->get_error_message();	
  	      return $return;
     }	 	
// echo '<br><br>Response:<pre>';
//   print_r( $response['body'] );
//   echo '</pre>';
     $pxml = simplexml_load_string($response['body']);
     if ($pxml === False) {
   		$emessage = "Failed loading XML, errors returned: ";
   		foreach(libxml_get_errors() as $error) {
   			$emessage .= $error->message . ", ";
   		}	
   		libxml_clear_errors();
   		$return["error"]["module"] = "eBay";
   		$return["error"]["reason"] = "XML Error";
   		$return["error"]["message"] = $emessage;	
   		return $return;			
   	} else {
   		return $pxml;
   	}
   } 
}


?>