<?php
/*
	DevSaver Web Framework
	Copyright (c) 2002-2018 DevSaver. 
	All rights reserved.
		web:  www.devsaver.com
		mail: support@devsaver.com
*/

if (!defined("STPBase")) {
	die("This file can't be accessed directly!");
}

class CSocialMediaWidgetInstagram extends CWidget {

	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $meta = array(
		"type"	=> "4",
		"name"	=> "Instagram Feed",
	);

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Render($widget) {

		global $base;


		$data = $this->updateFeed($widget);

		if (!is_array($data)) {
			return "";
		}
		
		$cnt = 1;
		foreach ($data as $key => $val) {
			$media[] = $val;			

			$cnt++;

			if ($cnt > $widget["settings"]["set_items"]) {
				break;
			}
		}

		global $base;

		return $this->tpl->blockReplace(
			"Main" , 
			array(
				"images"	=> $base->html->Table(
					$this->tpl , 
					"",
					$media
				),

				"class"	=> $this->tpl->blockreplace($widget["settings"]["set_carousel"] ? "Carousel" :"List"),

			),
			$widget["settings"],
			$widget
		);
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function updateFeed($widget) {

		$cache = $this->db->QFetchArray(
			"SELECT * FROM {$this->tables['core:cache']} WHERE cache_name = '%s'",
			array("widget-" . $widget["widget_id"])
		);

		if (!is_array($cache) || ($cache["cache_expire"] < time())) {

			$data = $tmp = CHTTP::newInstance()
				->Get("https://api.instagram.com/v1/users/self/media/recent?access_token=" . $widget["settings"]["set_token"])
				->Raw();

			$cache["cache_data"] = $data;
			$cache["cache_date"] = time();
			$cache["cache_expire"] = time() + 3600 * 4;
			$cache["cache_name"] = "widget-" . $widget["widget_id"];


			if ($cache["cache_id"]) {
				$this->db->QueryUpdate(
					$this->tables["core:cache"],
					$cache,
					"cache_id={$cache[cache_id]}"
				);
			} else {
				$this->db->QueryInsert(
					$this->tables["core:cache"],
					$cache
				);
			}			
		}

		if ($cache["cache_data"]) {
			$feed = json_decode($cache["cache_data"] , true);
		}

		if (is_array($feed["data"])) {

			if (!is_array($feed["data"]["0"])) {
				$feed["data"] = array( 0 => $feed["data"]);
			}

			foreach ($feed["data"] as $key => $val) {
				$images[] = array(
					"tn"		=> $val["images"]["thumbnail"]["url"],
					"image"		=> $val["images"]["standard_resolution"]["url"],
					"title"		=> $val["caption"]["text"],
					"date"		=> $val["caption"]["created_time"],
					"likes"		=> $val["likes"]["count"],
					"comments"	=> $val["comments"]["count"],
					"url"		=> $val["link"],
				);
			}
		}

		return $images;		
		
		/*
		$file = "./upload/tmp/widget-" . $widget["widget_id"] . ".json";
		$expire = time() - 10 * 60;

		if (file_exists($file) && (filectime($file) > $expire) ) {
		} else {
			//reload the feed
			$feed = CHttp::newInstance()
				->get("https://www.instagram.com/{$widget[settings][set_user]}/")
				->raw();

			//process the file
			$tmp = explode("\n" , $feed);

			if (is_array($tmp)) {
				foreach ($tmp as $key => $val) {
					if (stristr($val , "window._sharedData = ")) {
						$json = rtrim(
							str_replace(
								"window._sharedData = " , 
								"",
								trim(
									strip_tags($val)
								)
							),
							";"
						);
					}
					
				}
				
			}

			//save in tmp
			CFile::Save($file , $json );			
		}

		return 	json_decode(CFile::Get($file) , true);
		*/
	}
	
}
