<?php

namespace App\Livewire\User;

use App\Models\Language;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cookie;
use Livewire\Component;

class LocaleSettings extends Component
{
    public string $locale;

    public function mount(): void
    {
        $this->locale = auth()->user()->locale ?? App::getLocale();
    }

    public function updatedLocale(string $value): void
    {
        // Validate locale exists and is active
        $language = Language::where('code', $value)
            ->where('status', 'active')
            ->first();

        if (! $language) {
            $this->locale = App::getLocale();

            return;
        }

        // Update user preference
        auth()->user()->update(['locale' => $value]);

        // Store in session for immediate effect
        session(['locale' => $value]);

        // Set cookie as backup
        Cookie::queue('locale', $value, 60 * 24 * 30);

        // Update app locale
        App::setLocale($value);

        $this->dispatch('show-toast',
            type: 'success',
            message: __('user.language_updated')
        );

        // Refresh the page to apply translations
        $this->redirect(request()->header('Referer', route('profile')), navigate: true);
    }

    public function render()
    {
        return view('livewire.user.locale-settings', [
            'languages' => Language::where('status', 'active')
                ->orderBy('name')
                ->get(),
        ]);
    }
}
