<?php
	class Walmart{
		
		function __construct() {
		    global $wpdb;
	    }
		public static function get_products($keyword='',$category='',$site='', $page = '', $per_page='',$info=array()) {
			$filter = array();
			$filter['wpeae_query']= $keyword;
			$filter['category_id']= $category;
			if(isset($filter['wpeae_query'])){


			$per_page = isset($per_page) && $per_page != '' ? $per_page : 12;
			
			/* if ($per_page >= 10) {
			
				$per_page = 10;
			} */
			$count_check = 1;
			//return $per_page;
			$result = array("total" => 0, "per_page" => $per_page, "items" => array(), "error" => "");
			$data = array();
			if ((isset($filter['wpeae_productId']) && !empty($filter['wpeae_productId'])) || (isset($filter['wpeae_query']) && !empty($filter['wpeae_query'])) || (isset($filter['category_id']) && $filter['category_id'] != 0)) {
				//echo 'dedee';


				$endpoint = 'http://api.walmartlabs.com/v1';  // URL to call
				$productId = isset($filter['wpeae_productId']) ? $filter['wpeae_productId'] : "";
				$safeQuery = isset($filter['wpeae_query']) ? urlencode(utf8_encode($filter['wpeae_query'])) : "";
				$price_min = (isset($info['min_price']) && floatval($info['min_price']) > 0.009) ? floatval($info['min_price']) : false;
				$price_max = (isset($info['max_price']) && floatval($info['max_price']) > 0.009) ? floatval($info['max_price']) : false;

				$available_to = (isset($filter['available_to']) && $filter['available_to']) ? $filter['available_to'] : false;

				//retailer
				$site = isset($filter['sitecode']) ? $filter['sitecode'] : false;
				$condition = (isset($filter['condition']) && $filter['condition'] !== "All") ? $filter['condition'] : false;
				$category_id = (isset($filter['category_id']) && IntVal($filter['category_id'])) ? IntVal($filter['category_id']) : 0;
				$link_category_id = (isset($filter['link_category_id']) && IntVal($filter['link_category_id'])) ? IntVal($filter['link_category_id']) : 0;

				$pagenum = (intval($page)) ? $page : 1;

				$currency_conversion_factor = floatval(1);
                $lsPublisherId ='';
				global $wpdb;

				$lsPublisherId  = get_option('affhub_walmart_publisherid',false);
				$apiKey         = get_option('affhub_walmart_apikey','52jcdw5db9qkzs9abjgyhf7f');
				
				$apiKey         = (isset($apiKey)?$apiKey:'');
		
				
				$responseEncoding = 'json';

				if ($productId != '') {
					// Format of the response
					$api_url = "http://api.walmartlabs.com/v1/items?"
							. "apiKey=" . $apiKey
							. ($lsPublisherId ? "&lsPublisherId=" . $lsPublisherId : "")
							. "&format=$responseEncoding"
							. "&ids={$productId}";

                    //echo  $api_url;
					//$tmp_response = wp_remote_get($api_url);
					$response = file_get_contents($api_url);
					if(empty($response)){
						if (!function_exists('curl_init')){ 
							die('CURL is not installed!');
						}
						$ch = curl_init();
						curl_setopt($ch, CURLOPT_URL, $api_url);
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						$response = curl_exec($ch);
						curl_close($ch);
					}
					//print_r($response);
				

					if (is_wp_error($tmp_response)) {
						$result["error"] = 'Walmart api not response!';
					} else {
						$body = wp_remote_retrieve_body($tmp_response);
						$resp = simplexml_load_string($body);

						if (!isset($resp->Errors)) {
                            if($resp->error->code==6001){
							$tmp_res = array("state" => "error", "message" => "" . $resp->error->message, "goods" => $goods);
							}else{ 
							$tmp_res = $this->load_detail(new WPEAE_Goods("walmart#$productId"), array("init_load" => true,
								"link_category_id" => $link_category_id,
								"currency_conversion_factor" => $currency_conversion_factor,
								"item" => $resp->items->item));
							}	
						} else {
							$tmp_res = array("state" => "error", "message" => "" . $resp->Errors->LongMessage, "goods" => $goods);
						}
					}

					if ($tmp_res['state'] == 'ok') {
						$result["total"] = 1;
						$result["items"] = array($tmp_res['goods']);
					} else {
						$result["error"] = $tmp_res['message'];
					}
				} else {

					

					$apicall = "$endpoint/search?"
							. "apiKey=" . $apiKey
							. ($lsPublisherId ? "&lsPublisherId=" . $lsPublisherId : "")
							. "&query=$safeQuery"
							. ($category_id ? "&categoryId=" . $category_id : "")
							. "&format=$responseEncoding"
							. "&responseGroup=full"
							. "&keywords=$safeQuery"
							. "&numItems=$per_page" /* 10 - 25 */
							. "&start=" . (($pagenum - 1) * $per_page + 1)
							. "&sort=price&ord=asc"
							. "&facet=on";

				//echo $apicall;
			//	exit;
					$filter_index = 1;

					if ($price_min && $price_max)
						$apicall.="&facet.range=price:[{$price_min}+TO+{$price_max}]";
					elseif (!$price_min && $price_max)
						$apicall.="&facet.range=price:[*+TO+{$price_max}]";
					elseif ($price_min && !$price_max)
						$apicall.="&facet.range=price:[{$price_min}+TO+*]";

					if ($available_to) {
						$encoded_available_to = urlencode($available_to);
						$apicall.="&facet.filter=pickup_and_delivery:{$encoded_available_to}";
						$filter_index++;
					}

					if ($site) {
						$apicall.="&facet.filter=retailer:{$site}";
						$filter_index++;
					}

					if ($condition) {
						$apicall.="&facet.filter=condition:{$condition}";
						$filter_index++;
					}

					if (isset($_GET['orderby'])) {
						switch ($_GET['orderby']) {
							case 'price':
								if ($_GET['order'] == 'asc') {
									$apicall.="&sort=price&ord=asc";
								} elseif ($_GET['order'] == 'desc') {
									$apicall.="&sort=price&ord=desc";
								}
								break;
							default:
								break;
						}
					}
					
					//echo '<pre>';print_r($apicall);echo '</pre>';
					//$tmp_response = wp_remote_get($apicall);
					$tmp_response = file_get_contents($apicall);
					if(empty($tmp_response)){
						if (!function_exists('curl_init')){ 
							die('CURL is not installed!');
						}
						$ch = curl_init();
						curl_setopt($ch, CURLOPT_URL, $apicall);
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
						$tmp_response = curl_exec($ch);
						curl_close($ch);
					}		
                    $resp = json_decode($tmp_response);					
					


                        //echo'<pre>';print_r($resp);echo'</pre>';
							


						//return $resp;
						//echo '<pre>';print_r($resp);echo '</pre>';

						if(isset($resp->items) && $resp->items!=''){
							//echo'<pre>';print_r($item->items);echo'</pre>';
							foreach ($resp->items as $key => $item) {
//echo'<pre>';print_r($item);echo'</pre>';
								$item = (array) $item;
					            //echo "<pre>";print_r($item);echo "</pre>"; 
					            //exit;
								//$item = json_decode(json_encode($item), TRUE);
								//return $item;
								//$priceCurr = trim(strval($item->sellingStatus->convertedCurrentPrice['currencyId']));
								//print_r($item['sellingStatus']['convertedCurrentPrice']);
								//$priceCurr = trim(strval($item['sellingStatus']['convertedCurrentPrice']['currencyId']));
								//print_r($item['sellingStatus']['convertedCurrentPrice']['currencyId']);
								//echo $priceCurr.'634';
								$productId    = $item['itemId'];

								$productTitle = strip_tags(isset($item['name']) ? $item['name']:'');
								//print_r($productTitle);
								//$globalId     = (isset($item['globalId']) ? $item['globalId']:'');
								//$Category     = (isset($item['primaryCategory']) ? $item['primaryCategory']['categoryName']:'');
								//$location     = (isset($item['location']) ? $item['location']:$item['country']);
								$imageUrl     = (isset($item['thumbnailImage']) ? $item['thumbnailImage']:'');
								$mediumImage  =  (isset($item['mediumImage']) ? $item['mediumImage']:'');
								$productUrl   = str_replace("item=0", "item=".$item['itemId'], $item['productUrl']);
								$largeImage =  (isset($item['largeImage']) ? $item['largeImage']:'');
								
								//$paymentMethod= (isset($item['paymentMethod']) ? $item['paymentMethod']:'');
								//$autoPay      = (isset($item['autoPay']) ? $item['autoPay']:'');
								
								//$storeName =(isset($item['storeInfo']['storeName']) ? $item['storeInfo']['storeName']:'');
								//$storeURL  =(isset($item['storeInfo']['storeURL']) ? $item['storeInfo']['storeURL']:'');
								
								//$sellerUserName =(isset($item['sellerInfo']['sellerUserName']) ? $item['sellerInfo']['sellerUserName']:'');
								//$feedbackScore  =(isset($item['sellerInfo']['feedbackScore']) ? $item['sellerInfo']['feedbackScore']:'');
								//$positiveFeedbackPercent =(isset($item['sellerInfo']['positiveFeedbackPercent']) ? $item['sellerInfo']['positiveFeedbackPercent']:'');

								//$shippingServiceCost =(isset($item['shippingInfo']['shippingServiceCost']) ? $item['shippingInfo']['shippingServiceCost']:'');
								//$shippingType  =(isset($item['shippingInfo']['shippingType']) ? $item['shippingInfo']['shippingType']:'');
								//$shipToLocations =(isset($item['shippingInfo']['shipToLocations']) ? $item['shippingInfo']['shipToLocations']:'');
								//$handlingTime =(isset($item['shippingInfo']['handlingTime']) ? $item['shippingInfo']['handlingTime']:'');								
								
								//$returnsAccepted= (isset($item['returnsAccepted']) ? $item['returnsAccepted']:'');
								//$conditionDisplayName =(isset($item['condition']['conditionDisplayName']) ? $item['condition']['conditionDisplayName']:'');								
								
								$salePrice    = (isset($item['salePrice']) ? $item['salePrice']:'');
								
								$tmp_price = round(self::get_normalize_price($item['salePrice']),2);	
								if(!empty($item['msrp']) && $item['msrp']>$item['salePrice']){	
								$old_price = round(self::get_normalize_price($item['msrp']),2);
								}else{
								$old_price = round(self::get_normalize_price($item['salePrice']),2);	
								}
								
								$description    = (isset($item['shortDescription']) ? $item['shortDescription']:'');


								$rating    = (isset($item['customerRating']) ? $item['customerRating']:'');
								//$currency =   $item['sellingStatus']['convertedCurrentPrice']['currencyId']);
								
								$currency = 'USD';
								//$shipToLocations = (is_array($shipToLocations)?$shipToLocations:array($shipToLocations));
								//$paymentMethod   = (is_array($paymentMethod)?$paymentMethod:array($paymentMethod));
								//$sellerUserName  = (is_array($sellerUserName)?$sellerUserName:array($sellerUserName));

					            $numReviews = $item['numReviews'];
								if(isset($salePrice) && $salePrice != 0 ){			                                
								$goods = array(
						           'external_id'=>$productId,
								   'title'=>$productTitle,							   
						           'image'=>$imageUrl,
								   'product_url'=>$productUrl,
								   'orig_url'=>$productUrl,
                                   'old_price'=>$old_price,								  
								   'tmp_price'=>$tmp_price,
								   'currency'=>getCurrencySymbol('USD'),
								   'description' => $description,
								   'logo' => '',
								   'orig_img_large' => $largeImage,
								   'mediumImage' => $mediumImage,
								   'rating'      => $rating,
								   'reviews'  => $numReviews,
						         );	
                                 $data[] = $goods;
                                 if ($count_check == $per_page ) {
        				   				break;
        				   			}
        				   			$count_check++;
								  /* echo "<pre>";
								  print_r($data);
								  echo "</pre>"; */
								 // echo '677 here';
									//unset($product_data);
								}	
							}

						}

				}
			} else {
				$result["error"] = 'Please enter some search keywords or select item from category list!';
			}
					/* echo "<pre>";
					print_r($result);
					echo "</pre>"; */
			//$result = json_decode(json_encode($result), TRUE);


			return $data;
		}
		else{
			return '';
		}
		}

		public function load_detail($id, $params = array()) {
			$init_load = isset($params["init_load"]) ? $params["init_load"] : false;
			if ($init_load) {
				$link_category_id = isset($params["link_category_id"]) ? $params["link_category_id"] : 0;

				$currency_conversion_factor = isset($params["currency_conversion_factor"]) ? $params["currency_conversion_factor"] : false;
				$item = isset($params["item"]) ? $params["item"] : false;

				$goods->type = "walmart";
				$goods->external_id = $item->itemId;

				$goods->availability = $item->availableOnline == "true";
				$goods->link_category_id = $link_category_id;
				$goods->image = ($item->largeImage) ? $item->largeImage : '';
				$tmp_p = "";
				$result = $item->xpath('./imageEntities/imageEntities');
				foreach ($result as $imageEntity) {
					$tmp_p .= ($tmp_p ? "," : "") . (string)$imageEntity->largeImage;
				}
				$goods->photos = $tmp_p;
				$goods->detail_url = $item->productUrl;
				$goods->title = $item->name;
				$goods->subtitle = "#notuse#";
				$goods->category_id = $item->categoryNode;
				$goods->category_name = $item->categoryPath;
				$goods->keywords = "#needload#";
				if (strlen(trim($goods->description)) == 0) {

					$goods->description = $item->longDescription;
					$goods->description = html_entity_decode($goods->description);
					$goods->description = self::remove_tags($goods->description);
				}
				$goods->additional_meta['condition'] = "#notuse#";
				$goods->price = round($this->get_normalize_price($item->salePrice),2);
				$goods->additional_meta['ship'] = $this->get_normalize_price($item->standardShipRate);
				$goods->curr = "USD";

			} else {
				//$keywords = $this->curl_get_keywords($goods->detail_url);
				$goods->keywords = str_replace(', Wal-mart, Walmart.com', '', $keywords);
			}
			$result = array("state" => "ok", "message" => "", "goods" => $goods);
			return $result;
		}

		public function check_availability(/* @var $goods WPEAE_Goods */ $goods) {
			$lsPublisherId = $this->account->lsPublisherId;
			$responseEncoding = 'XML';

			$api_url = "http://api.walmartlabs.com/v1/items?"
					. "apiKey=" . $this->account->apiKey
					. ($lsPublisherId ? "&lsPublisherId=" . $lsPublisherId : "")
					. "&format=$responseEncoding"
					. "&ids={$goods->external_id}";

			$tmp_response = wpeae_remote_get($api_url);
			if (is_wp_error($tmp_response)) {
				// if walmart is not response? just return true (product availabile)
				return array('state' => 'error', 'message' => 'Walmart api not response!');
			}
			$body = wp_remote_retrieve_body($tmp_response);
			$resp = simplexml_load_string($body);

			if ($resp->items->item->availableOnline == "true")
				return true;
			return false;
		}

		public static function get_product_by_id($product_id='',$aCountry='',$acategory='',$page='',$count_product='',$site='')
		{

			$tmp_res = array('state' => '', 'message' => '');
			$result = array('state' => '', 'message' => '');
			// Format of the response
			$currency_conversion_factor = floatval(1);
			$lsPublisherId = '';
			global $wpdb;

			$lsPublisherId  = get_option('affhub_walmart_publisherid',false);
			$apiKey         = get_option('affhub_walmart_apikey','52jcdw5db9qkzs9abjgyhf7f');
			
			$responseEncoding = 'json';

			$api_url = "http://api.walmartlabs.com/v1/items?"
					. "apiKey=" . $apiKey
					. ($lsPublisherId ? "&lsPublisherId=" . $lsPublisherId : "")
					. "&format=$responseEncoding"
					. "&ids={$product_id}";

			//$tmp_response = wp_remote_get($api_url);
			$tmp_response = file_get_contents($api_url);
			if(empty($tmp_response)){
				if (!function_exists('curl_init')){ 
					die('CURL is not installed!');
				}
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $api_url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$tmp_response = curl_exec($ch);
				curl_close($ch);
			}		
			$resp = json_decode($tmp_response);		
            //echo"<pre>";print_r($resp);echo"</pre>";

				if (isset($resp->items['0']) && $resp->items['0']!='') {
					



					$item = $resp->items['0'];
					//return $item;
					$goods = (object)array();
				//	return $item;
					$goods->type = "walmart";
					$goods->external_id = $item->itemId;
				//	return $goods;

					$goods->availability = $item->availableOnline == "true";
					//$goods->link_category_id = $link_category_id;
					$goods->image = ($item->largeImage) ? $item->largeImage : '';
					$tmp_p = "";
					//$result = $item->xpath('./imageEntities/imageEntities');
					//return $result;
					//foreach ($result as $imageEntity) {
				//		$tmp_p .= ($tmp_p ? "," : "") . (string)$imageEntity->largeImage;
				//	}
				//	$goods->photos = $tmp_p;
					$goods->orig_url = $item->productUrl;
					$goods->title = $item->name;
					$goods->subtitle = "#notuse#";
					$goods->category_id = $item->categoryNode;
					$goods->category_name = $item->categoryPath;
					$goods->keywords = "#needload#";
					// if (strlen(trim($goods->description)) == 0) {

					 	$goods->description = $item->longDescription;
					 	$goods->description = html_entity_decode($goods->description);
					 	$goods->description = self::remove_tags($goods->description);
					// }
					$goods->additional_meta['condition'] = "#notuse#";
					$goods->tmp_price = round(self::get_normalize_price($item->salePrice),2);	
					if(!empty($item->msrp) && $item->msrp>$item->salePrice){	
					$goods->original_price = round(self::get_normalize_price($item->msrp),2);
					}else{
					$goods->original_price = round(self::get_normalize_price($item->salePrice),2);	
					}
					
					

					
					//$goods->original_price = round($this->get_normalize_price($item->regularPrice),2);
				
					$goods->additional_meta['ship'] = self::get_normalize_price($item->standardShipRate);
					$goods->currency = getCurrencySymbol('USD');	
					$goods->rating = $item->customerRating;
					$goods->numReviews = $item->numReviews;
					$goods->addToCartUrl= $item->addToCartUrl;
					return (array) $goods;					
				} else {
					return false;
					$goods = array("state" => "error", "message" => "" . $resp->Errors->LongMessage, "goods" => '');
				}
		}

		function curl_get_keywords($url) {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			$html = curl_exec($ch);
			curl_close($ch);

			$doc = new DOMDocument();
			@$doc->loadHTML($html);
			$metas = $doc->getElementsByTagName('meta');
			for ($i = 0; $i < $metas->length; $i++) {

				$meta = $metas->item($i);
				if ($meta->getAttribute('name') == 'keywords')
					$keywords = $meta->getAttribute('content');
			}
			return $keywords;
		}
        public static function get_normalize_price($price) {
            return (isset($price) && $price) ? sprintf("%01.2f", str_replace(array('US $', 'RUB', '$', 'GPB', 'BRL', 'CAD', 'AUD', 'EUR', 'INR', 'UAH', 'JPY', 'MXN', 'IDR', 'TRY', 'SEK', '.00'), '', $price)) : "0.00";
        }	
        public static function remove_tags($html, $tags = array()) {
            if(function_exists('mb_convert_encoding')){
                $html = trim(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
            }else{
                $html = htmlspecialchars_decode(utf8_decode(htmlentities($html, ENT_COMPAT, 'UTF-8', false)));    
            }
            
            $dom = new DOMDocument();
            libxml_use_internal_errors(true);
            @$dom->loadHTML($html);
            libxml_use_internal_errors(false);
            $dom->formatOutput = true;

            if (!$tags) {
                $tags = array('script', 'head', 'meta', 'style', 'map', 'noscript', 'object');

                $tags[] = 'img';
                $tags[] = 'a';
            }
            foreach ($tags as $tag) {
                $elements = $dom->getElementsByTagName($tag);
                for ($i = $elements->length; --$i >= 0;) {
                    $e = $elements->item($i);
                    if ($tag == 'a') {
                        while ($e->hasChildNodes()) {
                            $child = $e->removeChild($e->firstChild);
                            $e->parentNode->insertBefore($child, $e);
                        }
                        $e->parentNode->removeChild($e);
                    } else {
                        $e->parentNode->removeChild($e);
                    }
                }
            }
            
            return preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
        }
        function get_logo_url($logo_name = '') {

        	return WPMTY_PLUGIN_URL.'/components/resources/public/images/'.$logo_name.'.png';
        	
		}	
		public static function get_Walmart_categories() {
		
				$result = json_decode(file_get_contents(PLUGIN_PATH.'/api/data/wal_categories.json'), true);
				$result = $result["categories"];
				array_unshift($result, array("id" => "", "name" => "-- Select category --", "level" => 1));
				return $result;
			//}
	
		}	
	}