<?php

namespace App\Livewire\Admin\Translations\Modals;

use App\Models\Translation;
use LivewireUI\Modal\ModalComponent;

class EditModal extends ModalComponent
{
    public $key;
    public $values = [];

    public function mount($key = null)
    {
        $this->key = $key;

        foreach (config('app.locales') as $code => $label) {

            $this->values[$code] = Translation::where('key', $key)
                ->where('locale', $code)
                ->value('value') ?? '';
        }
    }

    public function save()
    {
        if (!$this->key) {
            $this->addError('key', 'Key erforderlich');
            return;
        }

        foreach ($this->values as $locale => $value) {

            Translation::updateOrCreate(
                [
                    'key' => $this->key,
                    'locale' => $locale,
                ],
                [
                    'value' => $value
                ]
            );
        }

        $this->dispatch('translations:updated');

        $this->closeModal();
    }

    public function render()
    {
        return view('livewire.admin.translations.modals.edit-modal');
    }
}
