<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
setlocale(LC_ALL, 'de_DE', 'de_DE.UTF-8');

class tanss
{

	private $tanssurl			= "https://tanss.vision4it.de/";
	private $token4devices		= "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJERVZJQ0VfTUFOQUdFTUVOVCIsImV4cCI6MTY3MjIxOTg2NSwidHlwZSI6IkRFVklDRV9NQU5BR0VNRU5UIn0.Z5_Lly9jBIBqO59cLL8TXOjULrKUtbf7OVamX0M7Y3_goduPO6sNmzKwmMHaEW9kiAMUSJn_J2XeJ_JVP_DkxuCLAwsKbDVXkyTK_txKXVgkyZ18niQIa4gAALn9QBKe6Cio2nN5Q6Wwo30lnZcg4AyuJ1cg_gJNFisxdWILF8w";
	//private $token4tanssx		= "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJUQU5TU19BUFAiLCJleHAiOjE2NzIyMTkyNzYsInR5cGUiOiJUQU5TU19BUFAifQ.REWqktC1irfeIY3QZL8YKelmqvHepmtpkJqm3O_gmSj0bVJWpPw1xF3mV1ICwLoLYm_oy7S6CB-Cxe6gHRHCCBVbr1uFbhpo5sk7cjuqFrfCOS6A5gc6a29vNLihnWXaGD3LwzsVgA7xqfUQVBxdofUbkfxOwAJUOjpzztG_Pus";
	private $token4monitor		= "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJNT05JVE9SSU5HIiwiZXhwIjoxNjc2NTQ4NzQ4LCJ0eXBlIjoiTU9OSVRPUklORyJ9.G1a85W2Gpgm72epAxioyjY4i-3bfxwMkyxGvSwcjAzjb8_bwArMPSdaTV7dJrO1MAJBhgXfhU-MICtcBFi8FMrOrd9t2WJGIgsLKPI2Bg7OYkEatS4b2mQGTggtA27b2FvoPIviPv6snL8CIPkO5-iOGBaDhIi0SW2BlY7goLss";
	private $token4phone        = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJQSE9ORSIsImV4cCI6MTY5MjM2NjU2NCwidHlwZSI6IlBIT05FIn0.ON4AnJi0uVUa7eFizkaEfITos1m4JyslZ2-TqTD7tN4aAw21-megGv7xwMIZxQOvHUVDSVoLuWbBQ1QW1iWxOgMdgds0d6vC99Z4iQ2ulLE7SQckmDzgA2Qx4f6BQ2_PqdcmdZa0pQ0JxcHb_xlaZptu7gtcMP52Bu9XRRrUUHg";
	//private $token4remoteSupports	= "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJSRU1PVEVfU1VQUE9SVCIsImV4cCI6MTY5Mjk2NTUyNCwidHlwZSI6IlJFTU9URV9TVVBQT1JUIiwiaW5mbyI6IjEwMDEifQ.nE19B7tJCnnUhIyHgE5NxyFHBj-RpSLWJ5bnM65KNMlfzHt47DfLFISSN7YuUHr3onYCIrwVAs9KyjBj03i4vRGmR8XmxizUbGtjmJkbRurO5XCBByYvJn0e1wxQKx_-YnAbPNtiyosiyH9TWktgHyVA4UVDUTnHRsmxD7k3nyU";
	private $token4remoteSupports	= "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJSRU1PVEVfU1VQUE9SVCIsImV4cCI6MTY5NzI5NDAxNiwidHlwZSI6IlJFTU9URV9TVVBQT1JUIiwiaW5mbyI6IjEwMDIifQ.nrZJR0_X2JY0-42EAfv9Fib4ZelGV0wh1iviKFjBxooGwNc5hbUGf4-5_IYYNaTh8Y5inOaxQMlFz3mj2QPiP85nsOeAC30F5_qW442IqnemntQrssd-WbCHxL2-ocl61iMWXMBPIja2BISu61-oXSWVT1WvMHyS0IFv_CFt718";
	private $headers4tickets	= "";
	private $headers4devices	= "";
	private $userheader			= "";
	public $logintoken			= "";
	public $loggedin			= false;
	public $username			= "";
	public $password			= "";
	public $employeeId			= 0;
	public $expire              = 0;
	protected $cookieFileLocation = './cookie.txt';
	private $client				= "";
	private $db                 = null;
	public $dbhost              = "10.7.50.52";
	public $dbuser				= "tanss_ro";
	public $dbpass				= "-QqZg)nTJa2)#";

