<?php

namespace App\Modules\Mattermost\Controllers\Api\V1;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Modules\Clients\Site;
use App\Modules\Bookings\Task;
use App\Modules\Clients\Client;
use App\Modules\Clients\Customer;
use App\Modules\Mattermost\MattermostHelper;
use App\Http\Controllers\BaseController;
use App\Models\Status;

class MattermostControllerREST  extends BaseController
{

	public function __construct()
	{
		//Load helper functions
		$this->MattermostHelper = new MattermostHelper();
	}

	public function getSupport(Request $request){

		//  default settings in helper
		/*
		'clientId'      => 53, // computer assistance
    'clientName'    => 'Computer', // computer assistance
    'responseType' => 'ephemeral', // mattermost response type - only to yourself
    'username' 			=> 'Seraph', // mattermost something
    'userId'        => 1, // administrator
		'success'       => false,
    'searchType'    => 'open'
		'adminUserName' => 'admin', // administrator
		*/

		$defaults = $this->MattermostHelper->getAllDefaultSettings();

		$success = $defaults['success'];
		$responseType = $defaults['responseType'];
		$searchType = $defaults['searchType'];

		if(!$request->input('text')){
				// same as default (open)
			$responseData = Task::open()->support()->with('user')->where('assigned_to', null)->sortid()->take(30)->get();
			$success = true;
			$user = false;
		}
		else if($request->input('text')) {
			//There is extra text to process. Check if it contains 'open', 'my'
			$responseType = $this->MattermostHelper->setResponseType($request->input('text'));

			$searchType = $this->MattermostHelper->setSearchType($request->input('text'));

			$user = $request->input('text') ? $this->MattermostHelper->getUser($request->input('text')) : false;


			if ($searchType == 'my')	{

				$matterUser = User::query()->where('username','like', '%' . $request->input('user_name') . '%')->first();

				if ($matterUser) {
					Auth::login($matterUser);
					$responseData = Task::own()->support()->open()->sortid()->take(30)->get();
					if ($responseData->count() > 0) {
						$success = true;
					}
					else {
						return $this->MattermostHelper->sendEnhancedResponse("No tasks found!", false, "ephemeral");
					}
				}
				else {
					return $this->MattermostHelper->sendEnhancedResponse("User not found found!", false, "ephemeral");
				}
			}
			else if($searchType == 'open' && !$user) {
				$responseData = Task::open()->support()->with('user')->where('assigned_to', null)->sortid()->take(30)->get();
				$success = true;
			}
			else if ($user) {
				$userId = $user->id;
				$responseData = Task::open()->support()->with('user')->where('assigned_to', $userId)->sortid()->take(30)->get();
				$success = true;

			}
			else  {
				$userId = false;
				return $this->MattermostHelper->sendResponse("User \"". substr($request->input('text'), 1) ."\" not found - try again!");
			}
		}

$text = "
---
### Seraph Support Jobs

| Job ID | Title | User | Type |
|:-------|:------|:-----|:-----|
";

		foreach($responseData as $resp){

			$requestUser = $resp->user ? $resp->user->username : 'unassigned';

			$text = $text . "|" ."[". $resp->id ."](' . config('app.url') . '/tasks/". $resp->id .")" . "|" . trim(preg_replace('/\s\s+/', '', strip_tags($resp->title))) ."|" . $requestUser . "|" .$resp->type . "|" . "\n";
		}

		$text = $text . "---";
		$response = [
			'text'         => $text
		];

		$response += ['success' => $success ];
		$response += ['response_type' => $responseType ];
		$response += ['username' => 'Seraph' ];

		// Cache the results of this query for 24 hours
		// Cache::tags(['tasks'])->put($requestUri, $response, 24 * 60);

		return response()->json($response, ($response['success']) ? 200 : 400);
	}

