* WolfPanel is licensed under a
 * Creative Commons Attribution-NonCommercial 4.0 International License.
 * 
 * You should have received a copy of the license along with this
 * work. If not, see <http://creativecommons.org/licenses/by-nc/4.0/>. 
 */
include "../core.php";
// Admin Check
$user = UserManager::getLocalUser();
if (!$user->isAdmin()) {
    PageManager::displayErrorPage("access");
    return;
}
$id = isset($_GET["serverid"]) && is_numeric($_GET["serverid"]) ? $_GET["serverid"] : -1;
$port = isset($_GET["port"]) && is_numeric($_GET["port"]) ? $_GET["port"] : -1;
if (!PhysicalServerManager::existsById($id)) {
    Page::renderJson(array("status" => "error", "message" => "Server doesnt exist"));
    return;
}
if ($port < Core::getConfig("port_min") || $port > Core::getConfig("port_max")) {
    Page::renderJson(array("status" => "error", "message" => "Invalid Port"));
    return;
}
$server = new PhysicalServer($id);
if ($server->isPortFree($port)) {
    Page::renderJson(array("status" => "success", "message" => "Port is available"));
    return;
} else {
    Page::renderJson(array("status" => "error", "message" => "Port is not available"));
    return;
}
 // Port
 $err = @Utils::checkInput($_POST['port'], "Port", 1, 64, INPUT_TYPE_NUMERIC);
 if (strlen($err) != 0) {
     if (strlen($_POST['port']) == 0) {
         $serverPort = $server->getRandomFreePort();
         if ($serverPort === false) {
             $error[] = "The given Server doesnt have any free port.";
         }
     } else {
         $error[] = $err;
     }
 } else {
     if (!Core::isValidPort($_POST['port'])) {
         $error[] = "The given port is not a valid port.";
     } else {
         if (!$server->isPortFree($_POST['port'])) {
             $error[] = "The given port isnt free.";
         } else {
             $serverPort = $_POST["port"];
         }
     }
 }
 // Template ID
 $err = @Utils::checkInput($_POST['templateid'], "Template ID", 1, 64, INPUT_TYPE_NUMERIC);
 if (strlen($err) != 0) {
     $error[] = $err;
 } else {
     if (!TemplateManager::existsById($_POST['templateid'])) {
         $error[] = "The given Template doesnt exist.";
     } else {
         $template = new Template($_POST['templateid']);