<?php
if (!function_exists('ah_safe_return_url')) {
    function ah_safe_return_url(?string $candidate, string $fallback = '/index.php'): string {
        $candidate = trim((string)$candidate);
        if ($candidate === '') return $fallback;

        if (preg_match('#^https?://#i', $candidate)) {
            $parts = parse_url($candidate);
            $host = strtolower((string)($parts['host'] ?? ''));
            $current = strtolower((string)($_SERVER['HTTP_HOST'] ?? ''));
            if ($host === '' || ($current !== '' && $host !== $current)) {
                return $fallback;
            }
            $path = (string)($parts['path'] ?? '/');
            $query = isset($parts['query']) ? ('?' . $parts['query']) : '';
            return $path . $query;
        }

        if ($candidate[0] !== '/') {
            $base = rtrim(str_replace('\\', '/', dirname($_SERVER['PHP_SELF'] ?? '/')), '/');
            if ($base === '') $base = '/';
            $candidate = ($base === '/' ? '' : $base) . '/' . ltrim($candidate, '/');
        }

        if (strpos($candidate, '/admin/') === 0 || strpos($candidate, '/login/') === 0 || strpos($candidate, '/comments/') === 0 || strpos($candidate, '/requests/') === 0 || strpos($candidate, '/poll/') === 0 || strpos($candidate, '/about/') === 0 || strpos($candidate, '/djs/') === 0 || strpos($candidate, '/friends/') === 0 || strpos($candidate, '/news/') === 0 || strpos($candidate, '/schedule/') === 0 || strpos($candidate, '/top50/') === 0 || strpos($candidate, '/page.php') === 0 || strpos($candidate, '/index.php') === 0 || strpos($candidate, '/contact.php') === 0 || strpos($candidate, '/team.php') === 0 || strpos($candidate, '/events.php') === 0 || strpos($candidate, '/fans.php') === 0 || strpos($candidate, '/chat.php') === 0 || $candidate === '/') {
            return $candidate;
        }

        return $fallback;
    }
}

if (!function_exists('ah_redirect_back')) {
    function ah_redirect_back(string $fallback = '/index.php', array $params = []): void {
        $candidate = $_POST['return_to'] ?? $_GET['return_to'] ?? $_SERVER['HTTP_REFERER'] ?? $fallback;
        $target = ah_safe_return_url($candidate, $fallback);
        if (!empty($params)) {
            $parts = parse_url($target);
            $path = (string)($parts['path'] ?? $fallback);
            $query = [];
            if (!empty($parts['query'])) parse_str($parts['query'], $query);
            foreach ($params as $k => $v) $query[$k] = $v;
            $target = $path . (!empty($query) ? ('?' . http_build_query($query)) : '');
        }
        header('Location: ' . $target);
        exit;
    }
}
