<?php

class ApiController extends BaseController
{

	public function getAllApprovedStatuses($num = 8)
	{
		$statuses = DB::table('statuses')
			->select('id', 'files')
			->whereIn('state',array(1,2))
			->take($num)
			->orderBy('order','asc')
			->get();

		$xml = new SimpleXMLElement('<statuses/>');

		foreach ($statuses as $id => $status) {
			// $xml->addAttribute('status', 'documentary');
			$files = json_decode($status->files);

			$item = $xml->addChild('status');
			$item->addChild('regular', $files[0]);
			$item->addChild('wide', $files[1]);
		}

		return $xml->asXML();
		exit();
	}

	public function getNApprovedStatus($n, $size)
	{

		/*$status = DB::table('statuses')
			->select('files')
			->where('order', $n)
			->whereIn('state',array(1,2))
			->first();

		$files = '';
		if( $status && isset($status->files) )
		{
			$files = json_decode($status->files);
			$size = array_search($size, ['4x3', '16x9']);
			$file = $files[$size];
		}
		else
		{*/
			// $file = url('/images/-' . .'.png');
			$file =  url('/api/status/' . $n . '/' . $size . '/image.png');
		// }

		$response = "<?xml version=\"1.0\"?>\n<image url=\"".$file."\"></image>";

		return Response::make($response, '200')->header('Content-Type', 'text/xml');
	}

	public function getNApprovedStatusImage($n, $size)
	{
		$status = DB::table('statuses')
			->select('files')
			->where('order', $n)
			->whereIn('state',array(1,2))
			->first();

		$imageUrl = '';
		if( $status && isset($status->files) )
		{
			$files = json_decode($status->files);
			$size = array_search($size, ['4x3', '16x9']);
			$imageUrl = $files[$size];
		}
		else
		{
			$imageUrl = public_path('images/' . $n . '-' .$size .'.png');
		}

		$file = file_get_contents($imageUrl);

		return Response::make($file, 200)
							->header('Content-Type', 'image/png');
	}



	public function getInitialStatuses($num=4)
	{
		$statuses = DB::table('statuses')
			->select('id', 'username', 'profile_img', 'social_network', 'text', 'media', 'likes')
			->whereIn('state',array(1,2))
			->take($num)
			->orderBy('order','asc')
			->get();

		return Response::json($statuses);
	}



	public function getNextStatus($id)
	{

		/*
		 * Get newly published status
		 */
		$new = DB::table('statuses')
			->where('state', '=', 2)
			->take(1)
			->get();

		if( !empty($new) )
		{
			$new = array_shift($new);

			/*
			 * If current status is newly published degrade it
			 */
			DB::table('statuses')
				->where('id', '=', $new->id)
				->where('state', '=', 2)
				->update(['state' => 1]);

			return Response::json($new);
		}

		/*
		$next = DB::select( DB::raw("
		SELECT
			s.id, s.username, s.profile_img, s.social_network, s.text, s.media, s.likes
		FROM
			statuses s
		WHERE
			s.id IN (
				SELECT a.next_id
				FROM statuses a
				WHERE a.id=:id
		)", array('id'=>$id)) );
		*/

		$nextId = DB::table('statuses')
			->select('next_id')
			->whereIn('state', array(1,2))
			->where('id', '=', $id)
			->take(1)
			->get();
		if( empty($nextId) )
		{
			return Response::json(array('error'=>'something went wrong'));
		}

		$next = DB::table('statuses')
			->where('id', '=', $nextId[0]->next_id)
			->take(1)
			->get();

		$next = array_shift($next);
		return Response::json($next);
	}



	public function index($type='tweets')
	{
		$json = Request::header('Content-Type') == 'application/json';
		$requireMedia = $type == 'photos' ? true : false;

		$dbData = DB::table('statuses')
			->select('id', 'username', 'profile_img', 'social_network', 'text', 'media', 'likes')
			->where('state','=',2)
			->where('media',($requireMedia ? '!=' : '='),($requireMedia ? '' : null))
			->take(12)
			->orderBy('order','asc')
			->get();
		$statuses = '';

		if( !$json ) {
			for ($i=0; count($dbData) > $i; $i++) {
				$dbData[$i]->social_network = $dbData[$i]->social_network == 1 ? 'twitter' : 'instagram';
				$statuses .= $this->_twitterify(View::make('templates.'.($requireMedia ? 'vipPhoto' :'vipNoPhoto'))->with('status',$dbData[$i])->render());
			}
			return Response::json($statuses);
		} else {
			for ($i=0; count($dbData) > $i; $i++) {
				$dbData[$i]->social_network = $dbData[$i]->social_network == 1 ? 'twitter' : 'instagram';
			}
			return Response::json($dbData);
		}

		return true;
	}



	public function unity()
	{
		$response = DB::table('statuses')
			->where('state','=',2)
			->where('media','=',null)
			->orderBy('order','asc')
			->get(['username','profile_img']);

		return Response::json($response);
	}



	public function getToplist()
	{
		$items = file_get_contents('http://hpapps.net/dnss/public/getToplistVip');
		$items = json_decode($items);

		$topListViewData = '';

		$i = 1;
		foreach($items as $item)
		{
			if($i <= 10)
			{
				$item->i = $i;

				if($i == 1)
				{
					$topListViewData .= '<div class="tl-left">';
				}

				if($i == 6)
				{
					$topListViewData .= '</div>';
					$topListViewData .= '<div class="tl-right">';
				}


				$topListViewData .= View::make('templates.toplist')->with('data',(array)$item)->render();

				if($i == 10)
				{
					$topListViewData .= '</div>';
				}

			}
			$i++;
		}

		return Response::json($topListViewData);
	}



	private function _twitterify($ret)
	{
		$ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2", $ret);
		$ret = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $ret);
		$ret = preg_replace("/#([a-zA-Z]\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $ret);

		return $ret;
	}
}
