<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class LocalizationController extends Controller
{
    public function index(Request $request)
    {
        $locale = $request->get('locale', app()->getLocale());
        if (! in_array($locale, ['en', 'ps', 'fa'], true)) {
            $locale = 'en';
        }

        $file = lang_path($locale.'/app.php');
        $translations = File::exists($file) ? include $file : [];

        return view('localization.index', compact('locale', 'translations'));
    }

    public function update(Request $request)
    {
        $data = $request->validate([
            'locale' => ['required', 'in:en,ps,fa'],
            'translations' => ['required', 'array'],
        ]);

        $file = lang_path($data['locale'].'/app.php');
        $content = "<?php\n\nreturn ".var_export($data['translations'], true).";\n";
        File::ensureDirectoryExists(dirname($file));
        File::put($file, $content);

        return back()->with('success', __('app.updated_successfully'));
    }
}
