<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\TranslationManagerService;
use App\Traits\LogsAdminActivity;
use App\Traits\ValidatesFileUpload;
use Illuminate\Http\Request;

class LanguageManagerController extends Controller
{
    use LogsAdminActivity;
    use ValidatesFileUpload;

    public function __construct(private TranslationManagerService $translationService) {}

    public function index(Request $request)
    {
        $locale = $request->input('locale', 'en');
        $groups = $this->translationService->getGroups($locale);
        $group = $request->input('group', $groups[0] ?? null);

        $translations = $group ? $this->translationService->getTranslations($locale, $group) : [];
        $locales = TranslationManagerService::getSupportedLocales();

        return view('admin.language-manager.index', compact('locale', 'groups', 'group', 'translations', 'locales'));
    }

    public function save(Request $request)
    {
        $request->validate([
            'locale' => 'required|string|max:10',
            'group' => 'required|string',
            'key' => 'required|string',
            'value' => 'required|string',
        ]);

        $this->translationService->saveOverride($request->locale, $request->group, $request->key, $request->value);

        return response()->json(['success' => true]);
    }

    public function export(Request $request)
    {
        $locale = $request->input('locale', 'en');
        $data = $this->translationService->exportLocale($locale);

        return response()->json($data)
            ->header('Content-Disposition', "attachment; filename=\"translations-{$locale}.json\"");
    }

    public function import(Request $request)
    {
        // Hard size + mimes whitelist at validation layer (5 MB JSON).
        // The trait then does extension/MIME/null-byte/double-ext defence-in-depth.
        $request->validate([
            'locale' => 'required|string|max:10',
            'file'   => 'required|file|max:5120|mimes:json,txt',
        ]);

        $file = $request->file('file');

        $securityError = $this->validateUploadSecurity(
            $file,
            allowedExtensions: ['json'],
            allowedMimes: ['application/json', 'text/json', 'text/plain'],
        );
        if ($securityError) {
            return back()->with('error', $securityError);
        }

        // Magic-bytes sanity check: a translation export starts with '{'.
        $content = file_get_contents($file->getRealPath());
        if ($content === false || ltrim($content)[0] !== '{') {
            return back()->with('error', 'Invalid JSON file.');
        }

        $data = json_decode($content, true);

        if (! is_array($data)) {
            return back()->with('error', 'Invalid JSON file.');
        }

        $count = $this->translationService->importLocale($request->locale, $data);

        return back()->with('success', "Imported {$count} translations.");
    }
}
