<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MenuItem;
use App\Models\Page;
use App\Models\Setting;
use App\Services\TranslationService;
use Illuminate\Http\Request;

class MultilangController extends Controller
{
    public function __construct(
        protected TranslationService $translation
    ) {}

    public static function getAvailableLanguages(): array
    {
        return [
            'fr' => 'Français',
            'en' => 'English',
            'de' => 'Deutsch',
            'es' => 'Español',
            'it' => 'Italiano',
            'pt' => 'Português',
            'nl' => 'Nederlands',
        ];
    }

    public function settings()
    {
        $raw = Setting::get('multilang_languages', '["fr"]');
        $enabled = is_array($raw) ? $raw : json_decode($raw, true);
        if (! is_array($enabled)) {
            $enabled = ['fr'];
        }
        $defaultLocale = Setting::get('multilang_default', 'fr');
        $available = self::getAvailableLanguages();
        $translationAvailable = $this->translation->isAvailable();

        return view('admin.multilang.settings', compact('enabled', 'defaultLocale', 'available', 'translationAvailable'));
    }

    public function settingsStore(Request $request)
    {
        $available = array_keys(self::getAvailableLanguages());
        $enabled = array_values(array_intersect(
            (array) ($request->multilang_languages ?? []),
            $available
        ));
        if (empty($enabled)) {
            $enabled = ['fr'];
        }
        $defaultLocale = in_array($request->multilang_default ?? '', $enabled, true)
            ? $request->multilang_default
            : $enabled[0];

        Setting::set('multilang_languages', json_encode($enabled), 'multilang');
        Setting::set('multilang_default', $defaultLocale, 'multilang');

        return redirect()->route('admin.multilang.settings')->with('success', 'Paramètres enregistrés.');
    }

    public function translateAll(Request $request)
    {
        if (! $this->translation->isAvailable()) {
            return redirect()->route('admin.multilang.settings')->with('error', 'La traduction automatique n\'est pas disponible.');
        }

        set_time_limit(600);

        $raw = Setting::get('multilang_languages', '["fr"]');
        $enabled = is_array($raw) ? $raw : json_decode($raw, true);
        $defaultLocale = Setting::get('multilang_default', 'fr');
        $targetLocales = array_values(array_diff($enabled ?? [], [$defaultLocale]));

        if (empty($targetLocales)) {
            return redirect()->route('admin.multilang.settings')->with('info', 'Une seule langue est activée. Ajoutez d\'autres langues pour traduire.');
        }

        $delayMs = 80;

        $menuItems = MenuItem::orderBy('order')->get();
        foreach ($menuItems as $item) {
            $tr = $item->translations ?? [];
            foreach ($targetLocales as $locale) {
                $tr[$locale] = $this->translateWithDelay($item->label, $locale, $defaultLocale, $delayMs) ?? $item->label;
            }
            $item->update(['translations' => $tr]);
        }

        $pages = Page::where('is_published', true)->get();
        foreach ($pages as $page) {
            $tr = $page->translations ?? [];
            foreach ($targetLocales as $locale) {
                $title = $this->translateWithDelay($page->title, $locale, $defaultLocale, $delayMs) ?? $page->title;
                $content = $page->content ? ($this->translateWithDelay($page->content, $locale, $defaultLocale, $delayMs) ?? $page->content) : '';
                $sections = $this->translation->translateSections($page->sections ?? [], $locale, $defaultLocale, $delayMs);
                $tr[$locale] = ['title' => $title, 'content' => $content, 'sections' => $sections];
            }
            $page->update(['translations' => $tr]);
        }

        if (\App\Models\MarketplacePurchase::hasPurchased('plugin', 'reservation')) {
            $this->translateReservationServices($targetLocales, $defaultLocale, $delayMs);
        }

        $this->translateLangFiles($defaultLocale, $targetLocales, $delayMs);

        return redirect()->route('admin.multilang.settings')->with('success', 'Traduction terminée. Pages, menus et chaînes statiques traduits.');
    }

    protected function translateWithDelay(string $text, string $targetLocale, string $sourceLocale, int $delayMs): ?string
    {
        return $this->translation->translate($text, $targetLocale, $sourceLocale, $delayMs);
    }

    protected function translateReservationServices(array $targetLocales, string $defaultLocale, int $delayMs): void
    {
        $services = \App\Models\ReservationService::orderBy('order')->get();
        foreach ($services as $service) {
            $tr = $service->translations ?? [];
            foreach ($targetLocales as $locale) {
                $tr[$locale] = [
                    'name' => $this->translateWithDelay($service->name, $locale, $defaultLocale, $delayMs) ?? $service->name,
                    'description' => $service->description ? ($this->translateWithDelay(strip_tags($service->description), $locale, $defaultLocale, $delayMs) ?? $service->description) : '',
                ];
            }
            $service->update(['translations' => $tr]);
        }
    }

    protected function translateLangFiles(string $sourceLocale, array $targetLocales, int $delayMs = 0): void
    {
        $path = lang_path($sourceLocale.'.json');
        if (! is_file($path)) {
            $path = lang_path('fr.json');
        }
        if (! is_file($path)) {
            return;
        }
        $source = json_decode(file_get_contents($path), true);
        if (! is_array($source)) {
            return;
        }
        foreach ($targetLocales as $locale) {
            $out = [];
            foreach ($source as $key => $value) {
                if (is_string($value) && trim($value) !== '') {
                    $t = $delayMs > 0 ? $this->translateWithDelay($value, $locale, $sourceLocale, $delayMs) : $this->translation->translate($value, $locale, $sourceLocale);
                    $out[$key] = $t ?? $value;
                } else {
                    $out[$key] = $value;
                }
            }
            $file = lang_path($locale.'.json');
            file_put_contents($file, json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        }
    }
}
