<?php

use api\classes\API;
use bin\php\Classes\pageNavbar;

if (!defined('APP_INIT')) {
    exit;
}

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

# Includes Section
require_once "{$_SERVER['DOCUMENT_ROOT']}/bin/php/Classes/pageNavbar.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API.php";

# Check permissions
$API = new API();
if (!$API->checkPermissions('servers', 'RO', true)) {
    echo 'error 401 unauthorized';
    exit;
}

# Page functions

# JS Scripts to load for this page
$jsScriptLoadData['/src/js/sentri/delete_confirmation.js'] = true;
$jsScriptLoadData['/src/js/sentri/breadCrumbs.js'] = true;
$jsScriptLoadData['codeblocks'] = true;
$jsScriptLoadData['/src/js/sentri/serverView.js'] = true;

# PageClasses Setup
$pageNavbar = new pageNavbar(true);

# Retrieve Information for the page
$server_uuid = htmlspecialchars($_GET['view'], ENT_QUOTES, 'UTF-8');
$stmt = $GLOBALS['conn']->prepare("SELECT * FROM servers WHERE server_uuid = ?");
$stmt->bind_param('s', $server_uuid);
$stmt->execute();
$result = $stmt->get_result();
$server_data = $result->fetch_assoc();

if ($GLOBALS['modules_enabled']['customers']) {
    $companies_data = $GLOBALS['conn']->query("SELECT company_uuid, company_name FROM companies WHERE company_state = 'active'");
    $companies = array();
    while ($company_data = $companies_data->fetch_assoc()) {
        $companies[] = $company_data;
    }
}

# Retrieve Information for the page
$user_groups_data = $GLOBALS['conn']->query("SELECT * FROM system_user_groups WHERE user_group_type = 'admin' ORDER BY user_group_weight DESC");


# memory
$mem = isset($server_data['server_memory']) ? (float)$server_data['server_memory'] : 0;
$demand = isset($server_data['server_memory_demand']) ? (float)$server_data['server_memory_demand'] : 0;
if ($mem > 0) {
    $mem_percent = ($demand / $mem) * 100;
    $mem_percent_numb = round($mem_percent, 1);
    $mem_demand = round($mem_percent, 1) . "%"; // round to 1 decimal place
    $mem_percent_sort = $mem_percent_numb;

    if ($mem_percent_numb <= 89) {
        $mem_demand_text_color = 'success';
    }
    if ($mem_percent_numb > 89) {
        $mem_demand_text_color = 'secondary';
    }
    if ($mem_percent_numb > 99) {
        $mem_demand_text_color = 'danger';
    }
} else {
    $mem_demand = "N/A";
    $mem_percent_numb = 'N/A';
    $mem_percent_sort = -1;
}

# disks
$disks = json_decode($server_data['server_disks'], true);
$totalDiskSpace = 0;
if (is_array($disks)) {
    foreach ($disks as $disk) {
        $totalDiskSpace += $disk['disk_space'];
    }
}

if (is_array($disks) && count($disks) > 0) {
    $sizes = array_column($disks, 'disk_space');
    $totalDiskSpace = array_sum($sizes);
}

$server_state_color = returnServerStateColor($server_data['server_state']);

# Licences
$licenses = json_decode($server_data['server_licenses'], true);

#

# OS Logo display
$baseos = strtolower(explode(' ', $server_data['server_os'])[0]);
$logos = [
        'almalinux' => 'almalinux',
        'centos' => 'centos',
];
$logo = $logos[$baseos] ?? 'server';

if ($API->checkPermissions('servers', 'RW', true)) {
    $pageNavbar->AddHTMLButton(
            '<form id="FormValidation" enctype="multipart/form-data" method="post" action="/api/v1/servers/">
        <input type="hidden" name="X-HTTP-Method-Override" value="POST">
        <input type="hidden" name="_return" value="/servers?view=' . $server_data['server_uuid'] . '">
        <input type="hidden" name="server_vm_id" value="' . $server_data['server_vm_id'] . '"/>' .
            (
            $server_data['server_state'] != 'deleted'
                    ? '<input type="hidden" name="server_state" value="deleted">
               <button class="btn btn-danger w-100">
                   <i class="fas fa-trash-alt"></i> Delete
               </button>'
                    : '<input type="hidden" name="server_state" value="disabled">
               <button class="btn btn-primary w-100">
                   <i class="fa-solid fa-clock-rotate-left"></i> Restore
               </button>'
            ) .
            '</form>'
    );
}

