<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Language;
use App\Models\Translation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LanguageController extends Controller
{
    public function index()
    {
        $languages = Language::orderBy('sort_order')->orderBy('name')->get();

        // Calculează translation statistici
        foreach ($languages as $language) {
            $totalKeys = Translation::where('language_code', 'ro')->distinct('key')->count('key');
            $translatedKeys = Translation::where('language_code', $language->code)->count();
            $language->progress = $totalKeys > 0 ? round(($translatedKeys / $totalKeys) * 100) : 0;
        }

        return view('admin.settings.languages.index', compact('languages'));
    }

    public function create()
    {
        return view('admin.settings.languages.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'code' => 'required|string|max:10|unique:languages,code',
            'flag' => 'nullable|string|max:10',
            'is_active' => 'boolean',
            'sort_order' => 'integer'
        ]);

        $language = Language::create($validated);

        return redirect()->route('settings.languages.index')
            ->with('success', 'Limba a fost adăugată cu succes!');
    }

    public function edit(Language $language)
    {
        return view('admin.settings.languages.edit', compact('language'));
    }

    public function update(Request $request, Language $language)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'code' => 'required|string|max:10|unique:languages,code,' . $language->id,
            'flag' => 'nullable|string|max:10',
            'is_active' => 'boolean',
            'sort_order' => 'integer'
        ]);

        $language->update($validated);

        return redirect()->route('settings.languages.index')
            ->with('success', 'Limba a fost actualizată cu succes!');
    }

    public function destroy(Language $language)
    {
        if ($language->is_default) {
            return back()->with('error', 'Nu poți șterge limba implicită!');
        }

        $language->delete();

        return redirect()->route('settings.languages.index')
            ->with('success', 'Limba a fost ștearsă cu succes!');
    }

    public function setDefault(Language $language)
    {
        DB::transaction(function () use ($language) {
            Language::where('is_default', true)->update(['is_default' => false]);
            $language->update(['is_default' => true, 'is_active' => true]);
        });

        return back()->with('success', 'Limba implicită a fost setată!');
    }

    public function toggleActive(Language $language)
    {
        if ($language->is_default) {
            return back()->with('error', 'Nu poți dezactiva limba implicită!');
        }

        $language->update(['is_active' => !$language->is_active]);

        return back()->with('success', 'Statusul limbii a fost actualizat!');
    }

    public function translations(Language $language)
    {
        $groups = Translation::where('language_code', $language->code)
            ->select('group')
            ->distinct()
            ->pluck('group');

        $translations = Translation::where('language_code', $language->code)
            ->orderBy('group')
            ->orderBy('key')
            ->get()
            ->groupBy('group');

        return view('admin.settings.languages.translations', compact('language', 'translations', 'groups'));
    }

    public function updateTranslations(Request $request, Language $language)
    {
        $validated = $request->validate([
            'translations' => 'required|array',
            'translations.*' => 'required|string'
        ]);

        foreach ($validated['translations'] as $id => $value) {
            Translation::where('id', $id)
                ->where('language_code', $language->code)
                ->update(['value' => $value]);
        }

        return back()->with('success', 'Traducerile au fost actualizate cu succes!');
    }

    public function importTranslations(Request $request, Language $language)
    {
        $request->validate([
            'file' => 'required|file|mimes:json'
        ]);

        $content = file_get_contents($request->file('file')->getRealPath());
        $data = json_decode($content, true);

        if (!$data) {
            return back()->with('error', 'Fișier JSON invalid!');
        }

        DB::beginTransaction();
        try {
            foreach ($data as $group => $translations) {
                foreach ($translations as $key => $value) {
                    Translation::updateOrCreate(
                        [
                            'language_code' => $language->code,
                            'group' => $group,
                            'key' => $key
                        ],
                        [
                            'value' => $value
                        ]
                    );
                }
            }
            DB::commit();
            return back()->with('success', 'Traducerile au fost importate cu succes!');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Eroare la importul traducerilor: ' . $e->getMessage());
        }
    }

    public function exportTranslations(Language $language)
    {
        $translations = Translation::where('language_code', $language->code)
            ->get()
            ->groupBy('group')
            ->map(function ($group) {
                return $group->pluck('value', 'key');
            });

        $filename = "translations_{$language->code}_" . date('Y-m-d') . ".json";

        return response()->json($translations, 200, [
            'Content-Type' => 'application/json',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"'
        ]);
    }
}