	function __construct() 
	{
		$this->headers4tickets	= ["apiToken: ". $this->token4monitor  , "Content-Type: application/json"];
		$this->headers4devices	= ["apiToken: ". $this->token4devices  , "Content-Type: application/json"];
		$this->cookieFileLocation = dirname(__FILE__).'/cookie.txt';
		$this->client = new \GuzzleHttp\Client([ 'base_uri' => $this->tanssurl, 'debug'   => false, 'verify' => false , "Content-Type" => "application/json;charset=ISO-8859-1"]);
	}

	public function login($username,$password,$refreshToken="") 
	{
		if ($refreshToken=="") {
			$headers=["user"=> $username , "password" => $password ];
		} else {
			$headers=["user" => $username , "password" => $password, "logintoken" => $refreshToken];
		}
		$response = $this->client->request( 'GET', '/backend/api/v1/user/login',  ['headers' => $headers] );
		
		// Ergebnisse ermitteln
		$statuscode = $response->getStatusCode();
		$header = $response->getHeaders();
		$body = json_decode($response->getBody()->getContents());
		// Ergebnis Object bauen
		$ergobj = (object) ["statuscode" => $statuscode, "header" => $header, "body" => $body];

		if ($ergobj->statuscode == 200 && $ergobj->body->meta->text <> "Unsuccesful login attempt") {
			$this->logintoken = $ergobj->body->content->apiKey;
			$this->userHeader = ["apiToken" => $ergobj->body->content->apiKey];
			$this->username = $username;
			$this->password = $password;
			$this->employeeId = $ergobj->body->content->employeeId;
			$this->expire = $ergobj->body->content->expire;
			$retvalue = 200;
		} else {
			$this->logintoken = "";
			$this->username = "";
			$this->password = "";
			$this->userHeader = "";
			$this->employeeId =  0;
			$this->expire = 0;
			$retvalue = 403;
		}
		return $retvalue;
	}

	public function readsession(&$session)
	{
		$this->loggedin = $session['loggedin'];
		$this->logintoken = $session['id'];
		$this->userHeader = $session["userHeader"];
		$this->username = $session["username"];
		$this->password = $session["password"];
		$this->employeeId = $session["employeeId"];
		$this->expire = $session["expire"];
	}

	public function writesession(&$session)
	{
		$session['loggedin'] = $this->loggedin;
		$session['id'] = $this->logintoken;
		$session["userHeader"] = $this->userHeader;
		$session["name"] = $this->username;
		$session["password"] = $this->password;
		$session["employeeId"] = $this->employeeId;
		$session["expire"] = $this->expire;
	}

	public function ticketlist() 
	{
		try { 
			$response = $this->client->request( 'GET', '/backend/api/v1/tickets/own', ['headers' => $this->userHeader] ); 
			$statuscode = $response->getStatusCode();
			$header = $response->getHeaders();
			$body = json_decode($response->getBody()->getContents());
			$ergobj = (object) ["statuscode" => $statuscode, "header" => $header, "body" => $body];
			if ($ergobj->statuscode == 200) {
				$retvalue = $ergobj;
			} else { 
				$retvalue = (object)[];
			}
		} 
		catch (Exception $e) { 
			$retvalue = (object)[]; 
			echo "<pre>Fehler: "; 
			echo Psr7\Message::toString($e->getRequest());
			echo Psr7\Message::toString($e->getResponse());
			echo "</pre>";			
		}
		return $retvalue;
	}

	public function ticketlistAll() 
	{
		try { 
			$response = $this->client->request( 'GET', '/backend/api/v1/tickets/technician', ['headers' => $this->userHeader] ); 
			$statuscode = $response->getStatusCode();
			$header = $response->getHeaders();
			$body = json_decode($response->getBody()->getContents());
			$ergobj = (object) ["statuscode" => $statuscode, "header" => $header, "body" => $body];
			if ($ergobj->statuscode == 200) {
				$retvalue = $ergobj;
			} else { 
				$retvalue = (object)[];
			}
		} 
		catch (Exception $e) { 
			$retvalue = (object)[]; 
			echo "<pre>Fehler: "; 
			echo Psr7\Message::toString($e->getRequest());
			echo Psr7\Message::toString($e->getResponse());
			echo "</pre>";			
		}
		return $retvalue;
	}

