<?php

namespace App\Livewire;

use App\Models\AppSetting;
use App\Support\ApplicationName;
use App\Support\LocaleOptions;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.app')]
class AdminSystemSettingsPage extends Component
{
    public array $draft = [
        'app_name' => 'Budgets',
        'support_email' => '',
        'maintenance_mode' => false,
        'default_currency' => 'EUR',
        'default_language' => 'en',
    ];

    public function mount(): void
    {
        $stored = AppSetting::query()->where('key', 'global')->value('value');
        if (is_array($stored)) {
            $this->draft = array_replace($this->draft, $stored);
        }
    }

    public function saveSettings(): void
    {
        $validated = $this->validate([
            'draft.app_name' => ['required', 'string', 'max:255'],
            'draft.support_email' => ['required', 'email', 'max:255'],
            'draft.maintenance_mode' => ['boolean'],
            'draft.default_currency' => ['required', 'string', 'max:8'],
            'draft.default_language' => ['required', Rule::in(LocaleOptions::available())],
        ]);

        AppSetting::query()->updateOrCreate(
            ['key' => 'global'],
            ['value' => $validated['draft']]
        );

        ApplicationName::forget();

        session()->flash('toast', (string) __('budgets.admin_console.system_saved'));
    }

    public function render()
    {
        return view('livewire.admin-system-settings-page')
            ->title((string) __('budgets.admin_console.system_title'));
    }
}
