<?php

class AdminController extends BaseController
{



	public function index()
	{
		if(!Session::has('is_logged_in'))
		{
			return Redirect::to('login');
		}
		else
		{
			return Redirect::route('statusesManager');
		}
	}

	public function getStatusesIndex()
	{
		return View::make('admin.statuses');
	}



	/**
	 * Parse search string to twitter query string.
	 *
	 * @param $searchTerm
	 * @return string
	 */
	private function _parseSearchTerm($searchTerm) {
		$searchTerm = str_replace(' ','',$searchTerm);

		if(strpos($searchTerm,',') == true){
			$searchTerm = str_replace(',','+AND+',$searchTerm);
		}

		return $searchTerm;
	}



	/**
	 * Creates new column.
	 *
	 * @return void
	 */
	public function addColumn()
	{
		$socialNetwork	= Input::get('social_network');
		$hashtag		= $this->_parseSearchTerm(Input::get('hashtag'));
		if( !$socialNetwork || !$hashtag )
		{
			return Response::json(['error' => 'Undefined parameters.']);
		}

		// Check if column with this hashtag allerady exists, and if so, abort adding new.
		$cm = new ColumnsModel();
		$exists = $cm->where('hashtag', '=', $hashtag)
			->where('social_network', '=', $socialNetwork)
			->where('state', '=', 1)
			->count();

		if( $exists < 1 )
		{
			$cm->hashtag = $hashtag;
			$cm->social_network = $socialNetwork;
			$cm->save();

			return Response::json([
				'success'		=> true,
				'id'			=> $cm->id,
				'hashtag'		=> $hashtag,
				'social_network'=> $socialNetwork == 1 ? 'twitter' : 'instagram'
			]);
		}

		return Response::json(['error' => 'Column allready exists.']);
	}



	public function postTabSettings($id)
	{
		$inputs = Input::all();

		$column = ColumnsModel::where('id', $id)->first();

		$settings = !$column->settings ? [] : (array) json_decode($column->settings);
		$settings = array_merge($settings, $inputs);

		$column->settings = json_encode($settings);
		$column->save();

		return Response::json([
			'tab' => $column->toArray()
		]);
	}



	/**
	 * Disable column
	 *
	 * @return void
	 */
	public function postTabState($id)
	{
		$state = Input::get('state');
		// dd($state);

		$columnToRemove = ColumnsModel::find($id);
		$columnToRemove->state = $state;
		$columnToRemove->save();

		return Response::json(['success'=>'Hash Tag Deleted']);
	}



	/**
	 * Return all columns from the database.
	 *
	 * @return array
	 */
	public function getColumns()
	{
		$cm = new ColumnsModel();
		$id = Input::get('id');
		$lastCreated = Input::get('lastCreated');

		if(!$id) {
			$columns = $cm::where('state','=',1)->get();
		} else {
			$columns = array($cm::find($id));
		}

		if($lastCreated == 1) {
			$id = DB::table('columns')->max('id');
			$columns = array($cm::find($id));
		}

		if(!empty($columns)) {

			$parsedColumns = [];
			foreach($columns as $column) {
				$column->social_network = $column->social_network == 1 ? 'twitter' : 'instagram';
				$column->hashtag = str_replace('+AND+',',',$column->hashtag);
				$parsedColumns[] = $column;
			}

			return Response::json(['tabs'=>$columns]);
		} else {
			return Response::json(['error' => 'No columns has been found.']);
		}
	}



	/**
	 * Get new tweets and instagram by columns and save them to the database.
	 * Returns only new statuses for the admin.
	 *
	 * @param $columnId
	 * @return array
	 *
	 */
	public function collectStatusesByColumns($columnId = null) {
		if($columnId) {
			$columns = array(ColumnsModel::find($columnId));
		} else {
			$columns = ColumnsModel::where('state','=',1)->get();
		}

		// Updating is_new status to 0, so only new statuses have value 1
		DB::table('statuses')
			->where('state', '=', 0)
			->update(array('state' => 1));

		foreach($columns as $column) {
			if($column->social_network == 1) {
				$this->getTweets($column->hashtag,$column->id);
			} else {
				$this->getInstagrams($column->hashtag,$column->id);
			}
		}

		if(Input::get('autopilot') == 1) {
			$this->approveAllStatuses();
		}

		$this->respondSuccess("Saved");
	}