	public function timestamp() 
	{
		try { 
			$response = $this->client->request( 'GET', '/backend/api/v1/timestamps', ['headers' => $this->userHeader] ); 
			$statuscode = $response->getStatusCode();
			$header = $response->getHeaders();
			$body = json_decode($response->getBody()->getContents());
			$ergobj = (object) ["statuscode" => $statuscode, "header" => $header, "body" => $body];
			if ($ergobj->statuscode == 200) {
				$retvalue = $ergobj;
			} else { 
				$retvalue = (object)[];
			}
		} 
		catch (Exception $e) { 
			$retvalue = (object)[]; 
			echo "<pre>Fehler: "; 
			echo Psr7\Message::toString($e->getRequest());
			echo Psr7\Message::toString($e->getResponse());
			echo "</pre>";			
		}
		return $retvalue;
	}

	public function settimestamp($state)
	{
		$body = [
			"employeeId" => $this->employeeId,
			"state" => strtoupper($state),
			"type" => "WORK",
			"date" => time(),
			"autoPause" => true
		];
		var_dump($body);
		try { 
			$response = $this->client->request( 'POST', '/backend/api/v1/timestamps', ['headers' => $this->userHeader, 'json' => $body, "query" => "autoPause=true" ] ); 
			$statuscode = $response->getStatusCode();
			$header = $response->getHeaders();
			$body = json_decode($response->getBody()->getContents());
			$ergobj = (object) ["statuscode" => $statuscode, "header" => $header, "body" => $body];
			if ($ergobj->statuscode == 201) {
				$retvalue = $ergobj;
			} else { 
				$retvalue = (object)[];
			}
		} 
		catch (Exception $e) 
		{ 
			$retvalue = (object)[]; 
			echo "<pre>Fehler: "; 
			echo Psr7\Message::toString($e->getRequest());
			echo Psr7\Message::toString($e->getResponse());
			echo "</pre>";			
		}
		return $retvalue;		
	}

	public function getCalls($employeeId = 0) 
	{
		$body = [
			"timeframe" => [
			  "from" => (time() - (12 * 60 * 60)) ,
			  "to" => time() 
			],
			"numberFilters" => [],
			"showTrysAsWell" => true,
			"employeeId"  => $employeeId ,
			"numberInfos" => true
		];

		try { 
			$response = $this->client->request( 
				'put', 
				'/backend/api/calls/v1', 
				['headers' => [ 
					"apiToken" => $this->token4phone, 
					"Content-Type" => "application/json"
				],
				'json' => $body ]
			); 
			$statuscode = $response->getStatusCode();
			$header = $response->getHeaders();
			$body = json_decode($response->getBody()->getContents());
			$ergobj = (object) ["statuscode" => $statuscode, "header" => $header, "body" => $body ];
			
			if ($ergobj->statuscode == 200) {
				$retvalue = $ergobj;
			} else { 
				$retvalue = (object)[];
			}
		} 
		catch (Exception $e) { 
			$retvalue = (object)[]; 
			echo "<pre>Fehler: "; 
			echo Psr7\Message::toString($e->getRequest());
			echo Psr7\Message::toString($e->getResponse());
			echo "</pre>";			
		}
		return $retvalue;
	}

	public function getChats($employeeId = 0) 
	{
		$body = [
			"employeeId"  => $employeeId ,
			"onlyExpectedTimeExpired" => false,
			"status" => "OPEN",
			"loadMessages" => "NONE",
			"showOnlyParticapatedChat" => true,
			"loadMessages" => "NONE"		
		];

		try { 
			$response = $this->client->request( 
				'PUT', 
				'/backend/api/v1/chats', 
				['headers' => [ "apiToken" => $this->userHeader	] , 
				'json' => $body ]
			); 
			$statuscode = $response->getStatusCode();
			$header = $response->getHeaders();
			$body = json_decode($response->getBody()->getContents());
			$ergobj = (object) ["statuscode" => $statuscode, "header" => $header, "body" => $body ];
			
			if ($ergobj->statuscode == 200) {
				$retvalue = $ergobj;
			} else { 
				$retvalue = (object)[];
			}
		} 
		catch (Exception $e) { 
			$retvalue = (object)[]; 
			echo "<pre>Fehler: "; 
			echo Psr7\Message::toString($e->getRequest());
			echo Psr7\Message::toString($e->getResponse());
			echo "</pre>";			
		}
		return $retvalue;
	}

