<?php
	
	namespace Api\Libs\Rcon\Games;
	
	use Api\Libs\Rcon\BaseRcon;
	use Api\Libs\Rcon\IRcon;
	use Exception;
	
	class Unturned extends BaseRcon implements IRcon
	{
		/**
		 * @throws Exception
		 */
		public function connect(): void
		{
			$this->socket = fsockopen($this->host, $this->port, $errno, $errstr, 3);
			if (!$this->socket) {
				throw new Exception("Connection failed: " . $errstr);
			}
			
			fwrite($this->socket, "login " . $this->password . "\r\n");
			sleep(1);
			$response = $this->receive();
			
			if (strpos($response, "Invalid password") !== false) {
				throw new Exception("Invalid RCON password.");
			}
		}
		
		public function disconnect(): bool
		{
			try {
				fclose($this->socket);
			} catch (Exception $e) {
				return false;
			}
			
			return true;
		}
		
		public function checkConnection(): bool
		{
			try {
				$this->connect();
				$this->sendCommand('say "Test!"');
				$this->disconnect();
				return true;
			} catch (Exception $e) {
				return false;
			}
		}
		
		/**
		 * @throws Exception
		 */
		public function sendCommand(string $command, bool $response = false)
		{
			fwrite($this->socket, $command . "\r\n");
			sleep(1);
			if ($response) {
				$socketRes = $this->receive();
				if ($socketRes === false) {
					throw new Exception("Failed to read from socket.");
				}
				return trim($socketRes, "\x00");
			}
			return true;
		}
		
		private function receive(){
			return fread($this->socket, 1024);
		}
	}