	/**
	 * Get all statuses from the db by column.
	 *
	 * The params are sent by a POST method.
	 *
	 * @return array
	 */
	public function getStatuses()
	{

		$response = [];
		$idColumn = Input::get('idColumn');
		$onlyNew  = Input::get('onlyNew');

		$columns = ColumnsModel::where('state','=',1)->get();

		for($i=0; $i < count($columns); $i++) {
			$statuses = array();
			$count = 0;

			if($onlyNew == 1) {
				$statuses = StatusesModel::where('id_column', '=', $columns[$i]->id)
					->where('state', '=', 0)
					->orderBy('id', 'desc')
					->get()
					->toArray();

				$count = StatusesModel::where('id_column', '=', $columns[$i]->id)
					->where('state', '=', 0)
					->count();
			} else {
				if($idColumn) {
					$statuses = StatusesModel::where('id_column', '=', $columns[$i]->id)
						->where('id_column', '!=', $idColumn)
						->orderBy('id', 'desc')
						->paginate(100)
						->toArray();
						/*->take(100)
						->take()
						->toArray();*/

					$count = StatusesModel::where('id_column', '=', $columns[$i]->id)
						->where('id_column', '!=', $idColumn)
						->count();
				} else {
					$statuses = StatusesModel::where('id_column', '=', $columns[$i]->id)
						->whereNotIn('state', array(-1,1,2))
						->orderBy('id', 'desc')
						->paginate(100)
						->toArray();
						/*->take(100)
						->get()
						->toArray();*/

					$count = StatusesModel::where('id_column', '=', $columns[$i]->id)
						->whereNotIn('state', array(-1,1,2))
						->count();
				}
			}

			$response[$i] = array(
				'tab'			=> $columns[$i],
				'statusCount'	=> $count,
				'statuses'		=> $statuses
			);
		}

		return Response::json($response);
	}


	/**
	 * Get new status.
	 *
	 *states:
	 * -1 = blocked,
	 *  0 = unpublished,
	 *  1 = published,
	 *  2 = newly published,
	 *  3 = outdated,
	 *
	 * @method POST.
	 *
	 * @return object
	 */
	public function getNextStatus()
	{
		$current = Input::get('statusId');
		if( empty($current) ) {
			return Response::json(['error'=>'Status not defined']);
		}

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

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

		if( !empty($new) ) {
			return Response::json($new);
		}


		$next = DB::select( DB::raw("SELECT * FROM statuses WHERE id = ( SELECT next_id FROM statuses WHERE id=:id )", array('id'=>$current)) );
		return Response::json($next);
	}


	/**
	 * Get statuses for playlist.
	 *
	 * states:
	 * -1 = blocked
	 *  0 = unpublished,
	 *  1 = published,
	 *  2 = newly published,
	 *  3 = outdated,
	 *
	 * @method GET.
	 *
	 * @return array
	 */
	public function getApprovedStatuses($num = 20)
	{
		$statuses = DB::table('statuses')
			->whereIn('state', array(1,2))
			->take($num)
			->orderBy('order', 'ASC')
			->get();

		/*usort($statuses, function($a, $b){
			return $a['order'] - $b['order'];
		});*/


		if(!empty($statuses)) {
			return Response::json(['statuses' => $statuses]);
		} else {
			return Response::json(['error' => 'There is not any approved status yet.']);
		}
	}



	/**
	 * Changes statuses state.
	 *
	 *states:
	 * -1 = blocked
	 *  0 = unpublished,
	 *  1 = published,
	 *  2 = newly published,
	 *  3 = outdated,
	 *
	 * @method POST.
	 *
	 * @return void
	 */
	public function approveStatus()
	{
		if( !Input::has('statusId') || !Input::has('photos') ) {
			return Response::json(['error'=>'Required parameters are empty']);
		}

		$statusId	= Input::get('statusId');
		$photos		= Input::get('photos');
		$files		= [];
		$response	 = [
			'status'	=> 'error',
			'files'		=> []
		];

		$sm = new StatusesModel;
		$status = $sm->find($statusId);

		foreach ($photos as $i => $photo)
		{
			$base64String = substr($photo, strpos($photo, ",")+1);

			$image = base64_decode($base64String);
			$extension = $this->getBase64FileExtension($photo);

			$imageName = "status-". $i . '-' . time() . "." . $extension;
			$path = public_path() . '/approvedSatuses/' . $imageName;
			$file = File::put($path, $image);

			if( !$file )
			{
				$response['status'] = 'error';
				break;
			}
			else
			{
				$response['status'] = 'success';
			}

			$response['files'][] = url('/') . '/approvedSatuses/' . $imageName;
		}

		if( $response['status'] === 'success' )
		{
			$status->state = 2;
			$status->files = json_encode($response['files']);
			$status->published_at = date('Y-m-d H:i:s');
			$status->save();
		}

		return Response::json($response);
	}