# Set breadcrumb data
$_SESSION['breadCrumbArray'][] = ['display' => __('server_overview'), 'href' => '/servers/'];
$_SESSION['breadCrumbArray'][] = ['display' => $server_data['server_vm_host_name'], 'href' => ''];

# Start page output
$pageNavbar->outPutNavbar();

?>
<div class="card">
    <div class="card-body">
        <div class="row">
            <h1>
                <i class="<?php echo $GLOBALS['pages']['servers']['server_overview']['page_icon'] ?>"> </i> <?php echo $server_data['server_vm_host_name'] ?>
                <span class="badge bg-<?php echo $server_state_color ?> fs-4 align-middle"><?php echo ucfirst($server_data['server_state']) ?></span>
            </h1>
        </div>


        <div class="row pb-5">
            <div class="col-md-3 col-lg-3">
                <h2><?php echo $server_data['server_os'] ?></h2>
                <img alt="os-logo" class="img-fluid os-logo" src="/src/images/os/<?php echo $logo ?>.svg">
            </div>

            <div class="col-lg-auto col-md-auto">
                <form id="FormValidation" enctype="multipart/form-data" method="post" action="/api/v1/servers/">
                    <table class="table table-borderless">
                        <input type="hidden" name="X-HTTP-Method-Override" value="POST">
                        <input type="hidden" name="_return" value="/servers?view=<?php echo $server_data['server_uuid'] ?>">
                        <input type="hidden" name="server_vm_id" value="<?php echo $server_data['server_vm_id'] ?>"/>
                        <tr>
                            <td>
                                <h4>
                                    <i class="fa-solid fa-microchip"></i> <?php echo __('server_cpu') ?>
                                </h4>
                            </td>
                            <td>
                                <h4>
                                    <?php echo (strlen($server_data['server_cpu']) > 0) ? $server_data['server_cpu'] . 'x' : ''; ?>
                                </h4>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <h4>
                                    <i class="fa-solid fa-memory"></i> <?php echo __('server_memory') ?>
                                </h4>
                            </td>
                            <td>
                                <h4>
                                    <?php echo (strlen($server_data['server_memory']) > 0) ? $server_data['server_memory'] . 'MB' : ''; ?>
                                </h4>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <h4>
                                    <i class="fa-solid fa-hard-drive"></i> <?php echo __('server_disks') ?>
                                </h4>
                            </td>
                            <td class="mx-3">
                                <h4>
                                    <?php
                                    if (is_array($disks) && count($disks) > 0) {
                                        if (count($sizes) === 1) {
                                            echo $sizes[0] . 'GB';
                                        } else {
                                            echo $totalDiskSpace . 'GB (' . implode('GB, ', $sizes) . 'GB)';
                                        }
                                    } ?>
                                </h4>
                            </td>
                        </tr>
                        <?php if ($GLOBALS['modules_enabled']['customers']) { ?>
                            <tr>
                                <td>
                                    <h4>
                                        <i class="fas fa-building"></i> <?php echo __('company') ?>
                                    </h4>
                                </td>
                                <td>
                                    <?php if ($API->checkPermissions('servers', 'RW', true)) { ?>


                                        <div class="input-group">
                                            <label for="company_uuid"></label>
                                            <select id="company_uuid" name="company_uuid" class="form-control">
                                                <option></option>
                                                <?php foreach ($companies as $company) { ?>
                                                    <option <?php echo ($server_data['company_uuid'] == $company['company_uuid']) ? 'selected' : '' ?> value="<?php echo $company['company_uuid'] ?>"><?php echo $company['company_name'] ?></option>
                                                <?php } ?>
                                            </select>
                                        </div>

                                    <?php } else { ?>
                                        <h4>
                                            <?php
                                            $companyMap = array_column($companies, 'company_name', 'company_uuid');
                                            echo $companyMap[$server_data['company_uuid']] ?? null;
                                            ?>
                                        </h4>
                                    <?php } ?>
                                </td>
                            </tr>
                        <?php } ?>
                        <tr>
                            <td>
                                <h4>
                                    <i class="fa-solid fa-circle-dot"></i> <?php echo __('server_state') ?>
                                </h4>
                            </td>
                            <td>
                                <?php if ($API->checkPermissions('servers', 'RW', true)) {
                                    if ($server_data['server_state'] != 'deleted') { ?>
                                        <div class="input-group">
                                            <label for="server_state"></label>
                                            <select id="server_state" class="form-control">
                                                <option></option>
                                                <option <?php echo ($server_data['server_state'] == 'active') ? 'selected' : '' ?> value="active">Active</option>
                                                <option <?php echo ($server_data['server_state'] == 'trial') ? 'selected' : '' ?> value="trial">Trial</option>
                                                <option <?php echo ($server_data['server_state'] == 'disabled') ? 'selected' : '' ?> value="disabled">Disabled</option>
                                            </select>
                                        </div>
                                    <?php } else { ?>
                                        <h4>
                                            <?php echo ucfirst($server_data['server_state']) ?>
                                        </h4>
                                    <?php }
                                } else { ?>
                                    <h4>
                                        <?php echo ucfirst($server_data['server_state']) ?>
                                    </h4>
                                <?php } ?>
                            </td>
                        </tr>

                        <tr>
                            <td>
                                <h4>
                                    <i class="fa-regular fa-clock"></i> <?php echo __('last_update') ?>
                                </h4>
                            </td>
                            <td>
                                <h4>
                                    <?php echo date('Y-m-d H:i:s', $server_data['server_modified_timestamp']) ?>
                                </h4>
                            </td>
                        </tr>
                        <?php if ($API->checkPermissions('servers', 'RW', true)) { ?>
                            <tr>
                                <td></td>
                                <td>
                                    <button class="btn btn-rounded btn-success w-100">
                                        <i class="fa-solid fa-floppy-disk"></i> <?php echo __('save') ?>
                                    </button>
                                </td>
                            </tr>
                        <?php } ?>
                    </table>
                </form>
            </div>
        </div>

        <?php if (is_array($disks) && count($disks) > 0) { ?>
            <h2 class="">
                <i class="fa-solid fa-hard-drive text-secondary"></i> <?php echo __('server_disks') ?>
            </h2>
            <div id="accordion">
                <div class="card">
                    <?php foreach ($disks as $i => $disk) {
                        $collapseId = 'collapseDisk' . $i; ?>
                        <a data-bs-toggle="collapse" data-bs-target="#collapse<?php echo $collapseId ?>">
                            <div class="card-header py-1" id="heading<?php echo $collapseId ?>">
                                <h4 class="mb-0">
                                    <i class="fa-solid fa-hard-drive text-secondary"></i> <?php echo $disk['disk_name'] ?>
                                </h4>
                            </div>
                        </a>

                        <div id="collapse<?php echo $collapseId ?>" class="collapse" data-parent="#accordion">
                            <div class="card-body">
                                <table class="table table-borderless table-sm">
                                    <tr>
                                        <td><?php echo __('disk_space') ?>:</td>
                                        <td><?php echo $disk['disk_space'] ?>GB</td>
                                    </tr>
                                    <tr>
                                        <td><?php echo __('disk_file_used') ?>:</td>
                                        <td><?php echo $disk['disk_used'] ?>GB</td>
                                    </tr>
                                    <tr>
                                        <td><?php echo __('disk_location') ?>:</td>
                                        <td><?php echo $disk['disk_location'] ?></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        <?php
                    } ?>
                </div>
            </div>
        <?php }


        if (is_array($licenses) && count($licenses) > 0) { ?>
            <h2>
                <i class="fa-solid fa-file-invoice-dollar text-success"></i> <?php echo __('server_licenses') ?>
            </h2>
            <div id="accordion">
                <div class="card">
                    <?php foreach ($licenses as $key => $licence) { ?>
                        <a data-bs-toggle="collapse" data-bs-target="#collapse<?php echo array_key_first($licence) ?>">
                            <div class="card-header py-1" id="heading<?php echo array_key_first($licence) ?>">
                                <h4 class="mb-0">
                                    <i class="fa-solid fa-file-invoice-dollar text-success"></i> <?php echo ucfirst(array_key_first($licence)) ?>
                                </h4>
                            </div>
                        </a>

                        <div id="collapse<?php echo array_key_first($licence) ?>" class="collapse" data-parent="#accordion">
                            <div class="card-body">
                                <?php echo __('type') . ': ' . end($licence) ?>
                            </div>
                        </div>
                        <?php
                    } ?>
                </div>
            </div>
        <?php } ?>

        <h1 class="pt-5"><?php echo __('all_technical_information') ?></h1>
        <div class="col-md-12 col-lg-12">
            <table class="table table-borderless table-sm table-responsive">
                <tr>
                    <td>server_uuid:</td>
                    <td class="w-100"><?php echo $server_data['server_uuid'] ?></td>
                </tr>
                <tr>
                    <td>company_uuid:</td>
                    <td><?php echo $server_data['company_uuid'] ?></td>
                </tr>
                <tr>
                    <td>server_vm_id:</td>
                    <td><?php echo $server_data['server_vm_id'] ?></td>
                </tr>
                <tr>
                    <td>server_vm_host_name:</td>
                    <td><?php echo $server_data['server_vm_host_name'] ?></td>
                </tr>
                <tr>
                    <td>server_vm_snapshot:</td>
                    <td><?php echo $server_data['server_vm_snapshot'] ?></td>
                </tr>
                <tr>
                    <td>server_vm_generation:</td>
                    <td><?php echo $server_data['server_vm_generation'] ?></td>
                </tr>
                <tr>
                    <td>server_power_state:</td>
                    <td><?php echo $server_data['server_power_state'] ?></td>
                </tr>
                <tr>
                    <td>server_state:</td>
                    <td><?php echo $server_data['server_state'] ?></td>
                </tr>
                <tr>
                    <td>server_hostname:</td>
                    <td><?php echo $server_data['server_hostname'] ?></td>
                </tr>
                <tr>
                    <td>server_os:</td>
                    <td><?php echo $server_data['server_os'] ?></td>
                </tr>
                <tr>
                    <td>server_cpu:</td>
                    <td><?php echo $server_data['server_cpu'] ?></td>
                </tr>
                <tr>
                    <td>server_memory:</td>
                    <td><?php echo $server_data['server_memory'] ?></td>
                </tr>
                <tr>
                    <td>server_memory_demand:</td>
                    <td><?php echo $server_data['server_memory_demand'] ?></td>
                </tr>
                <tr>
                    <td>server_disks:</td>
                    <td>
                        <pre class="bg-dark border rounded"><code class="language-json"><?= htmlspecialchars(json_encode(json_decode($server_data['server_disks']), JSON_PRETTY_PRINT)) ?></code></pre>
                    </td>
                </tr>
                <tr>
                    <td>server_ipv4:</td>
                    <td>
                        <pre class="bg-dark border rounded w-100 overflow-auto mb-0"><code class="language-json"><?= htmlspecialchars(json_encode(json_decode($server_data['server_ipv4']), JSON_PRETTY_PRINT)) ?></code></pre>
                    </td>
                </tr>
                <tr>
                    <td>server_ipv6:</td>
                    <td>
                        <pre class="bg-dark border rounded"><code class="language-json"><?= htmlspecialchars(json_encode(json_decode($server_data['server_ipv6']), JSON_PRETTY_PRINT)) ?></code></pre>
                    </td>
                </tr>
                <tr>
                    <td>server_licenses:</td>
                    <td>
                        <pre class="bg-dark border rounded"><code class="language-json"><?= htmlspecialchars(json_encode(json_decode($server_data['server_licenses']), JSON_PRETTY_PRINT)) ?></code></pre>
                    </td>
                </tr>
                <tr>
                    <td>server_backup:</td>
                    <td>
                        <pre class="bg-dark border rounded"><code class="language-json"><?= htmlspecialchars(json_encode(json_decode($server_data['server_backup']), JSON_PRETTY_PRINT)) ?></code></pre>
                    </td>
                </tr>
                <tr>
                    <td>server_description:</td>
                    <td><?php echo $server_data['server_description'] ?></td>
                </tr>
                <tr>
                    <td>server_create_timestamp:</td>
                    <td><?php echo $server_data['server_create_timestamp'] ?> (<?php echo date('Y-m-d H:i:s', $server_data['server_create_timestamp']) ?>)</td>
                </tr>
                <tr>
                    <td>server_modified_timestamp:</td>
                    <td><?php echo $server_data['server_modified_timestamp'] ?> (<?php echo date('Y-m-d H:i:s', $server_data['server_modified_timestamp']) ?>)</td>
                </tr>
            </table>
        </div>
    </div>
</div>
