<?php

namespace bin\php\Classes;

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

class serverOverviewBuilder
{
    public array $servers = [];

    public array $showColumns = array(
            'server_hostname' => false,
            'company_name' => false,
            'server_power_state' => false,
            'server_os' => false,
            'server_cpu' => false,
            'server_memory' => false,
            'server_memory_demand' => false,
            'server_disks' => false,
            'server_ipv4' => false,
            'server_ipv6' => false,
            'server_vm_snapshot' => false,
            'server_vm_generation' => false,
            'server_licenses' => false,
            'server_backup' => false,
            'server_description' => false,
            'server_modified_timestamp' => false,
    );

    public array $allBackupTypes = [];
    public array $allLicenseTypes = [];

    public bool $showDelBtn = true;
    public bool $showServerOverviewTitle = true;

    public bool $showCompanies = true;

    public function processServerData(): void
    {
        foreach ($this->servers as $server) {
            if (!empty($server['server_backup'])) {
                $backups = json_decode($server['server_backup'], true);
                if (is_array($backups)) {
                    foreach ($backups as $item) {
                        foreach ($item as $key => $value) {
                            $this->allBackupTypes[$key] = true;
                        }
                    }
                }
            }

            if (!empty($server['server_licenses'])) {
                $licenses = json_decode($server['server_licenses'], true);
                if (is_array($licenses)) {
                    foreach ($licenses as $item) {
                        foreach ($item as $key => $value) {
                            $this->allLicenseTypes[$key] = true;
                        }
                    }
                }
            }
        }

        $this->allBackupTypes = array_keys($this->allBackupTypes);
        sort($this->allBackupTypes);

        $this->allLicenseTypes = array_keys($this->allLicenseTypes);
        sort($this->allLicenseTypes);


        if (isset($_COOKIE['serverTableColumns'])) {
            $CheckedColumns = json_decode(htmlspecialchars(($_COOKIE['serverTableColumns']), true));
            foreach ($CheckedColumns as $CheckedColumn) {
                $this->showColumns[$CheckedColumn] = true;
            }
        } else {
            $this->showColumns['server_hostname'] = true;
            $this->showColumns['company_name'] = true;
            $this->showColumns['server_os'] = true;
            $this->showColumns['server_cpu'] = true;
            $this->showColumns['server_memory'] = true;
            $this->showColumns['server_memory_demand'] = true;
            $this->showColumns['server_disks'] = true;
            $this->showColumns['server_state'] = true;
            $this->showColumns['server_modified_timestamp'] = true;
        }
    }

    private function cleanNumber($num): string
    {
        // If integer value, return without formatting
        if (floor($num) == $num) {
            return (string)$num;
        }

        // Otherwise return trimmed float
        return rtrim(rtrim(number_format($num, 10, '.', ''), '0'), '.');
    }

