<?php

class IMWB_Zonpress_module_commissionjunction {

   var $module_name = "commissionjunction";
   var $options = Array();
   var $currency_symbols = Array();
   
   /**
    * The constructor is executed when the class is instatiated and the plugin gets loaded.
    * @return void
    */
   function IMWB_Zonpress_module_commissionjunction($options, $currency_symbols) {
      $this->options = $options; 
      $this->currency_symbols = $currency_symbols;
   }

   function search($keyword, $numPosts = 0, $page = 0) {
      global $wpdb;
   
      $existingProducts = false;
      $numCreated = 0;
      $keyword = trim($keyword);

      // Loop through the result pages until we create enough posts
      do {
         
         if(!empty($this->options['cjcids']))
            $advertiserids = $this->options['cjcids'];
         else 
            $advertiserids = $this->options['cjadvertiserids'];
         
         $resultxml = $this->cj_request($keyword, $this->options['cjdevkey'], $this->options['cjwebpid'], $advertiserids, $page);	
      
         if(!empty($resultxml["error"])) {return $resultxml;}
         
         if ($resultxml === False) {
         	$return["error"]["module"] = "Commission Junction";
         	$return["error"]["reason"] = "API Request fail";
         	$return["error"]["message"] = "API request could not be sent.";	
         	return $return;	
         }
         
         if (!isset($resultxml->products->product)) {
         	$return["error"]["module"] = "Commission Junction";
         	$return["error"]["reason"] = "API Request";
         	
         	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' );
         	   
         	$return["error"]["message"] = $message;	
         	return $return;	
         }

         foreach($resultxml->products->product as $item) {	
//print_r($item);
     
            // Get the title
            $post_title = (string)$item->name;
            
            // Build the unique id
            if(!empty($item->upc) && $item->upc != "") {
               $unique = $item->upc;
               $uniqueId = "upc";
            } 
            elseif(!empty($item->sku)) {
               $unique = $item->sku;
               $uniqueId = "sku";
            } 
            elseif(!empty($item->isbn)) {
               $unique = $item->isbn;
               $uniqueId = "isbn";
            }
            
            $post_id = trim((string)$item->{"advertiser-id"});
            $post_id.= '_'.$uniqueId;
            $post_id.= '_'.$unique;
            
//echo $post_id."<br>";            
            // 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_commissionjunction_adid', $post_id) );
   			
   			if(count($results) > 0) {
   				$existingProducts = true;
   			   continue;			   
   			}
   			            
            // Get the description
            $post_desc = (string)$item->description;
   			   				   
            // Get the image
            $post_image = (string)$item->{"image-url"};
            
            // Get the price
            $post_price = $this->currency_symbols[(string)$item->currency].number_format((string)$item->price,2);

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

         // Page Loop
         if( $numCreated == $numPosts)
            break;         
            
         $page++;
                     
      } while($page <= 20);   
      
      $return["num_posts"] = $numCreated;
      $return["next_page"] = $page < 20 ? $page+1 : 1;

      return $return;
   }
   
   function import_items($itemids, $poststatus, $postcat) {
   
      $errors = Array();
      foreach ($itemids as $ADID) {
      
         $result = $this->import_item($ADID, $poststatus, $postcat);
         if(is_array($result)) {
            $errors[] = $result["error"]["module"].": ".$result["error"]["message"]."<br>";  
         }
      }
      
      return $errors;
   
   }
   
   function import_item($ADID, $poststatus, $postcat) {
      global $wpdb;
      
      $uADID = explode('_', $ADID, 3);
      
      $resultxml = $this->cj_request(null, $this->options['cjdevkey'], $this->options['cjwebpid'], $this->options['cjadvertiserids'], 0, $uADID);	
      
      if(!empty($resultxml["error"])) {return $resultxml;}
      
      if ($resultxml === False) {
      	$return["error"]["module"] = "Commission Junction";
      	$return["error"]["reason"] = "API Request fail";
      	$return["error"]["message"] = "API request could not be sent.";	
      	return $return;	
      }
      
      if (!isset($resultxml->products->product)) {
      	$return["error"]["module"] = "Commission Junction";
      	$return["error"]["reason"] = "API Request";
      	$return["error"]["message"] = "API returned no products.";	
      	return $return;	
      }
      
      $item = $resultxml->products->product;

      $post_adid = $ADID;
      
      // Get the title
      $post_title = (string)$item->name;
            
      // 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_commissionjunction_adid', $post_adid) );
      
      if(count($results) > 0) 
         return true;
      
      // Get the description
      $post_desc = (string)$item->description;
         				   
      // Get the image
      $post_image = (string)$item->{"image-url"};
      
      // Get the price
      $post_price = (string)$item->price;
      $post_currency = $this->currency_symbols[(string)$item->currency];
      
      // set category
      $post_category = $postcat;
      
      // 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 = $post_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"] = "Commission Junction";
         $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_commissionjunction_adid', $post_adid );
      
      // Update Featured image
      if($post_image != "") 
         imwb_zonpress_theme_products_set_featured_image($postId, $post_image);
         
      $post_link = trim((string)$item->{"buy-url"});
      
      // 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 Commission Junction');
      
      return true;

   }
   
   function cj_request($keyword, $devkey, $websitepid, $advertiserids, $page, $ADID = null) {
   	libxml_use_internal_errors(true);

   	if(is_null($keyword)) {
   	   $advertisers = $ADID[0];
   	   if($ADID[1] == 'upc')
   	      $keyword = '&upc='.urlencode($ADID[2]);
         else if($ADID[1] == 'isbn')
            $keyword = '&isbn='.urlencode($ADID[2]);
         else if($ADID[1] == 'sku')
            $keyword = '&advertiser-sku='.urlencode($ADID[2]);
            
   	   $page = '';
   	   $sortBy = '';
   	}
   	else {
         $keyword = '&keywords='.urlencode($keyword);
         
         if($advertiserids == 'J')
            $advertisers = 'joined';
         else if($advertiserids == 'N')
            $advertisers = 'notjoined';   	
         else 
            $advertisers = $advertiserids;   	
            
         $page = '&page-number='.$page;
         $sortBy = '&sort-by=Name';
      }
            
   	$requestURL = "https://product-search.api.cj.com/v2/product-search?website-id=$websitepid&advertiser-ids=$advertisers$keyword$page&records-per-page=50$sortBy"; // The request URL used by the API service
   	
//  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( 'Authorization' => $devkey );   	
   	$request = new WP_Http;
   	$response = $request->request( $requestURL , array( 'method' => 'GET', 'headers' => $headers ) );
   	
   	//$response = wp_remote_get($request, array('user-agent' => $user_agent, 'Authorization' => $devkey));
      if( is_wp_error( $response ) ) {
  	      $return["error"]["module"] = "Commission Junction";
  	      $return["error"]["reason"] = "Error Connecting to Commission Junction 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"] = "Commission Junction";
   		$return["error"]["reason"] = "XML Error";
   		$return["error"]["message"] = $emessage;	
   		return $return;			
   	} else {
   		return $pxml;
   	}
   } 
}


?>