<?php

namespace App\Modules\Settings\Localization\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Settings\Localization\DTOs\TranslationData;
use App\Modules\Settings\Localization\Models\Translation;
use App\Modules\Settings\Localization\Requests\StoreTranslationRequest;
use App\Modules\Settings\Localization\Requests\UpdateTranslationRequest;
use App\Modules\Settings\Localization\Services\LanguageService;
use App\Modules\Settings\Localization\Services\TranslationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class TranslationController extends Controller
{
    public function __construct(
        private readonly TranslationService $service,
        private readonly LanguageService $languageService,
    ) {}

    public function index(Request $request): View
    {
        $filters = $request->only(['group', 'locale', 'q']);

        return view('pages.settings.translations.index', [
            'translations' => $this->service->paginate($filters),
            'groups' => $this->service->groups(),
            'languages' => $this->languageService->all(),
            'filters' => $filters,
        ]);
    }

    public function create(): View
    {
        return view('pages.settings.translations.create', [
            'groups' => $this->service->groups(),
            'languages' => $this->languageService->all(),
        ]);
    }

    public function store(StoreTranslationRequest $request): RedirectResponse
    {
        $this->service->create(TranslationData::fromValidated($request->validated()));

        return redirect()
            ->route('settings.translations.index')
            ->with('status', __('translations.flash.created'));
    }

    public function edit(Translation $translation): View
    {
        return view('pages.settings.translations.edit', [
            'translation' => $translation,
            'groups' => $this->service->groups(),
            'languages' => $this->languageService->all(),
        ]);
    }

    public function update(UpdateTranslationRequest $request, Translation $translation): RedirectResponse
    {
        $this->service->update($translation, TranslationData::fromValidated($request->validated()));

        return redirect()
            ->route('settings.translations.index')
            ->with('status', __('translations.flash.updated'));
    }

    public function destroy(Translation $translation): RedirectResponse
    {
        $this->service->delete($translation);

        return redirect()
            ->route('settings.translations.index')
            ->with('status', __('translations.flash.deleted'));
    }
}
