<?php
// require_once("/var/www/php70/navnath/msacommon/lib/php/include/dbPDO.php");
require_once("lib/php/include/dbPDO.php");

class eurekster {
	function __construct() {
		$this->db_whale = CommonPDOConnector::connect('ConnectToWhale');
		$this->db_admin = CommonPDOConnector::connect('ConnectToAdmin');
        $this->organicSearchApiKey = "df2de800-cc3e-11f0-b9ec-8b29b34f37e2";
	}

	public function getResults($search) {
		$freeOrganicListings = false;
		$sql = "select id,result from eurekster_organic_listings where keyword = ? and valid=? and serp_type=? limit 1";
		$stmt = $this->db_whale->prepare($sql);
		$stmt->execute(array($search,1,'Search'));
		$row = $stmt->fetch(PDO::FETCH_ASSOC);

		if ($row && !empty($row['result'])) {
			$freeOrganicListings = stripslashes($row['result']);
			$freeOrganicListings = json_decode($freeOrganicListings,true);

		}
		if(empty($freeOrganicListings))
		{
			$freeOrganicListingUrl = "https://app.zenserp.com/api/v2/search?apikey=".$this->organicSearchApiKey."&q=".urlencode($search)."&device=desktop&location=Manhattan,New%20York,United%20States&num=100";
			$CurlData = array(	"url" => $freeOrganicListingUrl,"timeout" => '10');
			$freeOrganicListings = $this->curl_get_contents($CurlData);
			$result = json_decode($freeOrganicListings,true);
			if(isset($result['error']) || empty($result)){
				$sql = "SELECT id,result,valid,serp_type FROM eurekster_organic_listings WHERE MATCH(keyword) AGAINST (? IN NATURAL LANGUAGE MODE) and valid=? and serp_type=? limit 1";
				$stmt = $this->db_whale->prepare($sql);
				$stmt->execute(array($search,1,'Search'));
				$row = $stmt->fetch(PDO::FETCH_ASSOC);
				if($row && !empty( $row['result'] ) ) {
					$freeOrganicListings = stripslashes($row['result']);;
				} else {
					$freeOrganicListings = json_encode(array());
				}
			} else {
				try{
					$freeOrganicListings = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $freeOrganicListings);
					$escapedData = addslashes($freeOrganicListings);
					$sql = "INSERT into eurekster_organic_listings(keyword,result,serp_type) VALUES (?,?,?)";
					$stmt = $this->db_whale->prepare($sql);
					$stmt->execute(array($search,$escapedData,'Search'));
				}catch(\Exception $e){
					//pass
				}
			}
			$freeOrganicListings = json_decode($freeOrganicListings,true);
		}

		if( !isset( $freeOrganicListings['organic'] ) ) {
			return [];
		}

        $freeOrganicListings = $freeOrganicListings['organic'];

		$storsInfo = [];
		foreach ($freeOrganicListings as $key => $result) {
			if(isset($result['localPack']) && !empty($result['localPack'])){
				$storsInfo = $result['localPack'];
			}
		}

		foreach ($storsInfo as $key => $store) {
			$storsInfo[$key]['stars'] = $this->getStartImage( $store['stars'] );
		}

		return [ 'freeOrganicListings' => $freeOrganicListings, 'storsInfo' => $storsInfo  ];
	}

    public function curl_get_contents($data)
	{
		$ch = curl_init($data['url']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

		$result = curl_exec($ch);

		if (curl_error($ch))
			return curl_error($ch);
		$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);

		return $result;
	}

	function getLatestNews($keyword=false,$limit = false) {
		$query['keyword'] = ($keyword) ? $keyword : "";
		$query['limit'] = ($limit) ? $limit : 10;
		
		$url = "https://montanapost.com/recentNews?".http_build_query($query);
		$ch = curl_init( $url );
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
		$output = curl_exec( $ch );
		curl_close( $ch );
		$result = json_decode( $output, true );
		return $result;
	}

	function getStartImage($star) {
		if( empty( $star ) ) {
			return false;
		} else {
			$floorVal = floor($star);
			return (floatval($star) > floatval($floorVal.".5")) ? $floorVal.".5" : $floorVal;
		}
	}

	function getSponseredAds($search,$subid,$affiliate=false) {
		$SponsorFeed = new DomDocument();
		$xmlData = '';
		$xml_server = 'xml.admedia.com';
		$affiliate = empty($affiliate) ? "eurekster" : $affiliate;
		$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
		$ua=urlencode($_SERVER['HTTP_USER_AGENT']);

		$SponsorFeedUrl = "https://".$xml_server."/xml.php?affiliate=$affiliate&subid=$subid&mrpp=15&type=29&Terms=".urlencode($search)."&IP=".$ipaddress."&useragent=".$ua;
		$CurlData = array("url" => $SponsorFeedUrl,"timeout" => '10');
		$xmlData = $this->curl_get_contents($CurlData);
		$organicSearchApiKey = "54987540-8e3e-11ea-8998-3563d733c344";
		$SponsorFeed->loadXML($xmlData);
		$Listing = $SponsorFeed->getElementsByTagName("listing");
		return $Listing;
	}
	
	function getWeatherInfo() {
		include_once('lib/php/api/accuWeather.php');
		$weatherData = new Accuweather();
		$weatherData = $weatherData->apiData;
		return $weatherData;
	}

	function getKnowledgePanel($search) {
		$endPoint = "https://en.wikipedia.org/w/api.php";
		$params = [
			"action" => "query",
			"list" => "search",
			"srsearch" => $search,
			"format" => "json",
			"srlimit"=>1
		];
	
		$url = $endPoint . "?" . http_build_query( $params );
	
		$ch = curl_init( $url );
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
		$output = curl_exec( $ch );
		curl_close( $ch );
		$result = json_decode( $output, true );
                if(!empty($result['query']['search'])){
                    $title = $result['query']['search'][0]['title'];
                    $title = str_replace(" ","_",$title);
                    $url = "https://en.wikipedia.org/api/rest_v1/page/summary/".$title;
                    $ch = curl_init( $url );
                    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
                    $output = curl_exec( $ch );
                    curl_close( $ch );
                    $result = json_decode( $output, true );
                    return $result;
                }else{
                    $title = "";
                    return array();
                }
	}

	function getRelatedSearch($search) {
		$id = $sid = '';
		$landingUrl = base_url('Search')."?&search=";
		$relatedArr = array();
		$qsearch = str_replace(" ", "+", strtolower($search));
		$cSql = "select related from rep_2click_keywords where keyword = ?";
		
		$stmt = $this->db_admin->prepare($cSql);
			$stmt->execute(array($qsearch));
			$cRow = $stmt->fetch(PDO::FETCH_ASSOC);

		if($cRow && $cRow['related'] != '') {
			$related_ex = explode(",", $cRow['related']);
			foreach($related_ex as $rex) {
				$relatedArr[] = $rex;
			}
		}

		$relatedCt = 0;
		if(is_array($relatedArr) && count($relatedArr) > 0) {
			$relatedCt = 1;
		}
		
		return [ 'relatedArr' => $relatedArr, 'relatedCt' => $relatedCt, 'landingUrl' => $landingUrl ];
	}
}