<?php

namespace App\Helpers;

class UrlHelper
{
    /** Panel base when APP_ENV=local (not read from .env). */
    private const LOCAL_PANEL_BASE_URL = 'http://www.localhost:5173';

    /**
     * Ngrok is opt-in: only when APP_ENV=local, NGROK_USE_WEBHOOK=true, and URL is set.
     * Production and staging never use ngrok.
     */
    public static function shouldUseNgrok(): bool
    {
        if (!app()->environment('local')) {
            return false;
        }

        if (!filter_var(env('NGROK_USE_WEBHOOK', false), FILTER_VALIDATE_BOOLEAN)) {
            return false;
        }

        return filled(env('NGROK_LINK_LOCAL_HOST'));
    }

    public static function isUsingNgrok(): bool
    {
        return self::shouldUseNgrok();
    }

    /**
     * Public base URL from the current hosting environment (request host, then APP_URL).
     */
    public static function getPublicBaseUrl(): string
    {
        if (self::shouldUseNgrok()) {
            return rtrim((string) env('NGROK_LINK_LOCAL_HOST'), '/');
        }

        if (!app()->runningInConsole()) {
            try {
                $request = request();
                if ($request) {
                    $root = rtrim($request->root(), '/');
                    if ($root !== '' && self::isAcceptableDetectedUrl($root)) {
                        return $root;
                    }
                }
            } catch (\Throwable) {
                // fall through to APP_URL
            }
        }

        return rtrim((string) config('app.url'), '/');
    }

    /**
     * Base URL for the React panel. Local: fixed dev URL (never ngrok / .env).
     * Production: live hosting URL from the request, then FRONTEND_URL.
     */
    public static function getFrontendBaseUrl(): string
    {
        if (app()->environment('local')) {
            return self::LOCAL_PANEL_BASE_URL;
        }

        $configured = rtrim((string) config('app.frontend_url', ''), '/');

        $detected = self::getPublicBaseUrl();

        if ($detected !== '') {
            return $detected;
        }

        return $configured !== '' ? $configured : $detected;
    }

    public static function getPanelBaseUrlSource(): string
    {
        $detected = self::getPublicBaseUrl();
        $used = self::getFrontendBaseUrl();

        if ($used === $detected) {
            return self::getUrlSource();
        }

        return 'frontend_url';
    }

    /**
     * Build an absolute URL for Telegram webhooks and external callbacks.
     */
    public static function getWebhookUrl(string $path = ''): string
    {
        $base = self::getPublicBaseUrl();

        return $path === ''
            ? $base
            : $base . '/' . ltrim($path, '/');
    }

    /**
     * How the public base was resolved (for panel diagnostics).
     */
    public static function getUrlSource(): string
    {
        if (self::shouldUseNgrok()) {
            return 'ngrok';
        }

        if (!app()->runningInConsole()) {
            try {
                $request = request();
                if ($request) {
                    $root = rtrim($request->root(), '/');
                    if ($root !== '' && self::isAcceptableDetectedUrl($root)) {
                        return 'request';
                    }
                }
            } catch (\Throwable) {
                //
            }
        }

        return 'app_url';
    }

    private static function isAcceptableDetectedUrl(string $root): bool
    {
        if (!app()->environment('local')) {
            return true;
        }

        $host = parse_url($root, PHP_URL_HOST) ?: '';

        return !in_array($host, ['localhost', '127.0.0.1', '::1'], true);
    }

    /**
     * Web panel deep link for a client (Telegram URL button).
     */
    public static function getPanelActionsUrl(string $uniqueId): string
    {
        return self::getFrontendBaseUrl() . '/panel/actions/' . $uniqueId;
    }

    /**
     * Inline keyboard row with a single URL button to the web panel.
     */
    public static function panelButtonKeyboard(string $uniqueId, string $label = 'Open panel'): array
    {
        return [
            [
                ['text' => $label, 'url' => self::getPanelActionsUrl($uniqueId)],
            ],
        ];
    }

    /**
     * Whether Telegram accepts this URL on an inline keyboard button (no localhost).
     */
    public static function isValidTelegramUrlButton(string $url): bool
    {
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            return false;
        }

        $scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));
        if (!in_array($scheme, ['http', 'https'], true)) {
            return false;
        }

        $host = strtolower((string) parse_url($url, PHP_URL_HOST));
        if ($host === '' || in_array($host, ['localhost', '127.0.0.1', '::1'], true)) {
            return false;
        }

        return true;
    }

    public static function panelLinkHtml(string $uniqueId, string $label = 'Open panel'): string
    {
        $url = htmlspecialchars(self::getPanelActionsUrl($uniqueId), ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $safeLabel = htmlspecialchars($label, ENT_QUOTES | ENT_HTML5, 'UTF-8');

        return "\n\n🔗 <a href=\"{$url}\">{$safeLabel}</a>";
    }
}
