<?php
function checkIfUser(): bool
{
    if ($_SESSION['user']['user_group_type'] == 'user') {
        return true;
    } else {
        return false;
    }
}

function showTime($timestamp)
{
    if (empty($timestamp)) {
        return __('never');
    }

    try {
        $dt = new DateTime("@$timestamp");

        $timezone = $_SESSION['user']['user_timezone'] ?? 'UTC';
        $dt->setTimezone(new DateTimeZone($timezone));

        return $dt->format('Y-m-d H:i:s');

    } catch (DateInvalidTimeZoneException) {
        return __('invalid_date');
    }
}


function human_filesize($bytes, $decimals = 2): string
{
    $sizes = ['B', 'K', 'M', 'G', 'T', 'P']; // Array instead of string
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . $sizes[$factor];
}

function retrieveAvailableLocales(): array
{
    $availableLocales = array();
    $localeDir = $_SERVER['DOCUMENT_ROOT'] . "/bin/locales/";

    $localesInDir = array_diff(scandir($localeDir), array('.', '..'));
    foreach ($localesInDir as $localeFile) {
        if (pathinfo($localeFile, PATHINFO_EXTENSION) === 'php') {
            $availableLocales[] = basename($localeFile, '.php'); // Strip .php extension
        }
    }

    return $availableLocales;
}

function getPreferredLocale()

{
    $availableLocales = retrieveAvailableLocales();
    $defaultLocale = 'en';

    return in_array($_SESSION['user']['user_pref_language'], $availableLocales) ? $_SESSION['user']['user_pref_language'] : $defaultLocale;
}

function __(string $key, array $replacements = [])
{
    global $translations;

    $translation = $translations[$key] ?? $key;

    // Replace placeholders with dynamic values
    foreach ($replacements as $placeholder => $value) {
        $translation = str_replace(":$placeholder", $value, $translation);
    }

    return $translation;
}

function get_enabled_platforms($conn): array
{
    $platforms_enabled = [];
    $query = "SELECT * FROM autop_platforms WHERE platform_enabled = 1";

    if ($stmt = $conn->prepare($query)) {
        $stmt->execute();
        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {
            $platforms_enabled[$row['platform_uuid']] = [
                'data' => $row,
                'default_template_uuid' => false
            ];
        }
        $stmt->close();
    }
    return $platforms_enabled;
}

function getEnabledModules(): array
{
    $modules_enabled = [];
    $query = "SELECT * FROM system_modules";

    if ($stmt = $GLOBALS['conn']->prepare($query)) {
        $stmt->execute();
        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {
            $modules_enabled[$row['module_slugify']] = $row['module_enabled'];
        }
        $stmt->close();
    }
    return $modules_enabled;

}

function returnServerStateColor($serverState): string
{
    $server_state_color = 'secondary';
    if (strlen($serverState) > 0) {
        $server_state = ucfirst($serverState);
        switch ($server_state) {
            case 'New':
                $server_state_color = 'warning';
                break;
            case 'Deleted':
                $server_state_color = 'danger';
                break;
            case 'Trial':
                $server_state_color = 'primary';
                break;
            case 'Disabled':
                $server_state_color = 'gray';
                break;
            case 'Active':
                $server_state_color = 'success';
                break;
        }
    }
    return $server_state_color;
}