<?php
namespace Dashboard\Services;

use Curl\Curl;
use Exception;
use Dashboard\Libs\Rcon\Rcon;
use Dashboard\Libs\Websend;
use Dashboard\Libs\Websender;

class CommandService
{
	public static function sendCommand(
		$consoleIP,
		$consolePort,
		$consolePassword,
		$consoleToken,
		$consoleType,
		$commands
	): bool
	{
		if ($consoleType == 1) {
			$console = new Websend($consoleIP, $consolePort);
			$console->password = $consolePassword;
		}
		else if ($consoleType == 2) {
			$console = new Rcon($consoleIP, $consolePort, $consolePassword);
		}
		else if ($consoleType == 3) {
			$console = new Websender($consoleIP, $consolePassword, $consolePort);
		}
		else if ($consoleType == 4) {
			$commands = array_column($commands, "logID");
			
			$curl = new Curl();
			$curl->setHeader('Content-Type', 'application/json');
			$curl->setHeader('Accept', 'application/json');
			$curl->post("https://connect-api.leaderos.net/api/socket/send-commands", [
				"apiKey"   => settings("apiKey"),
				"token"    => $consoleToken,
				"commands" => $commands,
			]);
			
			$status = !$curl->error && isset($curl->response->status) && $curl->response->status === true;
			if (!$status) {
				foreach ($commands as $commandLogID) {
					$updateCommandLog = db()->prepare("UPDATE CommandLogs SET status = ?, updatedAt = ? WHERE id = ?");
					$updateCommandLog->execute(array('error', datetime(), $commandLogID));
				}
			}
			
			return $status;
		}
		else {
			$console = new Websend($consoleIP, $consolePort);
			$console->password = $consolePassword;
		}
		
		// Check if the console is connected
		// If not, update the command logs to error status
		try {
			$console->connect();
		} catch (Exception $e) {
			foreach ($commands as $command) {
				if (isset($command["logID"])) {
					$updateCommandLog = db()->prepare("UPDATE CommandLogs SET status = ?, updatedAt = ? WHERE id = ?");
					$updateCommandLog->execute(array('error', datetime(), $command["logID"]));
				}
			}
			
			// Disconnect the console
			$console->disconnect();
			
			return false;
		}
		
		// If the console is connected successfully, send the commands
		foreach ($commands as $command) {
			try {
				$console->sendCommand($command["command"]);
				
				if (isset($command["logID"])) {
					$updateCommandLog = db()->prepare("UPDATE CommandLogs SET status = ?, updatedAt = ? WHERE id = ?");
					$updateCommandLog->execute(array('completed', datetime(), $command["logID"]));
				}
			} catch (Exception $e) {
				// If an error occurs while sending the command, update the command log to error status
				if (isset($command["logID"])) {
					$updateCommandLog = db()->prepare("UPDATE CommandLogs SET status = ?, updatedAt = ? WHERE id = ?");
					$updateCommandLog->execute(array('error', datetime(), $command["logID"]));
				}
			}
		}
		
		// Disconnect the console
		$console->disconnect();
		
		return true;
	}
}