	public function getTasks_API($employeeId = 0,$companyId = 0,$typeId = 0, $text = "") 
	{
		
		$from = new DateTime('today midnight');
		$to= new DateTime();
		$to->add(new DateInterval('P7D'));		
		$body = ["timeframe" => [ "from" => $from->getTimestamp(), "to" => $to->getTimestamp()] ];
		($employeeId>0) ? $body[] = ["employeeId"  => $employeeId] : null;
		($companyId>0) ? $body[] = ["companyId"  => $companyId] : null;
		($typeId>0) ? $body[] = ["typeId"  => $typeId] : ["typeId"  => 3];
		($text>0) ? $body[] = ["text"  => $text] : null;
		//print_r($body);

		try { 
			$response = $this->client->request( 
				'PUT', 
				'/backend/api/remoteSupports/v1', 
				['headers' => [ "apiToken" => $this->token4remoteSupports] , 
				'json' => $body ]
			); 
			$statuscode = $response->getStatusCode();
			$header = $response->getHeaders();
			$body = json_decode($response->getBody()->getContents());
			$ergobj = (object) ["statuscode" => $statuscode, "header" => $header, "body" => $body ];
			//var_dump($this->logintoken);
			if ($ergobj->statuscode == 200) {
				$retvalue = $ergobj;
			} else { 
				$retvalue = (object)[];
			}
		} 
		catch (Exception $e) { 
			$retvalue = (object)[]; 
			echo "<pre>Fehler: "; 
			echo Psr7\Message::toString($e->getRequest());
			echo Psr7\Message::toString($e->getResponse());
			echo "</pre>";			
		}
		
		return $retvalue;
	}

	public function timeDifference( $date_1, $date_2, $differenceFormat = "%m Monate %d Tage %H Stunden %i Minuten" )
	{
		$datetime1 = new DateTime();
		$datetime1->setTimestamp($date_1);
		$datetime2 = new DateTime();
		$datetime2->setTimestamp($date_2);
		$interval = $datetime1->diff($datetime2);
		return $interval->format($differenceFormat);
	}

	function openMysql() {
		$this->db = new PDO("mysql:host=".$this->dbhost.";charset=utf8;dbname=tanss", $this->dbuser, $this->dbpass, array(PDO::ATTR_PERSISTENT => false, PDO::ATTR_TIMEOUT => 5, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
	}

	public function getTasks($employeeId = 0) {
		$sql_termine = 'SELECT
			leistungen.ID,
			leistungen.datum as termin_start,
			leistungen.dauer*60+leistungen.datum as termin_ende,
			leistungen.dauer/60 as termin_dauer,
			leistungen.text as info,
			mitarbeiter.name as techniker,
			firmen.name as kunde,
			leistungen.tepID as typ
			FROM tanss.leistungen
			left outer join mitarbeiter on leistungen.mitarbeiterID = mitarbeiter.ID
			left outer join firmen on leistungen.firmenID = firmen.ID
			WHERE FROM_UNIXTIME(datum,"%Y-%m-%d") >= date(now())
			AND leistungen.tepID in (2,3)
			' . ( ($employeeId>0) ? "AND mitarbeiter.ID = ".$employeeId : "" ). '
			ORDER BY datum ASC 
		';
		// Verbindung öffnen
		$this->openMysql();
		// SQL ausführen: Termine
		$datasql = $this->db->query($sql_termine, PDO::FETCH_ASSOC);
		$data_termine = $datasql->fetchAll(PDO::FETCH_OBJ);
		//$dbcount_termine = $datasql->rowCount();
		// Verbindung schließen
		$this->db = null;
		return $data_termine;
	}
}