<?php

/**
 * SSO Utility Functions
 * 
 * Shared utility functions used across SSO modules
 * 
 * @package SSO
 */

// Helper to log SSO errors
function log_sso($message, $level = 'error') {
    $logfile = get_root_dir() . '/var/components/sso_integration.log';
    $timestamp = date('Y-m-d H:i:s');
    $level = strtoupper($level);
    $entry = "[$timestamp] SSO: $level: $message\n";
    file_put_contents($logfile, $entry, FILE_APPEND | LOCK_EX);
}

// Validate group size and return configuration mode
function validate_group_size($member_count) {
    $MAX_GROUP_SIZE = 1000; // Maximum users per group for individual configuration
    $WARNING_GROUP_SIZE = 500; // Show warning at this size
    $LARGE_GROUP_SIZE = 5000; // Force shared account mode
    $DISABLED_GROUP_SIZE = 50000; // Completely disable selection
    
    if ($member_count >= $DISABLED_GROUP_SIZE) {
        return [
            'mode' => 'disabled',
            'warning' => "This group has " . number_format($member_count) . " users and is too large for SSO configuration. Please contact your administrator to subdivide this group.",
            'can_configure' => false,
            'recommended_mode' => 'none'
        ];
    } else if ($member_count >= $LARGE_GROUP_SIZE) {
        return [
            'mode' => 'shared',
            'warning' => "This group has " . number_format($member_count) . " users. Only shared account mode is available. Individual user configuration is not supported for groups this large.",
            'can_configure' => true,
            'recommended_mode' => 'shared'
        ];
    } else if ($member_count >= $MAX_GROUP_SIZE) {
        return [
            'mode' => 'bulk',
            'warning' => "This group has " . number_format($member_count) . " users. Individual configuration is not recommended. Consider using shared account mode or subdividing the group.",
            'can_configure' => true,
            'recommended_mode' => 'bulk'
        ];
    } else if ($member_count >= $WARNING_GROUP_SIZE) {
        return [
            'mode' => 'individual',
            'warning' => "This group has " . number_format($member_count) . " users. Performance may be affected during configuration.",
            'can_configure' => true,
            'recommended_mode' => 'individual'
        ];
    } else {
        return [
            'mode' => 'individual',
            'warning' => null,
            'can_configure' => true,
            'recommended_mode' => 'individual'
        ];
    }
}

function get_php_version()
{
    $php_version = phpversion();
    echo json_encode(array('status' => 'success', 'data' => $php_version));
    exit();
}

function get_callback_url()
{
    $base_url = get_base_url();
    $callback_url = $base_url . 'includes/components/oauth2/sso-aad-authcodeflow.php';
    echo json_encode(array('data' => $callback_url));
    exit();
}

function get_sso_method()
{
    $method = get_option('sso_login_method', 'select_account');
    echo json_encode(array('status' => 'success', 'data' => $method));
    exit();
}

function set_sso_method()
{
    $method = grab_request_var('method', '');
    set_option('sso_login_method', $method);
    echo json_encode(array('status' => 'success', 'message' => 'Successfully set SSO login method.'));
    exit();
}

function get_max_user_id()
{
    $users = get_users();
    $max_id = 0;
    foreach ($users as $user) {
        if ($user['user_id'] > $max_id) {
            $max_id = $user['user_id'];
        }
    }
    echo json_encode(array('status' => 'success', 'data' => $max_id));
    exit();
}

function get_assorted_user_settings()
{
    try {
        $languages = get_languages();
        $languagesHReadable = array();
        foreach ($languages as $lang) {
            $languagesHReadable[] = get_language_nicename($lang);
        }
        $date_formats = get_date_formats();
        $number_formats = get_number_formats();
        $week_formats = get_week_formats();
        $auth_levels = get_authlevels();
        $core_config_manager_access = [0 => 'None', 1 => 'Login', 2 => 'Limited', 3 => 'Full'];
        echo json_encode(array(
            'data' => [
                'status' => 'success',
                'language_keys' => $languages,
                'languages' => $languagesHReadable,
                'date_formats' => $date_formats,
                'number_formats' => $number_formats,
                'week_formats' => $week_formats,
                'auth_levels' => $auth_levels,
                'core_config_manager_access' => $core_config_manager_access
            ]
        ));
        exit();
    } catch (Exception $e) {
        echo json_encode(array('status' => 'error', 'message' => 'Failed to get assorted user settings.'));
        exit();
    }
}

function get_users_XI()
{
    $usersXI = get_users();
    $return_users = array();
    foreach ($usersXI as $user) {
        // Include all users, but mark enabled status
        $return_users[] = array(
            'user_id' => $user['user_id'],
            'username' => $user['username'],
            'name' => $user['name'],
            'email' => $user['email'],
            'enabled' => ($user['enabled'] == "1") ? true : false
        );
    }
    // remove nagiosadmin from the list
    $return_users = array_values(array_filter($return_users, function ($user) {
        return $user['username'] !== 'nagiosadmin';
    }));
    echo json_encode(array('status' => 'success', 'data' => $return_users));
    exit();
}

function authenticate_user_AAD()
{
    header('Location: /nagiosxi/includes/components/oauth2/sso-aad-authcodeflow.php');
    exit();
}

function normalize_boolean_flag($value)
{
    if (is_bool($value)) {
        return $value ? 1 : 0;
    }

    if (is_numeric($value)) {
        return ((int)$value) ? 1 : 0;
    }

    if (is_string($value)) {
        $value = strtolower(trim($value));
        return in_array($value, array('1', 'true', 'yes', 'on'), true) ? 1 : 0;
    }

    return $value ? 1 : 0;
}

/**
 * Sanitize username/contact name for Nagios XI compatibility
 * Removes illegal characters that are not allowed in Nagios Core contact names
 * and ensures the result is safe for use as a username or contact name.
 * 
 * Illegal characters: ` ~ ! $ % ^ & * | ' < > ? , = " ( )
 * 
 * @param string $username The username/name to sanitize
 * @param string $fallback Fallback value if sanitization results in empty string (default: 'SSO User')
 * @param bool $log_changes Whether to log when sanitization changes the input (default: true)
 * @return string Sanitized username safe for Nagios XI
 */
function sanitize_username_for_nagios($username, $fallback = 'SSO User', $log_changes = true)
{
    if (empty($username) || !is_string($username)) {
        return $fallback;
    }
    $original = $username;
    
    // Remove illegal characters (same pattern as admin/users.php)
    // Pattern: ` ~ ! $ % ^ & * | ' < > ? , = " ( )
    $illegal_chars = "/[`~!$%^&*|'<>?,=\"\(\)]/";
    $sanitized = preg_replace($illegal_chars, '', $username);
    $sanitized = preg_replace('/\s+/', ' ', $sanitized);
    $sanitized = trim($sanitized, " \t\n\r\0\x0B-");
    if (empty($sanitized)) {
        if ($log_changes) {
            log_sso('sanitize_username_for_nagios: Username "' . $original . '" was completely sanitized away, using fallback: "' . $fallback . '"', 'warning');
        }
        return $fallback;
    }
    if ($log_changes && $sanitized !== $original) {
        log_sso('sanitize_username_for_nagios: Sanitized username from "' . $original . '" to "' . $sanitized . '"', 'info');
    }
    return $sanitized;
}


