<?php

namespace App\Http\Middleware;

use App\Http\Controllers\LanguageController;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Symfony\Component\HttpFoundation\Response;

class Language
{
    /**
     * Map of country codes to language codes
     */
    private array $countryToLanguageMap = [
        'CZ' => 'cz',  // Czech Republic
        'DE' => 'de',  // Germany
        'AT' => 'de',  // Austria (German)
        'DK' => 'dk',  // Denmark
        'ES' => 'es',  // Spain
        'MX' => 'es',  // Mexico (Spanish)
        'AR' => 'es',  // Argentina (Spanish)
        'FR' => 'fr',  // France
        'BE' => 'fr',  // Belgium (French/Dutch - defaulting to French)
        'GR' => 'gr',  // Greece
        'CY' => 'gr',  // Cyprus (Greek)
        'HU' => 'hu',  // Hungary
        'IT' => 'it',  // Italy
        'NL' => 'nl',  // Netherlands
        'PL' => 'pl',  // Poland
        'PT' => 'pt',  // Portugal
        'BR' => 'pt',  // Brazil (Portuguese)
        'RU' => 'ru',  // Russia
        'BY' => 'ru',  // Belarus (Russian)
        'KZ' => 'ru',  // Kazakhstan (Russian)
        'TR' => 'tr',  // Turkey
        'RO' => 'ro',  // Romania
        'MD' => 'ro',  // Moldova (Romanian)
        'GB' => 'en',  // United Kingdom
        'US' => 'en',  // United States
        'CA' => 'en',  // Canada
        'AU' => 'en',  // Australia
        'NZ' => 'en',  // New Zealand
        'IE' => 'en',  // Ireland
    ];

    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->session()->has('language')) {
            // Get the language from the session
            $language = $request->session()->get('language');

            // Set the language
            app()->setLocale($language);
        }
        // IP DETECTION DISABLED - uncomment below to re-enable after translations are complete
        /*
        else {
            // First visit - detect language from IP
            $detectedLanguage = $this->detectLanguageFromIp($request);

            if ($detectedLanguage) {
                // Set the detected language in session
                $request->session()->put('language', $detectedLanguage);
                app()->setLocale($detectedLanguage);
            }
        }
        */

        return $next($request);
    }

    /**
     * Detect language from user's IP address
     */
    private function detectLanguageFromIp(Request $request): ?string
    {
        $ip = $request->ip();

        // Skip detection for local/private IPs
        if ($this->isPrivateIp($ip)) {
            return null;
        }

        try {
            // Use ip-api.com for geolocation (free, no API key needed)
            // Limit: 45 requests per minute
            $response = Http::timeout(3)->get("http://ip-api.com/json/{$ip}?fields=status,countryCode");

            if ($response->successful()) {
                $data = $response->json();

                if ($data['status'] === 'success' && isset($data['countryCode'])) {
                    $countryCode = $data['countryCode'];

                    // Map country code to language code
                    if (isset($this->countryToLanguageMap[$countryCode])) {
                        $language = $this->countryToLanguageMap[$countryCode];

                        // Verify language is supported
                        if (in_array($language, LanguageController::$supportedLanguages)) {
                            return $language;
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            // Silently fail - don't break the site if geolocation fails
            logger()->warning('IP geolocation failed', [
                'ip' => $ip,
                'error' => $e->getMessage()
            ]);
        }

        return null;
    }

    /**
     * Check if IP is private/local
     */
    private function isPrivateIp(string $ip): bool
    {
        // Check for localhost, private networks, etc.
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false;
    }
}
