<?php
if (!function_exists('ah_station_slug')) {
    function ah_station_slug(): string {
        return 'almostheaven';
    }
}

if (!function_exists('ah_auth_config_path')) {
    function ah_auth_config_path(): string {
        return 'C:/inetpub/Authentication/' . ah_station_slug() . '/auth_config.php';
    }
}

if (!function_exists('ah_api_config_path')) {
    function ah_api_config_path(): string {
        return 'C:/inetpub/Authentication/api/' . ah_station_slug() . '.php';
    }
}

if (!function_exists('ah_load_auth_config')) {
    function ah_load_auth_config(): array {
        $path = ah_auth_config_path();
        if (!file_exists($path)) {
            return [];
        }

        $config = require $path;
        return is_array($config) ? $config : [];
    }
}

if (!function_exists('ah_resolve_users_file')) {
    function ah_resolve_users_file(): string {
        $config = ah_load_auth_config();
        $candidates = [
            $config['users_file'] ?? null,
            $config['users_path'] ?? null,
            $config['user_file'] ?? null,
            $config['accounts_file'] ?? null,
            $config['json_file'] ?? null,
            $config['data_file'] ?? null,
        ];

        foreach ($candidates as $candidate) {
            if (is_string($candidate) && trim($candidate) !== '') {
                return str_replace('\\', '/', $candidate);
            }
        }

        return str_replace('\\', '/', dirname(ah_auth_config_path()) . '/users.json');
    }
}

if (!function_exists('ah_load_users')) {
    function ah_load_users(): array {
        $usersFile = ah_resolve_users_file();
        if (!file_exists($usersFile)) {
            return [];
        }

        $users = json_decode((string)file_get_contents($usersFile), true);
        return is_array($users) ? $users : [];
    }
}

if (!function_exists('ah_save_users')) {
    function ah_save_users(array $users): bool {
        $usersFile = ah_resolve_users_file();
        $dir = dirname($usersFile);
        if (!is_dir($dir)) {
            @mkdir($dir, 0775, true);
        }

        return file_put_contents($usersFile, json_encode(array_values($users), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) !== false;
    }
}

if (!function_exists('ah_verify_password')) {
    function ah_verify_password(string $inputPassword, $storedPassword): bool {
        if (!is_string($storedPassword) || $storedPassword === '') {
            return false;
        }

        $info = password_get_info($storedPassword);
        if (($info['algo'] ?? null) !== null && ($info['algo'] ?? 0) !== 0) {
            return password_verify($inputPassword, $storedPassword);
        }

        return hash_equals((string)$storedPassword, $inputPassword);
    }
}

if (!function_exists('ah_normalize_user_record')) {
    function ah_normalize_user_record(array $user): array {
        $user['role'] = $user['role'] ?? 'dj';
        $user['permissions'] = isset($user['permissions']) && is_array($user['permissions']) ? $user['permissions'] : [];
        return $user;
    }
}


if (!function_exists('ah_is_private_ip')) {
    function ah_is_private_ip(string $ip): bool {
        if ($ip === '' || $ip === '::1') return true;
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            $long = ip2long($ip);
            $ranges = [
                ['10.0.0.0', '10.255.255.255'],
                ['127.0.0.0', '127.255.255.255'],
                ['172.16.0.0', '172.31.255.255'],
                ['192.168.0.0', '192.168.255.255'],
            ];
            foreach ($ranges as [$start, $end]) {
                if ($long >= ip2long($start) && $long <= ip2long($end)) return true;
            }
        }
        return false;
    }
}

if (!function_exists('ah_is_local_env')) {
    function ah_is_local_env(): bool {
        $serverName = strtolower((string)($_SERVER['SERVER_NAME'] ?? ''));
        $httpHostRaw = (string)($_SERVER['HTTP_HOST'] ?? '');
        $httpHost = strtolower(preg_replace('/:\\d+$/', '', $httpHostRaw));
        $remoteAddr = (string)($_SERVER['REMOTE_ADDR'] ?? '');

        if (in_array($serverName, ['localhost', '127.0.0.1', '::1'], true)) return true;
        if (in_array($httpHost, ['localhost', '127.0.0.1', '::1'], true)) return true;
        if ($serverName !== '' && (str_contains($serverName, '.local') || !str_contains($serverName, '.'))) return true;
        if ($httpHost !== '' && (str_contains($httpHost, '.local') || !str_contains($httpHost, '.'))) return true;
        if (ah_is_private_ip($remoteAddr)) return true;
        if (filter_var($serverName, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) && ah_is_private_ip($serverName)) return true;
        if (filter_var($httpHost, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) && ah_is_private_ip($httpHost)) return true;

        return !file_exists(ah_auth_config_path());
    }
}