	public function getRepair(Request $request){
		// die ("hit");

		// return json_encode('banana','banana');
		//  default settings in helper
		/*
		'clientId'      => 53, // computer assistance
    'clientName'    => 'Computer', // computer assistance
    'responseType' => 'ephemeral', // mattermost response type - only to yourself
    'username' 			=> 'Seraph', // mattermost something
    'userId'        => 1, // administrator
		'success'       => false,
    'searchType'    => 'open'
		'adminUserName' => 'admin', // administrator
		*/

		$defaults = $this->MattermostHelper->getAllDefaultSettings();

		$success = $defaults['success'];
		$responseType = $defaults['responseType'];
		$searchType = $defaults['searchType'];

		if(!$request->input('text')){
				// same as default (open)
			$responseData = Task::open()->repair()->with('user')->where('assigned_to', null)->sortid()->take(30)->get();
			$success = true;
			$user = false;
		}
		else if($request->input('text')) {
			//There is extra text to process. Check if it contains 'open', 'my'
			$responseType = $this->MattermostHelper->setResponseType($request->input('text'));

			$searchType = $this->MattermostHelper->setSearchType($request->input('text'));

			$user = $request->input('text') ? $this->MattermostHelper->getUser($request->input('text')) : false;


			if ($searchType == 'my')	{

				$matterUser = User::query()->where('username','like', '%' . $request->input('user_name') . '%')->first();

				if ($matterUser) {
					Auth::login($matterUser);
					$responseData = Task::own()->repair()->open()->sortid()->take(30)->get();
					if ($responseData->count() > 0) {
						$success = true;
					}
					else {
						return $this->MattermostHelper->sendEnhancedResponse("No tasks found!", false, "ephemeral");
					}
				}
				else {
					return $this->MattermostHelper->sendEnhancedResponse("User not found found!", false, "ephemeral");
				}
			}
			else if($searchType == 'open' && !$user) {
				$responseData = Task::open()->repair()->with('user')->where('assigned_to', null)->sortid()->take(30)->get();
				$success = true;
			}
			else if ($user) {
				$responseData = Task::open()->repair()->with('user')->where('assigned_to', $user->id)->sortid()->take(30)->get();
				$success = true;

			}
			else  {
				$userId = false;
				return $this->MattermostHelper->sendResponse("User \"". substr($request->input('text'), 1) ."\" not found - try again!");
			}
		}

$text = "
---
### Seraph Repair Jobs

| Job ID | Title | User | Type |
|:-------|:------|:-----|:-----|
";

		foreach($responseData as $resp){

			$requestUser = $resp->user ? $resp->user->username : 'unassigned';

			$text = $text . "|" ."[". $resp->id ."](' . config('app.url') . '/tasks/". $resp->id .")" . "|" . trim(preg_replace('/\s\s+/', '', strip_tags($resp->title))) ."|" . $requestUser . "|" .$resp->type . "|" . "\n";
		}

		$text = $text . "---";
		$response = [
			'text'         => $text
		];

		$response += ['success' => $success ];
		$response += ['response_type' => $responseType ];
		$response += ['username' => 'Seraph' ];

		// Cache the results of this query for 24 hours
		// Cache::tags(['tasks'])->put($requestUri, $response, 24 * 60);

		return response()->json($response, ($response['success']) ? 200 : 400);
	}


	/**
	* Store a newly created resource in storage.
	*
	* @return Response
	*/
	public function bookSupport(Request $request)	{

		if (!$request->input('text')) {
			return $this->MattermostHelper->sendResponse($message = "Job request was blank! Add some text next time eg. \"/book blah blah\""); // equivalent to no title check
		}

		/**
		* check we have more than 3 words
		*/
		if(count($this->MattermostHelper->getWords(" ", $request->input('text'))) <= 3) {
			return $this->MattermostHelper->sendEnhancedResponse("Your job request (excluding markdown) \"" . $request->input('text') . "\" is not long enough, add more words please (4 words min)", true, "ephemeral");
		}
		else {

			// getAllDefaultBookingsData

			// 'client'        => "",
			// 'client_name'   => "",
			// 'client_type'   => "client",
			// 'title'         => "",
			// 'type'          => "support",
			// 'problem'       => "",
			// 'site_id'       => 53, //comp assistance
			// 'site_user_id'  => 53, // Main User
			// 'severity_id'   => 2, // normal

			$data = $this->MattermostHelper->getAllDefaultBookingsData();

			$message="";
			$messageEnd ="";
			$errorMessage ="";

			/** default in helper class
			*	'user'        => false,
			*	'client'      => false,
			*	'title'       => false,
			*	'problem'     => false,*/
			$controls = $this->MattermostHelper->processInput($request->input('text'));


			// login user logged in on mattermost - defaults to administrator if no one is logged in
			$this->MattermostHelper->loginAuthUser($request);


			/************ client ************/
			$clientData = $this->MattermostHelper->getClientData($controls['client']); // defaults to computer assistance

			if(array_key_exists('error', $clientData)) {
				$errorMessage .= $clientData['error'];
			}


			if ($clientData) {
				$client = $clientData['client'];
				$data['client'] = $client;
				$data['client_id'] = $client->id;
				$data['client_name'] = $client->name;
			} // else uses default values - computer assistance


			/************ user ************/
			$userData = $this->MattermostHelper->getUserData($controls['user']);

			if(array_key_exists('error', $userData)) {
				$errorMessage .= $userData['error'];
			}

			if ($userData['user']) {
				$data['assigned_to'] = $userData['user']->id; // if no @user then returns false which puts job in queue
			}
			else {
				$data['assigned_to'] = $userData['user']; // at this point user is false = queue
			}


			/************ title ************/
			if ($controls['title']) {
				$data['title'] =  $controls['title']; // if no @user then returns false which puts job in queue
			}


			/************ problem ************/
			if ($controls['problem']) {
				$data['problem'] = $controls['problem'];
			}


			/************ site id ************/
			if ($client->sites[0]->id){
				$data['site_id'] = $client->sites[0]->id;
			}
			else {
				return response()->json(['success' => false, 'errors' => ['Site not found!']], 400);
			}


			/************ site user id ************/
			if ($client->sites[0]->users[0]->id){
				$data['site_user_id'] = $client->sites[0]->users[0]->id;
			}
			else {
				return response()->json(['success' => false, 'errors' => ['Site user not found!']], 400);
			}


			/************ status - assign a default status ************/
			$status = Status::query()->repairs()->first();
			if (! $status) {
				return response()->json(['success' => false, 'errors' => ['No statuses defined']], 400);
			}
			else {
				$data['status_id'] = $status->id;
			}

			/**
			* at this point we should be able to create a support ticket using user supplied data or defaults
			*/
			$task = Task::create($data);

			if (! $task->id) {
				return response()->json($task->errors->all(), 400);
			}
			else {
				return $this->MattermostHelper->makeJobBookedTable($task, $request->input('text'), $errorMessage, $client, $data);
			}
		}
	}


