<?php

namespace App\Livewire\Admin\Language;

use Livewire\Component;
use Livewire\Attributes\On;
use Livewire\Attributes\Url;
use Livewire\WithPagination;
use App\Models\Admin\Language;
use App\Models\Admin\LanguageVariables;

class ShowLanguageVariables extends Component
{
    use WithPagination;

    #[Url(as: 'q')]
    public $search = '';

    public $paginate = 25;

    public Language $language;

    public $editing = null;
    public $editableValue = '';

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

        $storedPaginate = session('paginate', $this->paginate);
        $this->paginate = $storedPaginate;
    }

    public function updatedPaginate($value)
    {
        session(['paginate' => $value]);
    }

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function changeStatus($id)
    {
        $variable = LanguageVariables::find($id);

        $variable->status = !$variable->status;
        $variable->save();

        activity()->performedOn($variable)->causedBy(auth()->id())->log('Dil değişkeni durumu düzenlendi');

        $this->dispatch('showAlert', [
            'title' => 'Başarılı!', 'text' => 'Dil değişkeni durumu başarıyla değiştirildi.', 'icon' => 'success'
        ]);
    }

    public function editValue($id)
    {
        $this->editing = $id;
        $variable = LanguageVariables::find($id);
        $this->editableValue = $variable->getTranslation('value', $this->language->short, false);
    }

    public function saveValue($id)
    {
        $variable = LanguageVariables::find($id);
        $variable->setTranslation('value', $this->language->short, $this->editableValue);
        $variable->save();

        $this->editing = null;

        activity()->performedOn($variable)->causedBy(auth()->id())->log('Dil değişkeni değeri güncellendi');

        $this->dispatch('showAlert', [
            'title' => 'Başarılı!', 'text' => 'Dil değişkeni değeri başarıyla güncellendi.', 'icon' => 'success'
        ]);
    }

    #[On('saveCompleted')]
    public function render()
    {
        $variables = LanguageVariables::orderByDesc('created_at')->search($this->search)->paginate($this->paginate);

        return view('livewire.admin.language.show-language-variables', [
            'variables' => $variables
        ]);
    }
}
