<?php

namespace App\Http\Controllers;

use App\Models\Translation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;

class TranslationController extends Controller
{
    public function index(Request $request) { $locale = $request->get('locale', 'fa'); abort_unless(in_array($locale, ['en', 'fa', 'ps']), 404); $search = $request->get('search'); $savedKeys = Translation::where('locale', $locale)->pluck('key'); $appKeys = $this->appTranslationKeys(); $missingKeys = $appKeys->diff($savedKeys)->when($search, fn ($keys) => $keys->filter(fn ($key) => str_contains(strtolower($key), strtolower($search))))->take(30)->values(); $translations = Translation::where('locale', $locale)->when($search, fn ($query, $term) => $query->where(fn ($q) => $q->where('key', 'like', "%{$term}%")->orWhere('value', 'like', "%{$term}%")))->orderBy('key')->paginate(20); return view('translations.index', ['locale' => $locale, 'translations' => $translations, 'search' => $search, 'missingKeys' => $missingKeys, 'totalKeys' => $appKeys->count(), 'savedCount' => $appKeys->intersect($savedKeys)->count()]); }
    public function store(Request $request) { $data = $request->validate(['locale' => ['required', 'in:en,fa,ps'], 'key' => ['required', 'string', 'max:150'], 'value' => ['required', 'string']]); Translation::updateOrCreate(['locale' => $data['locale'], 'key' => $data['key']], ['value' => $data['value']]); Cache::flush(); return back()->with('success', __('Translation saved.')); }
    public function destroy(Translation $translation) { $translation->delete(); Cache::flush(); return back()->with('success', __('Translation removed.')); }
    private function appTranslationKeys()
    {
        $files = collect([resource_path('views'), app_path('Http/Controllers'), base_path('routes')])
            ->filter(fn ($path) => File::exists($path))
            ->flatMap(fn ($path) => File::allFiles($path));

        return $files->flatMap(function ($file) {
            preg_match_all("/__\(\s*['\"]([^'\"]+)['\"]/", File::get($file->getPathname()), $matches);
            return $matches[1] ?? [];
        })->filter()->unique()->sort()->values();
    }
}