	/**
	 * Clone statuses.
	 *
	 * @method POST.
	 *
	 * @return void
	 */
	public function cloneStatus($id)
	{
		$alfa = StatusesModel::where('id', $id)->get();
		if (!$alfa->count())
		{
			return Response::json(['error' => 'Wrong parameters'], 304);
		}

		$clone = $alfa->first()->replicate();
		$clone->save();

		return Response::json([
			'status'	=> 'success',
			'data'		=> $clone
		]);
	}


	/**
	 * Changes statuses state.
	 *
	 *states:
	 * -1 = blocked
	 *  0 = unpublished,
	 *  1 = published,
	 *  2 = newly published,
	 *  3 = outdated,
	 *
	 * @method POST.
	 *
	 * @return void
	 */
	public function setState($statusId=null)
	{
		// $statusId = Input::get('statusId');
		$state	= Input::get('state');
		$removeFromList = Input::get('remove', false);

		if( !$statusId || empty($state) ) {
			return Response::json(['error'=>'Required parameters are empty']);
		}

		$attrs = ['state'=>$state];
		if ($removeFromList)
		{
			$attrs['order'] = null;
			$attrs['next_id'] = null;
		}

		$sm = StatusesModel::where('id', $statusId)
			->update($attrs);

		return Response::json(['success'=>'Status state has been updated', 'status'=>$sm]);
	}



	/**
	 * Sort statuses
	 *
	 * @return void
	 */
	public function sortStatuses ()
	{
		$statusIDs = Input::get('statuses', []);
		$max = Input::get('max', 20);

		if( empty($statusIDs) )
		{
			return Response::json(['error'=>'Wrong parameters']);
		}

		$sortArr = array_slice($statusIDs, 0, $max);
		$removeArr = array_slice($statusIDs, $max);

		if( !empty($removeArr) )
		{
			$removed = DB::table('statuses')
				->whereIn('id', $removeArr)
				->update([
					'state'		=> '3',
					'order'		=> '',
					'next_id'	=> ''
				]);
		}

		$statuses = StatusesModel::whereIn('id', $sortArr)->take($max)->get();
		$updated = [];
		$statusesSum = $statuses->count();

		foreach ($statuses as $key => $status) {
			$values = [];

			$order = array_search($status->id, $statusIDs);

			if( $order !== false )
			{
				$status->update([
					'order'		=> $order,
					'next_id'	=> $order < $statusesSum-1 ? $statusIDs[$order+1] : $statusIDs[0]
				]);
			}
		}

		$newList = $statuses->toArray();
		usort($newList, function($a, $b){
			return $a['order'] - $b['order'];
		});

		return Response::json([
			'statuses'=>$newList,
			'length'=>$max
		]);
	}



	/**
	 * Approve statuses all for specific column
	 *
	 * @return void
	 */
	public function approveStatusesByColumn ()
	{
		$columnId = Input::get('columnId');
		DB::table('statuses')->where('id_column', $columnId)->update(array('state' => 2));
		$this->respondSuccess('Approved.');
	}



	/**
	 * Approves all statuse
	 *
	 * @return void
	 */
	public function approveAllStatuses()
	{
		DB::table('statuses')->where('state','=',0)->orWhere('state','=',1)->update(array('state' => 2));
	}


	/**
	 * Conver external image to base64 string
	 *
	 * @return JSON
	 */
	public function imageToBase64(){

		$url = Input::get('url');
		$url = urldecode($url);

		$type = $this->getFileExtension($url);
		$type = gettype($type) == 'array' ? array_pop($type) : $type;

		$base64 = base64_encode( file_get_contents($url) );

		return Response::json([
			'image'	=> 'data:image/' . $type . ';base64,' . $base64,
		]);
	}

	/**
	 * Login layout
	 *
	 * @return void
	 */
	public function getLogin()
	{
		Session::flush();
		return View::make('admin.login');
	}



	public function loginValidate ()
	{
		/*$pass = 'kumruzvelt';
		$inputPass = Input::get('pass');

		if($pass == $inputPass) {
			Session::put('is_logged_in', 1);
			$this->respondSuccess('You are logged in.');
		}*/
		$email		= Input::get('email');
		$password	= Input::get('pass');
		// dd($email, $password);

		if (Auth::attempt(array('email' => $email, 'password' => $password)))
		{
			return Redirect::route('statusesManager');
		}

		return View::make('admin.login');
	}


	public function getFileExtension($file)
	{
		$type = [];
		preg_match('/.(?:jpe?g|png|gif)/', $file, $type);
		if( !empty($type) )
		{
			$type = str_replace('.', '', array_pop($type));
		}

		return $type;
	}


	public function getBase64FileExtension($base64String)
	{
		$type = [];
		preg_match('/data:image\/([^;]*);base64/is', $base64String, $type);

		if( !empty($type) )
		{
			$type = str_replace('.', '', array_pop($type));
		}

		return $type;
	}
}