	public function showUsers(Request $request) {
		$data = new \stdClass;

		if ($request->input('text')) {

			$responseType = $this->MattermostHelper->setResponseType($request->input('text'));
			$userToSearchFor = $this->MattermostHelper->removeArrowControls($request->input('text'));

			$data->users = $this->MattermostHelper->userSearch($userToSearchFor);
			$data->responseType = $responseType;
			$data->searchTerm = $userToSearchFor;
		}
		else {

			$responseType = $this->MattermostHelper->getSingleDefaultSetting('responseType'); // defaul = ephemeral

			$data->users = $this->MattermostHelper->getAllUsers();
			$data->responseType = $responseType;
		}

		$user = $this->MattermostHelper->getAuthUserFromDatabase($request);
		$userExtension = $user ? $user->extension : false;

		if ($userExtension) {
			$data->userExtension = $userExtension;
		}

		if($data->users->count() > 0){
			return $this->MattermostHelper->makeUsersTable($data);
		}
		else{
			return $this->MattermostHelper->sendResponse("/users | " . $request->input('text') ." | User not found!");
		}
	}


	public function getClients(Request $request) {

		$clients = null;
		$user = $this->MattermostHelper->getAuthUserFromDatabase($request);
		$userExtension = $user ? $user->extension : false;

		if ($request->input('text')) {

			$responseType = $this->MattermostHelper->setResponseType($request->input('text')); // cannot set response on $puretext

			$pureText = $this->MattermostHelper->removeArrowControls($request->input('text'));

			if (strlen($pureText) > 0) { // $pureText contains search string

				$clientToSearchFor = $pureText;

				$clients = $this->MattermostHelper->clientSearch($clientToSearchFor);
				$clients->searchTerm = $clientToSearchFor;
				$clients->responseType = $responseType;

				if($userExtension){
					$clients->userExtension = $userExtension;
				}
			}
			else {
				// show all
				$responseType = $this->MattermostHelper->getSingleDefaultSetting('responseType'); // defaul = ephemeral

				$clients = $this->MattermostHelper->getAllClients();
				$clients->responseType = $responseType;

				if($userExtension){
					$clients->userExtension = $userExtension;
				}
			}
		}
		else {
			// show all
			$responseType = $this->MattermostHelper->getSingleDefaultSetting('responseType'); // defaul = ephemeral

			$clients = $this->MattermostHelper->getAllClients();
			$clients->responseType = $responseType;

			if($userExtension){
				$clients->userExtension = $userExtension;
			}
		}

		if ($clients->count() > 0){
			return $this->MattermostHelper->makeClientsTable($clients);
		}
		else {
			return $this->MattermostHelper->sendEnhancedResponse("\"$clientToSearchFor\" | Client not found!", true, $responseType);
		}
	}


		function showHelpTable(Request $request) {

			$responseType = $this->MattermostHelper->setResponseType($request->input('text')); // check to see if >all is present
			$message = "/book help | flags | -h -> help | from this list ->  -u: list users | -c: list clients | -u blah: list users begining with blah | -c blah: list clients begining with blah";
			$text =
"
#### Slash Commands Help
| command | options | additional info |
|:-----:|:-------|:-----|
";

			$text = $text . "| /help | - | Shows this table | \n";
			$text = $text . "| /book | @, # &#124; | Book jobs >> @user > assign to a user : #client > for a client : (no markdown) > title : &#124; > problem |\n";
			$text = $text . "| /clients | search string | See clients >> blank > all clients : search string > search for client/s by name |\n";
			$text = $text . "| /users | search string | See users >> blank > all users : search string > search for user/s by name |\n";
			$text = $text . "| /support | open, my, @user | See support jobs >> blank > open jobs : my >  your jobs : @user > list @user's jobs |\n";
			$text = $text . "| /icinga | blank, all | See our monitoring board >> blank > only shows warnings that have not been acknowldeged : all > shows both acknowldeged and not acknowldeged |\n";
			$text = $text . "---";

			return $this->MattermostHelper->sendEnhancedResponse($text, true, $responseType);
		}

}