    public function serverOverviewOutPut(): void
    { ?>
        <div class="form-group form-show-validation row mb-3">
            <?php if ($this->showServerOverviewTitle) { ?>
                <div class="col-auto">
                    <h2>
                        <i class="<?php echo $GLOBALS['pages']['servers']['server_overview']['page_icon'] ?>"></i> &nbsp; <?php echo __('server_overview') ?>
                    </h2>
                </div>
            <?php } ?>
            <div class="col d-flex justify-content-end px-1">
                <div class="selectgroup selectgroup-pills">
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_state" class="selectgroup-input" <?php echo($this->showColumns['server_state'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_state') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_hostname" class="selectgroup-input" <?php echo($this->showColumns['server_hostname'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_hostname') ?></span>
                    </label>
                    <?php if ($this->showCompanies) { ?>
                        <label class="selectgroup-item">
                            <input type="checkbox" name="value" value="company_name" class="selectgroup-input" <?php echo($this->showColumns['company_name'] ? 'checked=""' : '') ?>>
                            <span class="selectgroup-button"><?php echo __('company') ?></span>
                        </label>
                    <?php } ?>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_os" class="selectgroup-input" <?php echo($this->showColumns['server_os'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_os') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_cpu" class="selectgroup-input" <?php echo($this->showColumns['server_cpu'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_cpu') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_memory" class="selectgroup-input" <?php echo($this->showColumns['server_memory'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_memory') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_memory_demand" class="selectgroup-input" <?php echo($this->showColumns['server_memory_demand'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_memory_demand') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_disks" class="selectgroup-input" <?php echo($this->showColumns['server_disks'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_disks') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_ipv4" class="selectgroup-input" <?php echo($this->showColumns['server_ipv4'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_ipv4') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_ipv6" class="selectgroup-input" <?php echo($this->showColumns['server_ipv6'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_ipv6') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_vm_snapshot" class="selectgroup-input" <?php echo($this->showColumns['server_vm_snapshot'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_vm_snapshot') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_vm_generation" class="selectgroup-input" <?php echo($this->showColumns['server_vm_generation'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_vm_generation') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_licenses" class="selectgroup-input" <?php echo($this->showColumns['server_licenses'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_licenses') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_backup" class="selectgroup-input" <?php echo($this->showColumns['server_backup'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_backup') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_power_state" class="selectgroup-input" <?php echo($this->showColumns['server_power_state'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('server_power_state') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_modified_timestamp" class="selectgroup-input" <?php echo($this->showColumns['server_modified_timestamp'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('last_modified_date') ?></span>
                    </label>
                    <label class="selectgroup-item">
                        <input type="checkbox" name="value" value="server_description" class="selectgroup-input" <?php echo($this->showColumns['server_description'] ? 'checked=""' : '') ?>>
                        <span class="selectgroup-button"><?php echo __('description') ?></span>
                    </label>
                </div>
            </div>
            <?php if ($this->showDelBtn) { ?>
                <div class="col-lg-auto col-md-auto col-sm-auto">
                    <?php
                    if (!isset($_GET['del'])) { ?>
                        <a class="btn btn-danger btn-border" href="?del">
                            <i class="fa-solid fa-filter"></i> &nbsp; <?php echo __('show_del') ?>
                        </a>
                    <?php } else { ?>
                        <a class="btn btn-danger " href="/servers">
                            <i class="fa-solid fa-filter"></i> &nbsp; <?php echo __('show_del') ?>
                        </a>
                    <?php } ?>
                </div>
            <?php } ?>
        </div>

        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="multi-filter-select display table table-striped table-hover" data-skip-columns="action" data-page-length="50">
                        <thead>
                        <tr>
                            <th data-column="server_state"><?php echo __('server_state') ?></th>
                            <th data-column="server_hostname"><?php echo __('server_hostname') ?></th>
                            <?php if ($this->showCompanies) { ?>
                                <th data-column="company_name"><?php echo __('company') ?></th>
                            <?php } ?>
                            <th data-column="server_os"><?php echo __('server_os') ?></th>
                            <th data-column="server_cpu">
                                <i class="fa-solid fa-microchip"></i> <?php echo __('server_cpu') ?>
                            </th>
                            <th data-column="server_memory">
                                <i class="fa-solid fa-memory"></i> <?php echo __('server_memory') ?>
                            </th>
                            <th data-column="server_memory_demand"><?php echo __('server_memory_demand') ?></th>
                            <th data-column="server_disks">
                                <i class="fa-solid fa-hard-drive"></i> <?php echo __('server_disks') ?>
                            </th>
                            <th data-column="server_ipv4">
                                <?php echo __('server_ipv4') ?>
                            </th>
                            <th data-column="server_ipv6">
                                <?php echo __('server_ipv6') ?>
                            </th>
                            <th data-column="server_vm_snapshot"><?php echo __('server_vm_snapshot') ?></th>
                            <th data-column="server_vm_generation"><?php echo __('server_vm_generation') ?></th>
                            <?php
                            foreach ($this->allLicenseTypes as $licenseType) { ?>
                                <th data-column="server_licenses_<?php echo $licenseType ?>"><?php echo $licenseType ?></th>
                            <?php }
                            foreach ($this->allBackupTypes as $backupType) { ?>
                                <th data-column="server_backup_<?php echo $backupType ?>"><?php echo $backupType ?></th>
                            <?php }
                            ?>
                            <th data-column="server_power_state"><?php echo __('server_power_state') ?></th>
                            <th data-column="server_modified_timestamp"><?php echo __('last_modified_date') ?></th>
                            <th data-column="server_description"><?php echo __('description') ?></th>
                            <th data-column="action">
                                <?php echo __('action') ?>
                            </th>
                        </tr>
                        </thead>
                        <tfoot>
                        <tr>
                            <th data-column="server_state"><?php echo __('server_state') ?></th>
                            <th data-column="server_hostname"><?php echo __('server_hostname') ?></th>
                            <?php if ($this->showCompanies) { ?>
                                <th data-column="company_name"><?php echo __('company') ?></th>
                            <?php } ?>
                            <th data-column="server_os"><?php echo __('server_os') ?></th>
                            <th data-column="server_cpu"><?php echo __('server_cpu') ?></th>
                            <th data-column="server_memory"><?php echo __('server_memory') ?></th>
                            <th data-column="server_memory_demand"><?php echo __('server_memory_demand') ?></th>
                            <th data-column="server_disks"><?php echo __('server_disks') ?></th>
                            <th data-column="server_ipv4"><?php echo __('server_ipv4') ?></th>
                            <th data-column="server_ipv6"><?php echo __('server_ipv6') ?></th>
                            <th data-column="server_vm_snapshot"><?php echo __('server_vm_snapshot') ?></th>
                            <th data-column="server_vm_generation"><?php echo __('server_vm_generation') ?></th>
                            <?php
                            foreach ($this->allLicenseTypes as $licenseType) { ?>
                                <th data-column="server_licenses_<?php echo $licenseType ?>"><?php echo $licenseType ?></th>
                            <?php }
                            foreach ($this->allBackupTypes as $backupType) { ?>
                                <th data-column="server_backup_<?php echo $backupType ?>"><?php echo $backupType ?></th>
                            <?php }
                            ?>
                            <th data-column="server_power_state"><?php echo __('server_power_state') ?></th>
                            <th data-column="server_description"><?php echo __('description') ?></th>
                            <th data-column="action"><?php echo __('action') ?></th>
                        </tr>
                        </tfoot>
                        <tbody>

                        <?php
                        foreach ($this->servers as $server) {
                            $disks = json_decode($server['server_disks'], true);
                            $totalDiskSpace = 0;
                            if (is_array($disks)) {
                                foreach ($disks as $disk) {
                                    $totalDiskSpace += $disk['disk_space'];
                                }

                            }

                            if (is_null($server['server_hostname'])) {
                                $hostname = $server['server_vm_host_name'];
                            } else {
                                $hostname = $server['server_hostname'];
                            }

                            $mem = isset($server['server_memory']) ? (float)$server['server_memory'] : 0;
                            $demand = isset($server['server_memory_demand']) ? (float)$server['server_memory_demand'] : 0;

                            if ($mem == 0 && $demand == 0) {
                                $mem_assigned = 'N/A';
                                $mem_assigned_sort = 0;
                            } else {
                                $mem_assigned = $this->cleanNumber($mem) . "M";
                                $mem_assigned_sort = $this->cleanNumber($mem);
                            }

                            $mem_demand_text_color = '';
                            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 = 'warning';
                                }
                                if ($mem_percent_numb > 99) {
                                    $mem_demand_text_color = 'danger';
                                }

                            } else {
                                $mem_demand = "N/A";
                                $mem_percent_numb = 'N/A';
                                $mem_percent_sort = 0;
                            }

                            if ($server['server_cpu']) {
                                $server_cpu = htmlspecialchars($server['server_cpu']);
                                $server_cpu_sort = (int)$server_cpu;
                            } else {
                                $server_cpu = "N/A";
                                $server_cpu_sort = 0;
                            }

                            $ipv4_list = '';
                            if (!empty($server['server_ipv4'])) {
                                $ips = json_decode($server['server_ipv4'], true);
                                if (is_array($ips)) {
                                    $ipv4_list = implode(', ', $ips);
                                }
                            }

                            $ipv6_list = '';
                            if (!empty($server['server_ipv6'])) {
                                $ips = json_decode($server['server_ipv6'], true);
                                if (is_array($ips)) {
                                    $ipv6_list = implode(', ', $ips);
                                }
                            }

                            $thisServerLicenses = [];
                            foreach ($this->allLicenseTypes as $licenseType) {
                                $thisServerLicenses[$licenseType] = false;
                            }

                            if (!empty($server['server_licenses'])) {
                                $allLicenseTypesServer = json_decode($server['server_licenses'], true);
                                if (is_array($allLicenseTypesServer)) {
                                    foreach ($allLicenseTypesServer as $licenseTypeServer) {
                                        foreach ($licenseTypeServer as $licenseTypeServerKey => $licenseTypeServerValue) {
                                            $thisServerLicenses[$licenseTypeServerKey] = true;
                                        }
                                    }
                                }
                            }

                            $thisServerBackup = [];
                            foreach ($this->allBackupTypes as $BackupType) {
                                $thisServerBackup[$BackupType] = false;
                            }

                            if (!empty($server['server_backup'])) {
                                $allBackupTypesServer = json_decode($server['server_backup'], true);
                                if (is_array($allBackupTypesServer)) {
                                    foreach ($allBackupTypesServer as $BackupTypeServer) {
                                        foreach ($BackupTypeServer as $BackupTypeServerKey => $BackupTypeServerValue) {
                                            $thisServerBackup[$BackupTypeServerKey] = true;
                                        }
                                    }
                                }
                            }

                            if ($this->showCompanies) {
                                $company_name = '';
                                if (strlen($server['company_name']) > 0) {
                                    $company_name = $server['company_name'];
                                }
                            }

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

                            $server_modified_timestamp = ($server['server_modified_timestamp']) ? date('Y-m-d H:i:s', $server['server_modified_timestamp']) : __('never');

                            ?>

                            <tr data-item-id="<?php echo $server['server_uuid'] ?>">
                                <td data-column="server_state" class="text-nowrap" data-filter="<?php echo htmlspecialchars($server['server_state']); ?>" data-sort="<?php echo htmlspecialchars($server['server_state']); ?>">
                                    <span class="badge rounded-pill bg-<?php echo $server_state_color ?>"><?php echo $server['server_state'] ?></span>
                                </td>
                                <td data-column="server_hostname" class="text-nowrap" data-filter="<?php echo htmlspecialchars($hostname); ?>" data-sort="<?php echo htmlspecialchars($hostname); ?>">
                                    <i class="fa-solid fa-server"></i> <?php echo $hostname ?>
                                </td>
                                <?php if ($this->showCompanies) { ?>
                                    <td data-column="company_name" class="text-nowrap" data-filter="<?php echo $company_name ?>" data-sort="<?php echo $company_name ?>">
                                        <?php echo $company_name ?>
                                    </td>
                                <?php } ?>
                                <td data-column="server_os" class="text-nowrap"><?php echo $server['server_os'] ?></td>
                                <td data-column="server_cpu" class="text-nowrap" data-filter="<?php echo $server_cpu ?>" data-sort="<?php echo $server_cpu_sort ?>"><?php echo $server_cpu ?></td>
                                <td data-column="server_memory" class="text-nowrap" data-filter="<?php echo $mem_assigned; ?>" data-sort="<?php echo $mem_assigned_sort; ?>">
                                    <?php echo $mem_assigned ?>
                                </td>

                                <td data-column="server_memory_demand" class="text-nowrap <?php echo 'text-' . $mem_demand_text_color ?>" data-filter="<?php echo htmlspecialchars($mem_percent_numb); ?>" data-sort="<?php echo htmlspecialchars($mem_percent_sort); ?>">
                                    <?php echo $mem_demand ?>
                                </td>

                                <td data-column="server_disks" class="text-nowrap"
                                        <?php
                                        $sortValue = '';
                                        $filterValue = '';

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

                                            if ($totalDiskSpace > 0) {
                                                $sortValue = $totalDiskSpace;
                                                $filterValue = $totalDiskSpace;
                                            }
                                        }
                                        ?>
                                        data-sort="<?php echo htmlspecialchars($sortValue); ?>" data-filter="<?php echo htmlspecialchars($filterValue); ?>">
                                    <?php
                                    if (!empty($sortValue)) {
                                        if (count($sizes) === 1) {
                                            echo $sizes[0] . 'GB';
                                        } else {
                                            echo $totalDiskSpace . 'GB (' . implode('GB, ', $sizes) . 'GB)';
                                        }
                                    }
                                    ?>
                                </td>
                                <td data-column="server_ipv4" class="text-nowrap" data-sort="<?php echo htmlspecialchars($ipv4_list); ?>" data-filter="<?php echo htmlspecialchars($ipv4_list); ?>">
                                    <?php echo $ipv4_list ?>
                                </td>
                                <td data-column="server_ipv6" class="text-nowrap" data-sort="<?php echo htmlspecialchars($ipv6_list); ?>" data-filter="<?php echo htmlspecialchars($ipv6_list); ?>">
                                    <?php echo $ipv6_list ?>
                                </td>
                                <td data-column="server_vm_snapshot" class="text-nowrap" data-sort="<?php echo htmlspecialchars($server['server_vm_snapshot']); ?>" data-filter="<?php echo htmlspecialchars($server['server_vm_snapshot']); ?>">
                                    <?php echo $server['server_vm_snapshot']; ?>
                                </td>
                                <td data-column="server_vm_generation" class="text-nowrap" data-sort="<?php echo htmlspecialchars($server['server_vm_generation']); ?>" data-filter="<?php echo htmlspecialchars($server['server_vm_generation']); ?>">
                                    <?php echo $server['server_vm_generation']; ?>
                                </td>

                                <?php

                                foreach ($this->allLicenseTypes as $licenseType) { ?>
                                    <td data-column="server_license_<?php echo $licenseType ?>" class="text-nowrap" data-sort="<?php echo ($thisServerLicenses[$licenseType]) ? 'yes' : 'no' ?>" data-filter="<?php echo ($thisServerLicenses[$licenseType]) ? 'yes' : 'no' ?>"><?php echo ($thisServerLicenses[$licenseType]) ? '<i class="fa-solid text-success fa-toggle-on"></i>' : '<i class="fa-solid text-danger fa-toggle-off"></i>' ?></td>
                                <?php }
                                foreach ($this->allBackupTypes as $BackupType) { ?>
                                    <td data-column="server_backup_<?php echo $BackupType ?>" class="text-nowrap" data-sort="<?php echo ($thisServerBackup[$BackupType]) ? 'yes' : 'no' ?>" data-filter="<?php echo ($thisServerBackup[$BackupType]) ? 'yes' : 'no' ?>"><?php echo ($thisServerBackup[$BackupType]) ? '<i class="fa-solid text-success fa-toggle-on"></i>' : '<i class="fa-solid text-danger fa-toggle-off"></i>' ?></td>
                                <?php }
                                ?>
                                <td data-column="server_power_state" class="text-nowrap" data-filter="<?php echo htmlspecialchars($server['server_power_state']); ?>" data-sort="<?php echo htmlspecialchars($server['server_power_state']); ?>">
                                    <?php
                                    if ($server['server_power_state'] == 'Off') {
                                        echo '<i class="fa-solid text-danger fa-toggle-off"></i>';
                                    } elseif ($server['server_power_state'] == 'Running') {
                                        echo '<i class="fa-solid text-success fa-toggle-on"></i>';
                                    } ?>
                                </td>
                                <td data-column="server_modified_timestamp" class="text-nowrap" data-sort="<?php echo $server['server_modified_timestamp']; ?>" data-filter="<?php echo $server_modified_timestamp; ?>">
                                    <?php echo $server_modified_timestamp; ?>
                                </td>
                                <td data-column="server_description" class="text-nowrap" data-sort="<?php echo htmlspecialchars($server['server_description']); ?>" data-filter="<?php echo $server['server_description']; ?>">
                                    <?php echo $server['server_description']; ?>
                                </td>
                                <td>
                                    <a href="/servers?view=<?php echo $server['server_uuid'] ?>" class="btn btn-info btn-sm btn-rounded"><i class="fa-solid fa-eye"></i></a>
                                </td>
                            </tr>
                        <?php } ?>
                        </tbody>
                    </table>
                    <br>
                </div>
            </div>
        </div>

    <?php }
}