<?php

use api\classes\API_servers;

session_start();

require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API_servers.php";

$API_servers = new API_servers();

if (!$GLOBALS['modules_enabled']['servers']) {
    echo '405 Not Allowed';
    exit;
}

if ($API_servers->request_method === 'GET') {
    $API_servers->checkPermissions('servers', 'RO');

    $servers = $API_servers->getServers();

    $API_servers->apiOutput($code = 200, ['success' => $servers], '');
} elseif ($API_servers->request_method === 'POST') {
    $API_servers->checkPermissions('servers', 'RW');

    $requiredFields = [
        'server_vm_id' => ['type' => 'string'],
    ];

    $optionalFields = [
        'server_vm_host_id' => ['type' => 'string'],
        'server_vm_host_name' => ['type' => 'string'],
        'company_uuid' => ['type' => 'string'],
        'server_power_state' => ['type' => 'enum', 'values' => ['Running', 'Off']],
        'server_state' => ['type' => 'enum', 'values' => ['new', 'active', 'deleted', 'trial', 'disabled']],
        'server_hostname' => ['type' => 'string'],
        'server_os' => ['type' => 'string'],
        'server_cpu' => ['type' => 'int'],
        'server_memory' => ['type' => 'int'],
        'server_memory_demand' => ['type' => 'int'],
        'server_disks' => ['type' => 'json'],
        'server_ipv4' => ['type' => 'json'],
        'server_ipv6' => ['type' => 'json'],
        'server_vm_generation' => ['type' => 'int'],
        'server_vm_snapshot' => ['type' => 'int'],
        'server_licenses' => ['type' => 'json'],
        'server_backup' => ['type' => 'json'],
        'server_description' => ['type' => 'string'],
    ];

    if (isset($API_servers->postedData['servers'])) {
        // multiple servers are posted
        $allServers = $API_servers->postedData['servers'];

        foreach ($allServers as $server) {
            $API_servers->processServerData($server, $requiredFields, $optionalFields);
        }
    } else {
        // Single server update
        $API_servers->processServerData($API_servers->postedData, $requiredFields, $optionalFields);
    }

    $API_servers->apiOutput(200, ['success' => "Server(s) modified or updated successfully."]);
}